vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx

上传人:李司机 文档编号:7146638 上传时间:2024-06-15 格式:DOCX 页数:82 大小:124.40KB
返回 下载 相关 举报
vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx_第1页
第1页 / 共82页
vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx_第2页
第2页 / 共82页
vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx_第3页
第3页 / 共82页
vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx_第4页
第4页 / 共82页
vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx_第5页
第5页 / 共82页
点击查看更多>>
资源描述

《vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx》由会员分享,可在线阅读,更多相关《vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx(82页珍藏版)》请在三一办公上搜索。

1、WelcometotheFourthEditionoftheVBPJTechnicalTipsSupplement!ThesetipsandtricksweresubmittedbyprofessionaldevelopersusingVisualBasic3.0,VisualBasic4.0,VisualBasicforApplications,andVisualBasicScript.ThetipswerecompiledbytheeditorsatVisualBasicProgrammer,sJournal.SpecialthankstoVBPJTechnicalReviewBoardm

2、embersDougHaynes,KarlE.Peterson,andPhilWeberfortestingallthecode.Ifyou,dliketosubmitatiptoVisualBasicProgrammer,sJournal,pleasesendittoUserTips,FawcetteTechnicalPublications,209HamiltonAvenue,PaloAlto,California,USA,94301-2500.Youcanalsofaxitto415-853-0230orsenditelectronicallytovbpjedil.Pleaseinclu

3、deaclearexplanationofwhatthetechniquedoesandwhyitisuseful,indicateifit,sforVBA,VBS,VB3,orVB4,16-or32-bitversion.Pleasetrytolimitlimitcodelengthto20lines.Do11,tforgettoincludeyoure-mailandmailingaddresses.We,11payyou$25ifwepublishyourtip.VB3,VB416/321.evel:BeginningEasyCR/1.FPaddingWhenIwritetextinme

4、ssageboxes,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.(nu

5、m_linesAsInteger)AsStringThisfunctionreturnsaNew1.inecharacterforthenumberoftimespassedtothefunction.*DimmsgsStringDimiAsIntegerFori=1Tonumlinesmsg=msg&Chr(13)&Chr(IO)NextN1.-msgEndFunction-BretCutler,1.ayton,UtahVB3,VB416/321.evel:BeginningAutoSelectTextBoxContentsUsersoftenfinditfastertoretypethee

6、ntirecontentsofatextboxratherthanpositionthecursorwithinthedata,andtheneditthedata.Thisisespeciallytrueifthelengthofthedataisshortorifthedataisn,tvisible,aswithapasswordfield,forexample.Doubleclickingorusingamousetoselectthecontroscontentsisslowandinconvenient.Icreatedthissmallroutinetoautomatically

7、selectalldatawithinacontrol.Iplacethisroutineinacodemodulesothatit,saccessiblefromallforms.Icallthisroutinefromacontrol*sGotFocusevent.Thisway,thedataisselectediftheusertabstoorclicksonthecontrol,orifadatavalidationroutinedoesaSetFocus:PrivateSubMyTextBox_GotPocus()AutoSelectMyTextBoxEndSubTheAutoSe

8、lectroutineisquitesimple:SubAutoSelect(SelObjectAsControl)TheAutoSelectroutine,selectsthecontrosentirecontentsasifitweredoubled-clicked.SelObject.SelStart=OIfTypeOfSelObjectIsMaskEdBoxThenSelObject.Sel1.ength=1.en(SelObject.FormattedText)ElseIfTypeOfSelObjectIsTextBoxThenSelObject.Sel1.ength=1.en(Se

9、lObject.Text)EndIfEndIfEndSub-KevinForth,St.ClairShores,MichiganVB416/321.evel:BeginningCleartheClutterProvideyouruserswithaquickwaytocleartheirmessydesktopofextraneousformsbydroppingthiscodeintotheClickeventofacommandbutton:ForEachFormInFormsIfForm.NameMe.NameThenUnloadFormEndIfNextForm-JamesBell,C

10、harlotte,NorthCarolinaVB3,VB416/321.evel:BeginningCalculateAgeUsingDateDiffUsethefunctionDateDifftocalculateanindividuasexactagebasedonbirthdate.DateDifffirstcalculatesthetotalnumberofdaysanindividualhasbeenaliveandthendividesby365.25toaccountforleapyears.TheIntfunctiontruncatesthedivisionresultsbyr

11、emovingthedecimalandnotrounding:FunctionCalcAge(datEmpDateOfBirthasVariant)asIntegerCalcAge=Int(DateDiff(*y*,datEmpDateOfBirth,Date()_/365.25)EndFunction-MichaelFinley,ClarendonHiIls,IllinoisVB416/321.evel:IntermediatePreventUnwantedRecursionAbugaffectingtheSheridan3DControlsappearsinVB4.0a.Ido11,tb

12、elieveitwasin4.0,andIamcertainitwasnotin3.0.Inanycase,evenifyouuse4.0,youshouldpayattentionbecausethenewerOCXmaybeinstalledalreadyonusers*machineswhenyourappsaredistributed.IusetheSheridancommandbuttonsquiteabitfortheirabilitytodisplayaniconaswellastext,andIranintothisproblemwhenIinstalledVB4.0a.Ift

13、heuserdouble-clicksonacommondialogbox(forexample,toselectafile),andthedoubleclickisphysicallylocatedaboveaSheridan3Dcommandbutton,theClickprocedureofthatcommandbuttonwillbefired.Totestthis,startanewprojectandplaceaSheridancommandbuttonandacommondialogcontrolonForml.IntheClickprocedureofthecommandbut

14、ton,includethiscode:PrivateSubSSCommand1_C1ick()ConstCDERR_CANCE1.;&H7FF3ConimonDialogl.DialogTitle=OpenFile”CommonDia1og1.fiIename=*.*ConimonDialogl.DefaultExt=ConimonDialogl.CancelError=TrueCommonDialogl.Filter=,A11Files(*.*)*.*OnErrorResumeNextConimonDialogl.Action=1IfErr=CDERR_CANCE1.ThenExitSub

15、EndIfOnErrorGoToOEndSubRuntheprogram,clickonthecommandbutton,andwhenthecommondialogappears,moveitsothatthenameofanyfileappearsoverthebutton.Double-clickonthefilename.Thecommondialogwilldisappearandanewonewillappear,resultingfromtheSSCommandlClickeventfiringagain.Thesolutionistodeclareastaticflagvari

16、able,FalseClick,withinthebutton*sClickevent.ThenchangethecodeintheSSComniandlClickproceduretoread:PrivateSubSSCOmInand1.CliCkoConstCDERR.CANCE1.=&II7FF3StaticFalseClickAsBooleanIfFalseClickThenExitSubFalseClick=TrueCommonDialogl.DialogTitle=OpenFile”ConimonDialogl.filename=CommonDialogl.DefaultExt=.

17、*CommonDialogl.CancelError=TrueConimonDialogl.Filter=AllFiles(*.*)*.*OnErrorResumeNextCommonDia1og1.Action=1IfErr=CDERR_CANCE1.ThenFalseClick=FalseExitSubEndIfOnErrorGoToODoEvents,allowforrecursionFalseClick=FalseEndSubTheDoEventsfunctionisrequiredinanyprocedurethatissoshortthatthelaststatementexecu

18、tesbeforetherecursionbegins.Ihopethisworkaroundcanhelpothersfixthesameproblem.-MichaelP.Rose,Kingwood,TexasVB31.evel:IntermediateObtainingSystemDateFormatTheDateCheckfunctionisusefulwhenyouusetheMaskedEditcontrolforenteringthedateaccordingtothesystemformat.SomecountriesusetheMM/DD/YYYYformat,andothe

19、rcountries,likeIndia,usetheDD/MM/YYYYformat.Insteadofhard-codingtheMaskedEditcontrolsformataswel1asmaskproperties,usethisfunctiontosettherequireddateformataccordingtothecontrolpanelsettings.IntheGeneraldeclarationsectionofthemodule,definethis:DeclareFunctionGetProfiIeString1.ib_“Kernel”(ByvalSname$,

20、ByValKname$,ByvalDef$,ByvalRet$,ByvalSize%)asintegerglobaldatemaskasvariantglobaldateformatasvariantSubDateCheck()DimStrsecnamcasstringDimStrkeynameasstringDimVarsuccessasvariantDimStrretdateasstringDimStrretsepasstringDimStrcharasstring*1Strsecnamc=Tntl”Strkeyname=sShortDate”Strretdate=string$(11,0

21、)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&#&Strretse

22、p&#SelectcasestrcharcaseD:dateformat=DD_&Strretsep&Strretsep&YYYYcaseM:dateformat=MM”_&Strretscp&DD&Strretsep&YYYYcaseY:datemask=#_&Strretsep&#&Strretsep&#dateformat=YYYY&_Strretsep&MM&Strretsep&DD”EndselectEndSubIntheForm_1.oadevent,calltheDateCheckproceduretogetthecurrentdateformat,andassignformat

23、andmaskpropertiesoftheMaskedEditcontrol:SubFonn_1.oad()DateCheckCallthedatecheckprocedureMskdd.format=dateformatMskdd.mask=datemaskEndSub-S.Saravanan,Selaiyur,Madras,IndiaVB4321.evel:Intermediate1.ongFileNamesCanBeConfusingIfyouwanttoopenPaintwithafilefromyourapplication,it,sbettertoconvertthepathof

24、thefileyouwanttoopenfromlongtoshortnames.Doingsoiswisebecauseinsomesituations-ifyourpathcontainsspaces,forexample-Paintmayrefusetoworkproperly.BeforepassingafilenametoPaint,convertittoshortnameswiththisroutine,whichtakesadvantageoftheWin32API:DeclareFunctionGetShortPathName1.ibkernel32Alias“GetShort

25、PathNameA(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&)

26、EndIfEndFunctionThistrickmayproveusefulwithanyapplicationyoupassfilenamesto.Ttwouldbesmarttotrypassing“strangefilenames/pathstomakesure.-AndreaNagar,Torino,ItalyVB3,VB416/321.evel:Beginning,FileExists?”RevisionToadaptthetipFileExists?”(see101HotTechTipsforVBDevelopers,*SupplementtotheAugust1996issue

27、ofVBPJ,page7)toadirectorylistbox,itisnecessarytocontroltheerrorthatoccurswhentheuserselectstheroot(C:):SubDirlChangeDimFileAsStringFile=Dirl.PathIfRightS(File,1)=ThenFile=File&himem.sys”ElseFile=File&himem.sysEndIfChuongVanHuynh,stipIfDir$(File)”ThenMsgBoxhimem.sysexists!”EndIfEndSubWithouttestingto

28、seeifthepathalreadyendswithabackslash,asitwouldwhenit,stherootdirectory,anerroroccursbecauseofthestringc:himem.sys.-MichclRohan,McnthonnexSousClermont,FranceVB3,VB416/321.evel:IntermediateTrimmedtoFitThispieceofcodetrimslongfilenamestofitintoformscaptions,textboxes,andotherlimitedspaces.Thecodeallow

29、syoutospecifythenumberofcharactersafilenamemustbebeforeitperformsthetrimming.Forexample,ifthelabelcanhold50characters,thenyouwouldtype1.ongDirFix(nFile,50).It,sassimpleasthat.Here,sthecode:Function1.ongDirFix(IncommingAsString,MaxAsInteger)sStringDimiAsInteger,1.bl1.enAsInteger,String1.enAsIntegerDi

30、mTempStringAsStringTempString=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

31、)EndFunction-ShafayatKamal,Wallington,NewJerseyVB3,VB416/321.evel:BeginningUseR1.EstoReduceEXESizeManyprogramsuseasplashscreentodisplaythelogooftheprogram.Thelogoisusuallymadebyanimage.YouusedtostoreitasaBMP(uncompressed)inanimagebox.Perhapsyoudon,tknowthatyoualsocanputanR1.Eimage(compressedbitmap-P

32、aintShopProsupportsthisformat)withinVB4.Selecttheimage,clickonAllFiles,andselectyourR1.Efile.ThesizeofyourEXEwilldecreaseandyourappmayloadfaster.There,satrade-off,however,inthefactthatitwillbesmallertoreadfromdisk,butitwillconsumemoretimeasit,sdecodedtothescreen.-AndreaNagar,Torino,ItalyVB416/321.ev

33、el:BeginningWhereDoesItEnd?Whenusingthe1ine-continuationcharacterfacility-thecombinationofaspacefollowedbyanunderscore(_)usedinthedevelopmentenvironmenttoextendasinglelogicallineofcodetotwoormorephysicallines-itcanbedifficulttodeterminewherethesentencebeginsandends.Oneeasywaytoavoidthisdifficultyist

34、osetabreakpointinthedesiredline.Thelinewillbesettothebreakpointcolor,becominganobviouscodeline.ToremovethebreakpointfromtheRunmenu,chooseToggleBreakpoint(F9)again.Tosetabreakpoint,positiontheinsertionpointanywhereinalineoftheprocedurewhereyouwantexecutiontohalt.FromtheRunmenu,chooseToggleBreakpoint(

35、F9).Thebreakpointisadded,andthelineissettothebreakpointcolordefinedintheEditortaboftheOptionsdialogbox.-JoseAlbertoMarquesdaSilva,Coimbra,PortugalVB3,VB416/321.evel:BeginningCheapGraphicButtonsYoucanusetheWingdingsfonttoputsimplegraphicsonastandardcommandbutton.Putastandardcommandbuttononaform,andin

36、thePropertieswindow,changethebutton,sfonttoWingdings.1.oadtheCharacterMapapplicationthatcomeswithWindows,andchangethefonttoWingdings.Selectthepictureyouwantandcopyittotheclipboard.NowchangebacktoVBandselecttheCaptionpropertyforthecommandbuttoninthePropertieswindow.PastethenewcharacterintheCaptionpro

37、perty(youcanalsousetheKeystrokethatisshownatthebottomofthecharactermapwindow).Youcanmakethepicturebiggerbychangingthefontsize.Thismethodisusefulifyoudon,tneedcolorgraphicsanddon,twanttheadditionaloverheadofa3-Dcommandbutton.Beforewarnedthatit*spossibleyourusermighthaveremovedthisfontfromhisorhersyst

38、em,andthiscouldcauseunexpectedruntimeerrors.-DavidMoulton,Knoxville,TennesseeVB3,VB416/321.evel:IntermediateRememberSWAP?”CorrectionThetip,RememberSWAP?”*101HotTechTipsforVBDevelopers,*SupplementtotheAugust1996issueofVBPJ,page13hasacommonerror.Thislineactuallycreatesthreevariantsandonestring,rathert

39、hanthefourstringsdesired:Dima,b,casstring*4Thelineshouldread:DimDimDimaasbascasstringstringstring-TimothyJ.Hoffmann,ElSegundo,CaliforniaVB416/321.evel:IntermediateShellingMSInternetMailIfyouareusingthenewmailprogramthatcanbedownloadedforfreefromMicrosoft*sWebsite,youcanrunitfromwithinyourprogram.Sim

40、plyaddthiscommandtoacommandbutton:X=Shell(C:W1NDOWSEXP1.ORER.EXE/root,C:WINDOWSInternetMai1.(89292102-4755-1lcf-9DC2-00AA006C2B84,3)Notethatforthisexample,theWindowsdirectorynameishardcoded.Foraproductionapp,calltheGetWindowsDirectoryAPIandusethatreturnvalueinstead.-Fred1.yhne,SaltSpringIsland,Briti

41、shColumbia,CanadaVB416/321.evel:IntermediateRefertoColumnsinaDBGridControlColumnsinaDBGridcontrolareboundtodatabasefields.However,theindexnumberofacolumndoesn,ttellyouwhichfielditrepresents.Therefore,referringtoDBGridl.Columns(0).Valueisnotverydescriptive.It,sbettertointroducevariableswithclearnames

42、,whichareboundtospecificcolumns.Inthedeclarationssectionoftheform,forexample,thecodereads:DimColOrderIDAsColumnDimColArticle_IDAsColumnDimColAmountAsColumnIntheForm1.oadeventoftheform,thecodereads:WithDBGridlSetColOrder_TD=.Columns(O)SetColArticle_ID=.Columns(1)SetColAmount=.Columns(2)EndWithIt,snol

43、ongernecessarytorefertoDBGridl.Columns(O).Value,forexample,butyoucanuseColOrder_ID.Valueinstead.ColOrderIDis,ofcourse,thesameasDBGridl.Columns(O).IfanypropertyvalueofDBGridl.Columns(O)changes,thesamepropertyvalueofColOrder_IDchangesaccordingly,andviceversa.1.ateron,whenyouinsertadatabasefieldintothe

44、grid,youchangeonlytheindexnumbersofthecolumnsinthecodeoftheForm1.oadevent.-GeorgevanderBeek,Nieuw1.ekkerland,TheNetherlandsVB4321.evel:IntermediateMakeColumnHeadersthePerfectWidthWhenyou,redynamicallyaddingColumnlIeaderstoa1.istViewcontrolatruntime,youmaynotknowhowlongthetextfortheheaderwillbe,sothe

45、usermustreadjustthewidthofthecolumntoseeit.ButbymakingalabelwithitsVisiblepropertysettoFalse,anditsAutosizepropertysettoTrue,youcanfillupthelabelwiththesametextthat*sgoingtobeintheheader.Thenuse1.abell.WidthintheAddargumentfortheColumnHeader:PrivateSubCommandl_Click()DimColumnTextasString,clmxasColu

46、mnHeaderColumnText=_“Averylongheaderfor&the1.istViewcontrol*1.abel1.Caption=ColumnTextsetcImx=1.istViewl.ColumnHeaders.Add_(,ColumnText,1.abell.Width)1.istViewl.View=IvwReportEndSub-RichWigstone,HoffmanEstates,IllinoisVB31.evel:BeginningHiddenMDIChildrenHideanMDlchildformwithanon-sizableborderstyle(

47、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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号