vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx
WelcometotheFourthEditionoftheVBPJTechnicalTipsSupplement!ThesetipsandtricksweresubmittedbyprofessionaldevelopersusingVisualBasic3.0,VisualBasic4.0,VisualBasicforApplications,andVisualBasicScript.ThetipswerecompiledbytheeditorsatVisualBasicProgrammer,sJournal.SpecialthankstoVBPJTechnicalReviewBoardmembersDougHaynes,KarlE.Peterson,andPhilWeberfortestingallthecode.Ifyou,dliketosubmitatiptoVisualBasicProgrammer,sJournal,pleasesendittoUserTips,FawcetteTechnicalPublications,209HamiltonAvenue,PaloAlto,California,USA,94301-2500.Youcanalsofaxitto415-853-0230orsenditelectronicallytovbpjedil.Pleaseincludeaclearexplanationofwhatthetechniquedoesandwhyitisuseful,indicateifit,sforVBA,VBS,VB3,orVB4,16-or32-bitversion.Pleasetrytolimitlimitcodelengthto20lines.Do11,tforgettoincludeyoure-mailandmailingaddresses.We,11payyou$25ifwepublishyourtip.VB3,VB416/321.evel:BeginningEasyCR/1.FPaddingWhenIwritetextinmessageboxes,labels,andsoon,and1needtoincludeacarriagereturn/1inefeed,Iusethisfunction,passingitthenumberofCR/1.FsIneed.ThissavesalotoftypingandlookingupofASCIIvalues:SubcmdDelete_Click()msg="Areyousureyouwant"_,todeletethisitem?”&N1.(2)&"Press0K”rc=MsgBox(msg,4+32+256,"ConfirmDelete*)endsubFunctionN1.(num_linesAsInteger)AsStringThisfunctionreturnsaNew1.inecharacterforthenumberoftimespassedtothefunction.*DimmsgsStringDimiAsIntegerFori=1Tonumlinesmsg=msg&Chr(13)&Chr(IO)NextN1.-msgEndFunction-BretCutler,1.ayton,UtahVB3,VB416/321.evel:BeginningAutoSelectTextBoxContentsUsersoftenfinditfastertoretypetheentirecontentsofatextboxratherthanpositionthecursorwithinthedata,andtheneditthedata.Thisisespeciallytrueifthelengthofthedataisshortorifthedataisn,tvisible,aswithapasswordfield,forexample.Doubleclickingorusingamousetoselectthecontroscontentsisslowandinconvenient.Icreatedthissmallroutinetoautomaticallyselectalldatawithinacontrol.Iplacethisroutineinacodemodulesothatit,saccessiblefromallforms.Icallthisroutinefromacontrol*sGotFocusevent.Thisway,thedataisselectediftheusertabstoorclicksonthecontrol,orifadatavalidationroutinedoesaSetFocus:PrivateSubMyTextBox_GotPocus()AutoSelectMyTextBoxEndSubTheAutoSelectroutineisquitesimple:SubAutoSelect(SelObjectAsControl)'TheAutoSelectroutine,selects"the'controsentirecontentsasifitwere'doubled-clicked.SelObject.SelStart=OIfTypeOfSelObjectIsMaskEdBoxThenSelObject.Sel1.ength=1.en(SelObject.FormattedText)ElseIfTypeOfSelObjectIsTextBoxThenSelObject.Sel1.ength=1.en(SelObject.Text)EndIfEndIfEndSub-KevinForth,St.ClairShores,MichiganVB416/321.evel:BeginningCleartheClutterProvideyouruserswithaquickwaytocleartheir"messydesktop"ofextraneousformsbydroppingthiscodeintotheClickeventofacommandbutton:ForEachFormInFormsIfForm.NameMe.NameThenUnloadFormEndIfNextForm-JamesBell,Charlotte,NorthCarolinaVB3,VB416/321.evel:BeginningCalculateAgeUsingDateDiffUsethefunctionDateDifftocalculateanindividuasexactagebasedonbirthdate.DateDifffirstcalculatesthetotalnumberofdaysanindividualhasbeenaliveandthendividesby365.25toaccountforleapyears.TheIntfunctiontruncatesthedivisionresultsbyremovingthedecimalandnotrounding:FunctionCalcAge(datEmpDateOfBirthasVariant)asIntegerCalcAge=Int(DateDiff(*y*,datEmpDateOfBirth,Date()_/365.25)EndFunction-MichaelFinley,ClarendonHiIls,IllinoisVB416/321.evel:IntermediatePreventUnwantedRecursionAbugaffectingtheSheridan3DControlsappearsinVB4.0a.Ido11,tbelieveitwasin4.0,andIamcertainitwasnotin3.0.Inanycase,evenifyouuse4.0,youshouldpayattentionbecausethenewerOCXmaybeinstalledalreadyonusers*machineswhenyourappsaredistributed.IusetheSheridancommandbuttonsquiteabitfortheirabilitytodisplayaniconaswellastext,andIranintothisproblemwhenIinstalledVB4.0a.Iftheuserdouble-clicksonacommondialogbox(forexample,toselectafile),andthedoubleclickisphysicallylocatedaboveaSheridan3Dcommandbutton,theClickprocedureofthatcommandbuttonwillbefired.Totestthis,startanewprojectandplaceaSheridancommandbuttonandacommondialogcontrolonForml.IntheClickprocedureofthecommandbutton,includethiscode:PrivateSubSSCommand1_C1ick()ConstCDERR_CANCE1.;&H7FF3ConimonDialogl.DialogTitle="OpenFile”CommonDia1og1.fiIename="*.*"ConimonDialogl.DefaultExt=ConimonDialogl.CancelError=TrueCommonDialogl.Filter=,A11Files(*.*)*.*OnErrorResumeNextConimonDialogl.Action=1IfErr=CDERR_CANCE1.ThenExitSubEndIfOnErrorGoToOEndSubRuntheprogram,clickonthecommandbutton,andwhenthecommondialogappears,moveitsothatthenameofanyfileappearsoverthebutton.Double-clickonthefilename.Thecommondialogwilldisappearandanewonewillappear,resultingfromtheSSCommandlClickeventfiringagain.Thesolutionistodeclareastatic"flag"variable,FalseClick,withinthebutton*sClickevent.ThenchangethecodeintheSSComniandlClickproceduretoread:PrivateSubSSCOmInand1.CliCkoConstCDERR.CANCE1.=&II7FF3StaticFalseClickAsBooleanIfFalseClickThenExitSubFalseClick=TrueCommonDialogl.DialogTitle="OpenFile”ConimonDialogl.filename=CommonDialogl.DefaultExt=".*'CommonDialogl.CancelError=TrueConimonDialogl.Filter="AllFiles(*.*)*.*"OnErrorResumeNextCommonDia1og1.Action=1IfErr=CDERR_CANCE1.ThenFalseClick=FalseExitSubEndIfOnErrorGoToODoEvents,allowforrecursionFalseClick=FalseEndSubTheDoEventsfunctionisrequiredinanyprocedurethatissoshortthatthelaststatementexecutesbeforetherecursionbegins.Ihopethisworkaroundcanhelpothersfixthesameproblem.-MichaelP.Rose,Kingwood,TexasVB31.evel:IntermediateObtainingSystemDateFormatTheDateCheckfunctionisusefulwhenyouusetheMaskedEditcontrolforenteringthedateaccordingtothesystemformat.SomecountriesusetheMM/DD/YYYYformat,andothercountries,likeIndia,usetheDD/MM/YYYYformat.Insteadofhard-codingtheMaskedEditcontrolsformataswel1asmaskproperties,usethisfunctiontosettherequireddateformataccordingtothecontrolpanelsettings.IntheGeneraldeclarationsectionofthemodule,definethis:DeclareFunctionGetProfiIeString1.ib_“Kernel”(ByvalSname$,ByValKname$,ByvalDef$,ByvalRet$,ByvalSize%)asintegerglobaldatemaskasvariantglobaldateformatasvariantSubDateCheck()DimStrsecnamcasstringDimStrkeynameasstringDimVarsuccessasvariantDimStrretdateasstringDimStrretsepasstringDimStrcharasstring*1Strsecnamc=Tntl”Strkeyname="sShortDate”Strretdate=string$(11,0)Varsuccess=GetProfilestring_(Strsecname,Strkeyname,"",Strretdate,_(Strretdate)Strsecname二Strkeyname="sDate”Strretsep=StringS(2,O)Varsuccess=GetProfiIeString_(Strsecname,Strkeynane,“,.Strretsep,1.en(Strretsep)Strretsep=1.eftS(strretsep,1)Strchar=Ucase$(1.eftS(strretdate,1)datemask="#"&Strretsep&"#"&Strretsep&"#"Selectcasestrcharcase"D":dateformat="DD_&Strretsep&&Strretsep&"YYYY"case"M":dateformat="MM”_&Strretscp&"DD"&Strretsep&"YYYY"case"Y":datemask=#_&Strretsep&"#&Strretsep&"#dateformat="YYYY"&_Strretsep&"MM"&Strretsep&"DD”EndselectEndSubIntheForm_1.oadevent,calltheDateCheckproceduretogetthecurrentdateformat,andassignformatandmaskpropertiesoftheMaskedEditcontrol:SubFonn_1.oad()DateCheck'CallthedatecheckprocedureMskdd.format=dateformatMskdd.mask=datemaskEndSub-S.Saravanan,Selaiyur,Madras,IndiaVB4321.evel:Intermediate1.ongFileNamesCanBeConfusingIfyouwanttoopenPaintwithafilefromyourapplication,it,sbettertoconvertthepathofthefileyouwanttoopenfromlongtoshortnames.Doingsoiswisebecauseinsomesituations-ifyourpathcontainsspaces,forexample-Paintmayrefusetoworkproperly.BeforepassingafilenametoPaint,convertittoshortnameswiththisroutine,whichtakesadvantageoftheWin32API:DeclareFunctionGetShortPathName1.ib"kernel32"Alias“GetShortPathNameA"(ByValIpsz1.ongPathAsString,_ByValIpszShortPathAsString,_ByValCchBufferAs1.ong)As1.ongFunctionShortName(1.ongPathAsString)AsStringDimShortPathAsStringConstMAXPATH=260Dimret&ShortPath=Space$(MAX,PATH)ret&=GetShortPathName(1.ongPath,ShortPath,MAXPATH)Ifret&ThenShortName=1.eft$(ShortPath,ret&)EndIfEndFunctionThistrickmayproveusefulwithanyapplicationyoupassfilenamesto.Ttwouldbesmarttotrypassing“strange"filenames/pathstomakesure.-AndreaNagar,Torino,ItalyVB3,VB416/321.evel:Beginning,FileExists?”RevisionToadaptthetip"FileExists?”(see"101HotTechTipsforVBDevelopers,*SupplementtotheAugust1996issueofVBPJ,page7)toadirectorylistbox,itisnecessarytocontroltheerrorthatoccurswhentheuserselectstheroot(C:):SubDirlChangeDimFileAsStringFile=Dirl.PathIfRightS(File,1)=""ThenFile=File&"himem.sys”ElseFile=File&""&himem.sysEndIf'ChuongVanHuynh,stipIfDir$(File)”ThenMsgBox"himem.sysexists!”EndIfEndSubWithouttestingtoseeifthepathalreadyendswithabackslash,asitwouldwhenit,stherootdirectory,anerroroccursbecauseofthestringc:himem.sys.-MichclRohan,McnthonnexSousClermont,FranceVB3,VB416/321.evel:IntermediateTrimmedtoFitThispieceofcodetrimslongfilenamestofitintoformscaptions,textboxes,andotherlimitedspaces.Thecodeallowsyoutospecifythenumberofcharactersafilenamemustbebeforeitperformsthetrimming.Forexample,ifthelabelcanhold50characters,thenyouwouldtype1.ongDirFix(nFile,50).It,sassimpleasthat.Here,sthecode:Function1.ongDirFix(IncommingAsString,MaxAsInteger)sStringDimiAsInteger,1.bl1.enAsInteger,String1.enAsIntegerDimTempStringAsStringTempString=Incomming1.bl1.en=MaxIf1.en(TempString)<=1.bl1.enThen1.ongDirFix=TempStringExitFunctionEndIf1.bl1.en=1.bl1.en-6Fori=1.en(TempString)-1.bl1.enTo1.en(TempString)IfMid$(TempString,i,1)=""ThenExitEorNext1.ongDirFix=1.eft$(TempString,3)+_""+RightS(TempString,1.en(TempString)-(i-1)EndFunction-ShafayatKamal,Wallington,NewJerseyVB3,VB416/321.evel:BeginningUseR1.EstoReduceEXESizeManyprogramsuseasplashscreentodisplaythelogooftheprogram.Thelogoisusuallymadebyanimage.YouusedtostoreitasaBMP(uncompressed)inanimagebox.Perhapsyoudon,tknowthatyoualsocanputanR1.Eimage(compressedbitmap-PaintShopProsupportsthisformat)withinVB4.Selecttheimage,clickonAllFiles,andselectyourR1.Efile.ThesizeofyourEXEwilldecreaseandyourappmayloadfaster.There,satrade-off,however,inthefactthatitwillbesmallertoreadfromdisk,butitwillconsumemoretimeasit,sdecodedtothescreen.-AndreaNagar,Torino,ItalyVB416/321.evel:BeginningWhereDoesItEnd?Whenusingthe1ine-continuationcharacterfacility-thecombinationofaspacefollowedbyanunderscore(_)usedinthedevelopmentenvironmenttoextendasinglelogicallineofcodetotwoormorephysicallines-itcanbedifficulttodeterminewherethesentencebeginsandends.Oneeasywaytoavoidthisdifficultyistosetabreakpointinthedesiredline.Thelinewillbesettothebreakpointcolor,becominganobviouscodeline.ToremovethebreakpointfromtheRunmenu,chooseToggleBreakpoint(F9)again.Tosetabreakpoint,positiontheinsertionpointanywhereinalineoftheprocedurewhereyouwantexecutiontohalt.FromtheRunmenu,chooseToggleBreakpoint(F9).Thebreakpointisadded,andthelineissettothebreakpointcolordefinedintheEditortaboftheOptionsdialogbox.-JoseAlbertoMarquesdaSilva,Coimbra,PortugalVB3,VB416/321.evel:BeginningCheapGraphicButtonsYoucanusetheWingdingsfonttoputsimplegraphicsonastandardcommandbutton.Putastandardcommandbuttononaform,andinthePropertieswindow,changethebutton,sfonttoWingdings.1.oadtheCharacterMapapplicationthatcomeswithWindows,andchangethefonttoWingdings.Selectthepictureyouwantandcopyittotheclipboard.NowchangebacktoVBandselecttheCaptionpropertyforthecommandbuttoninthePropertieswindow.PastethenewcharacterintheCaptionproperty(youcanalsousetheKeystrokethatisshownatthebottomofthecharactermapwindow).Youcanmakethepicturebiggerbychangingthefontsize.Thismethodisusefulifyoudon,tneedcolorgraphicsanddon,twanttheadditionaloverheadofa3-Dcommandbutton.Beforewarnedthatit*spossibleyourusermighthaveremovedthisfontfromhisorhersystem,andthiscouldcauseunexpectedruntimeerrors.-DavidMoulton,Knoxville,TennesseeVB3,VB416/321.evel:IntermediateRememberSWAP?”CorrectionThetip,RememberSWAP?”*101HotTechTipsforVBDevelopers,*SupplementtotheAugust1996issueofVBPJ,page13hasacommonerror.Thislineactuallycreatesthreevariantsandonestring,ratherthanthefourstringsdesired:Dima,b,casstring*4Thelineshouldread:DimDimDimaasbascasstringstringstring-TimothyJ.Hoffmann,ElSegundo,CaliforniaVB416/321.evel:IntermediateShellingMSInternetMailIfyouareusingthenewmailprogramthatcanbedownloadedforfreefromMicrosoft*sWebsite,youcanrunitfromwithinyourprogram.Simplyaddthiscommandtoacommandbutton:X=Shell("C:W1NDOWSEXP1.ORER.EXE/root,C:WINDOWSInternetMai1.(89292102-4755-1lcf-9DC2-00AA006C2B84",3)Notethatforthisexample,theWindowsdirectorynameishardcoded.Foraproductionapp,calltheGetWindowsDirectoryAPIandusethatreturnvalueinstead.-Fred1.yhne,SaltSpringIsland,BritishColumbia,CanadaVB416/321.evel:IntermediateRefertoColumnsinaDBGridControlColumnsinaDBGridcontrolareboundtodatabasefields.However,theindexnumberofacolumndoesn,ttellyouwhichfielditrepresents.Therefore,referringtoDBGridl.Columns(0).Valueisnotverydescriptive.It,sbettertointroducevariableswithclearnames,whichareboundtospecificcolumns.Inthedeclarationssectionoftheform,forexample,thecodereads:DimColOrderIDAsColumnDimColArticle_IDAsColumnDimColAmountAsColumnIntheForm1.oadeventoftheform,thecodereads:WithDBGridlSetColOrder_TD=.Columns(O)SetColArticle_ID=.Columns(1)SetColAmount=.Columns(2)EndWithIt,snolongernecessarytorefertoDBGridl.Columns(O).Value,forexample,butyoucanuseColOrder_ID.Valueinstead.ColOrderIDis,ofcourse,thesameasDBGridl.Columns(O).IfanypropertyvalueofDBGridl.Columns(O)changes,thesamepropertyvalueofColOrder_IDchangesaccordingly,andviceversa.1.ateron,whenyouinsertadatabasefieldintothegrid,youchangeonlytheindexnumbersofthecolumnsinthecodeoftheForm1.oadevent.-GeorgevanderBeek,Nieuw1.ekkerland,TheNetherlandsVB4321.evel:IntermediateMakeColumnHeadersthePerfectWidthWhenyou,redynamicallyaddingColumnlIeaderstoa1.istViewcontrolatruntime,youmaynotknowhowlongthetextfortheheaderwillbe,sotheusermustreadjustthewidthofthecolumntoseeit.ButbymakingalabelwithitsVisiblepropertysettoFalse,anditsAutosizepropertysettoTrue,youcanfillupthelabelwiththesametextthat*sgoingtobeintheheader.Thenuse1.abell.WidthintheAddargumentfortheColumnHeader:PrivateSubCommandl_Click()DimColumnTextasString,clmxasColumnHeaderColumnText=_“Averylongheaderfor"&"the1.istViewcontrol*1.abel1.Caption=ColumnTextsetcImx=1.istViewl.ColumnHeaders.Add_(,ColumnText,1.abell.Width)1.istViewl.View=IvwReportEndSub-RichWigstone,HoffmanEstates,IllinoisVB31.evel:BeginningHiddenMDIChildren"Hide"anMDlchildformwithanon-sizableborderstyle(0or1)usingthiscodeintheMDIchild,sForm1.oadevent:forml.Moveforml.1.eft,forml.Top,O,OUsealabelcontrolcoveringthevisibleareaoftheformtoallowswitchingonandoff:Ifforml.Height=OThenforml.Moveforml.1.eft,forml.Top,_form1!1.abell.Width,form1!1.abell.HeightElseforml.Moveforml.1.eft,forml.Top,O,OEndIfTheformremainsloadedbutinvisibleandisimmediatelyavailablewhenrequired.Thelabelcontrolshouldconsumenoextraresources.ThismethodprovidesaquickpopupwindowwithinMDI.-RossGourlay,Edinburgh,ScotlandVB3,VB41