欢迎来到课桌文档! | 帮助中心 课桌文档-建筑工程资料库
课桌文档
全部分类
  • 党建之窗>
  • 感悟体会>
  • 百家争鸣>
  • 教育整顿>
  • 文笔提升>
  • 热门分类>
  • 计划总结>
  • 致辞演讲>
  • 在线阅读>
  • ImageVerifierCode 换一换
    首页 课桌文档 > 资源分类 > DOCX文档下载  

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

    • 资源ID:1421253       资源大小:124.40KB        全文页数:82页
    • 资源格式: DOCX        下载积分:5金币
    快捷下载 游客一键下载
    会员登录下载
    三方登录下载: 微信开放平台登录 QQ登录  
    下载资源需要5金币
    邮箱/手机:
    温馨提示:
    用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)
    支付方式: 支付宝    微信支付   
    验证码:   换一换

    加入VIP免费专享
     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    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

    注意事项

    本文(vbpjtip4 面向VisualBasic程序员的杂志 第4版.docx)为本站会员(夺命阿水)主动上传,课桌文档仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知课桌文档(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    备案号:宁ICP备20000045号-1

    经营许可证:宁B2-20210002

    宁公网安备 64010402000986号

    课桌文档
    收起
    展开