欢迎来到三一办公! | 帮助中心 三一办公31ppt.com(应用文档模板下载平台)
三一办公
全部分类
  • 办公文档>
  • PPT模板>
  • 建筑/施工/环境>
  • 毕业设计>
  • 工程图纸>
  • 教育教学>
  • 素材源码>
  • 生活休闲>
  • 临时分类>
  • ImageVerifierCode 换一换
    首页 三一办公 > 资源分类 > DOCX文档下载  

    tips_6 面向VisualBasic程序员的杂志 第6版.docx

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

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

    tips_6 面向VisualBasic程序员的杂志 第6版.docx

    WE1.COMETOTHESIXTHEDITIONOFTHEVBPJTECHNICA1.TIPSSUPP1.EMENT!ThesetipsandtricksweresubmittedbyprofessionaldevelopersusingVisualBasic3.0,VisualBasic4.0,VisualBasic5.0,VisualBasicforApplications(VBA),andVisualBasicScript(VBS).VB416/321.evel:IntermediateUSEBOO1.EANVARIAB1.ESFORCHECK-BOXVA1.UESVisualBasicspecifiesaBoolean'sdefaultvaluesaszeroforFalseand-1forTrue.Youmaysaveandsetthevalueofacheckbox,basedontheabsolutevalueofaBooleanvariable,asthesecorrespondtotheintrinsicconstantsVbUncheckedandVbChecked:DimbBoolasBooleanbBool=True'/IfbBool=0thecheckboxwillbe'/unchecked,ifitisanythingelseitwill,/bechecked.Checkl.Value=Abs(bBool)-JeremyBoschen,Branchburg,NewJerseyVB416/321.evel:IntermediateDISP1.AYHORIZONTA1.SCRO1.1.BARUnliketheWindows95commoncontrols,thestandardlistboxdoesn'thaveahorizontalscrollbarwhenlistitemsaretoowidetofitwithinthelistbox.Fortunately,it'snothardtodirectalist-boxcontroltodisplayahorizontalscrollbar.Addthiscodetoaform's1.oadevent.Itfillsalistboxwith100longstringsandcallsSetHScroIItoshowahorizontalscrollbarinthelistbox:PrivateSubForm_1.oad()DimiAsIntegerFori=1To1001.istl.AddItemCStr(i)&_ubottle(三)ofbeeronthewall.uNextiSetHScrollMe,1.istl,1.istl.1.ist(0)EndSubAddthiscode,whichincludestherequiredAPIdeclarationsandtheSetHScroIIroutine,toaBASmodule.TheSetHScroIIroutineusestheSendMessageAPIfunctiontosendthe1.B_SETHORIZONTA1.EXTENTmessagetoalistbox.Thelastargumentisanitemfromthelist,preferablyoneofthelongestitems.SetHScroIIdeterminesthestring'swidthinpixelsandpassesthisvaluetothelistboxalongwiththe1.B_SETHORIZONTA1.EXTENTmessage.Thelistboxsetsitshorizontalextenttothisvalue,andifitiswiderthanthelist-boxcontrol,thelistboxdisplaysahorizontalscrollbar:#IfWin32ThenDeclareFunctionSendMessage1.ib11user3211_AliasnSendMessageAn(_ByValhwndAs1.ong,ByValwMsgAs1.ong,ByValwParamAs1.ong,IParamAs1.ong)As1.ong#ElseDeclareFunctionSendMessage1.ib,user3211_Alias"SendMessageAn(_ByValhwndAsInteger,ByValwMsgAsInteger,ByValwParamAsInteger,IParamAs1.ong)As1.ong#EndIf,Defineconstantformessagetolist-boxcontrolConst1.B_SETHORIZONTA1.EXTENT=&H194PublicSubSetHScroll(FrmAsForm,CtrlAs_Control,StrTextAsString)DimnScaleModeAsIntegerDimnTextWidthAsInteger,ScaleinpixelsforwindowmessagenScaleMode=Frm.ScaleModeFrm-ScaleMode=3,Getthewidth,inpixels,ofthetextstringnTextWidth=Frm.TextWidth(StrText),SendamessagetothelistboxSendMessageCtrl.hwnd,1.B_SETHORIZONTA1.EXTENT,nTextWidth,O,RestorepreviousscalemodeFrm.ScaleMode=nScaleModeEndSub-PeterGomis,Shelton,ConnecticutVB416/32,VB51.evel:BeginningGETTHETRUEMEMBEROFANOPTIONARRAYSettinganelementinanarrayofoptionbuttonstoTrueiseasy.Clickontheoptionbutton,orusethiscode:OptionArray(ThisOne)=TrueThisOneistheIndexofthememberyouwanttobeselected.GettingtheTruememberofanoptionarrayisnotsosimple.Becauseyouneedtoperformthiskindoftaskinalmostanyreasonablycomplexprogram,addingthisfunctiontoyourcodelibraryorgenericmodulesimplifiesthetask.Youdon,tneedtoknowthearraysizeinadvance:FunctionOptionTrueIs(OptionArrayNameAs_Variant)AsInteger,ReturnstheindexoftheTrue,memberofanoptionarrayDimCtlasControlForEachCtlinOptionArrayNameIfCtl.Value=TrueThenOptionTruels=Ctl.IndexExitForEndIfNextEndFunctionYoucanusetheroutinetosetaPublicvariablefromaPropertiessheetusingthisformat:SomePublicVariable=OptionTrueIs(SomeOptionArray()Orusethiscodetosaveaprogramvariablebetweenruns:SaveSetting(uMyAppu,uOptionSettingsu,_"OptionKeyn,OptionTrueIs(SomeOptionArray()1.oadtheroutineusingthiscode:SomeOptionArray(GetSetting(uMyAppu,uuz"Optionsettings","OptionKeyn,O)j=TrueOryoucanloadtheroutineusingthiscode:SomePublicVariable=GetSetting(uMyAppu,11z"OptionSettings",nOptionKeyn,O)UsethiscodetocontrolaSelectCasestructure:SelectCaseOptionTrueIs(SomeOptionArray()CaseO:,ThiscodewillexecuteifelementO,ofSomeOptionArray()isselected.EndSelectUsethiscodetotestacondition:IfOptionTrueIs(SomeOptionArray()=SomeValueThen,Thiscodewillexecuteifelement,SomeValueofSomeOptionArray()is,selected.EndIf-RogerGilchrist,Ourimbah,NewSouthWales,AustraliaVB416/32,VB51.evel:IntermediateDEBUGERRORHAND1.ERSVisualBasicgivesyoutheoptiontoturnofferrortrappinginyourprojects.Thisisusefulwhenyoususpectthatyourerrorhandlerscontainerrorsthemselves.Toturnofferrorhandlingglobally,chooseOptionsfromtheToolsmenu.SelecttheGeneraltab,andselectBreakonAllErrors.Thenexttimeyourunyourprojectinthedevelopmentenvironment,VisualBasicwillbreakwheneveranerroroccursinyourcode,whethertheerroristrappedornot.-JeffreyP.McManus,SanFrancisco,CaliforniaVB3,VB416/32,VB51.evel:BeginningPROTECTDATAWITHINMODU1.ESUsePrivatevariablesinBASmodulestoprotectdatathatthemodule'sroutinesmustaccess,butwhichshouldbehiddenfromtherestoftheapplication:Dimhidden_dataAsIntegerFunctionGetData()AsIntegerGetData=hidden_data*2EndFunction-RodStephens,Boulder,ColoradoVB3,VB416/32,VB5,VBA1.evel:IntermediateCONVERTATEXTFI1.EINTOACCESSMDBItcanbetroublesometoconvertatextfileintoanAccessdatabase.IttakesalotoftimetoopenthefileforsequentialaccessandcreatenewrecordsusingtheAddNewmethod.Instead,usetheTextISAMdriverandSQ1.todothejobforyou.First,createaSCHEMA.INIfileforthetextfileandplaceitinthesamedirectoryasthetextfile.Usethiscodetoconvertthedatabase:DimdbAsDatabase,tblasTableDefSetdb=DBEngine.CreateDatabase(App.Path&_"mymdb.mdb",Cib1.angGeneral,dbVersion_0)Settbl=db.CreateTableDef(11Tem11)tbl.Connect=uTextzdatabase=C:vbpjdatautbl.SourceTableName=HCustomer#txtndb.TableDefs.Appendtbldb.Execute"SelectTemp.*intoNewTablefromTempudb.TableDefs.Deletetbl.Namedb.CloseSettbl=NothingSetdb=NothingNow,youonlyneedtocreateindexes.Youcanusethismethodtoconverttextfilesinexcessof100,000recordsinafewseconds.-RichardMageau,Warren,RhodeIslandVB3,VB416/32,VB5,VBA1.evel:IntermediateQUICKANDEASYSCHEMAJNiTocreateaSCHEMA.INIfileforatextfilequicklyandeasily,lettheODBCsetupanddriversdoitforyou.GototheControlPanelandstartODBC.ClickontheAddbuttonandselecttheTextdriver.ClickontheOptionsbuttonanddescribehowtoarrangethetextfile.Ifyourtextfilehasaheaderrecord,clickontheGuessbutton,andtheCoIumnNameswillbefilledoutforyou.Onthelastscreen,chooseCanceltoavoidsettingupthedatasource.Checkthedirectorywherethetextfileresides,andyou'llfindanewSCHEMA.INIfile.-RichardMageau,Warren,RhodeIslandVB416/32,VB51.evel:IntermediateCONTRO1.ARRAYSARECO1.1.ECTIONSMostVB4programmersknowtheycanaccessaform'scontrolcollectionusingaForEachloop.Many,however,arenotawarethatindividualcontrolarraysareactuallycollections.Thisknowledgecanbehelpfulwhencheckingthepropertiesofseveralcontrols,especiallywhennewcontrolsareloadedatruntime.Youmightwishtocreateaforminwhichalltextboxesmustbefilledout.Insteadofassigningauniquenametoeachtextbox,createacontrolarraywitheachtextboxnamedt×tFields.YoucanusethisnameasyouusethenameofanycollectioninaForEachloop:DimvForEachvIntxtFieldsIfv.Text=ThenMsgBoxuAllfieldsmustbe_,filledout.,VbExclamation+_VbOKOnlyExitSubEndIfNextBecausetxtFieldsisacollection,youcanalsodeterminehowmanytextboxesareinthearraybycheckingthevalueoftxtFields.Count.Formoreinformation,seeKarlE.Peterson1SQ&Acolumn,"TheKeystoYourControls"VBPJAugust1997.-DanielBuskirk,TheBronx,NewYorkVB3,VB416/32,VB5,VBA1.evel:BeginningSETAF1.AGTOTRUE/FA1.SEWhenyouwanttosetaflagtoTrueorFalse,dependingontheresultsofacomparison,youdon,tneedtouseanIfstatementlikethis:Ifx>3thenGreater=TrueElseGreater=FalseEndIf1.ogicaloperatorsreturnavaluelikeanyotheroperator.Instead,usethissyntax:Greater=x>3Thisway,youmovedirectlytotheresultofthecomparisoninyourflag.Itisshorterandfasterthantheformexample.-MartinGirard,Chicoutimi,Quebec,CanadaVB3,VB41632,VB5,VBA1.evel:IntermediateSUPPORTAFONTTHEPRINTERDOESN'TOftenusersprintfromapplicationsthatsupportafonttheprinterdoesn,t.AnerroroccursifanapplicationusesastatementsuchasPrinter.PrintSomethingToPrintfollowingaPrinterTontName=FontNamestatement,andtheprinterdoesn'tsupporttheFontName.Youcanusethisfunctionprocedureasacorrectivemeasureaftertheerroristrapped.Thisfunctionprocedureusesonlyoneparameter-thefontnamesspecifiedbytheapplication.Iftheprinterdoesn'tsupportthefont,thefunctionprocedurereturnsafontontheprintermostsimilartothefontintheapplication:FunctionFindFont(SpecifiedFontAsString),findthefontontheprinterwhichisthe,closesttothefontnamepassedtothisprocedure:Dimi%,tempfont%Fori%=1ToPrinter.FontCountter11pfont=InStr(Printer.Fonts(i%),SpecifiedFont),Getfont,sposition.Iftempfont<>0ThenExitForEndIfNextIftempfont<>0ThenFindFont=Printer.Fonts(i%)Else,takeanactionifnosimilarfontsare,foundonthisprinterEndIfEndFunctionInyourerrorhandler,usethisfunctioninconjunctionwiththeFontNamepropertyofthePrinterobject.Afteryoutakethiscorrectivemeasure,resumetheexecutionofyourprogram:Printer.FontName=FindFont(SpecifiedFont)ResumeNext-BrianHunter,Brooklyn,NewYorkVB432,VB5,VBA1.evel:IntermediateCENTERFORMSWITHTASKBARVISIB1.EJustabouteveryVBdeveloperusestheMove(Screen.Width-Width)2,(Screen.Height-Height)2methodtocentertheformsonscreen.However,whentheuserhastheWindows95orNT4.0taskbarvisible,yourformcentersonscreenbutdoesn'ttakeintoaccountthepositionofthetaskbaritself.TheCenterForm32routinecentersaforminavailablescreenarea,takingintoaccountthetaskbar.AddthiscodetotheDeclarationssectionofamodule,andputthecodeCenterForm32MeontheForm_1.oadeventoftheformsyouwanttocenter:OptionExplicitPrivateConstSPI_GETWORKAREA=48PrivateDeclareFunction_SystemParametersInfoS1.ib,'User32,'_Alias"SysternParametersInfoA"(_ByValuActionAs1.ong,ByValuParamAs1.ong,IpvParamAsAny,ByValfuWinlniAs1.ong)PrivateTypeRECT1.eftAs1.ongTopAs1.ongRightAs1.ongBottomAs1.ongEndTypePublicFunctionCenterForm32(frmAsForm)DimScreenWidthS,ScreenHeightS,Screen1.eftSzScreenTop&DimDesktopAreaAsRECTCallSystemParametersInfo(_SPI_GETWORKAREA,0,DesktopAreazO)ScreenHeight=(DesktopArea.Bottom-_DesktopArea.Top)*Screen.TwipsPerPixelYScreenWidth=(DesktopArea.Right-_DesktopArea.1.eft)*Screen.TwipsPerPixelXScreen1.eft=DesktopArea.1.eft*Screen.TwipsPerPixelXScreenTop=DesktopArea.Top*Screen.TwipsPerPixelYfrm.Move(ScreenWidth-frm.Width)2+Screen1.eft,(ScreenHeight-_frm.Height)2+ScreenTopEndFunction-MigueISantos,Aveiro,PortugalVB3,VB416/321.evel:IntermediateDISP1.AYTOO1.TIPSYoucaneasilyduplicatethetooltipsthatappearwhenyoufloatthemouseoverabuttoninMicrosoft'sproducts.Thiscodedisplaysthetooltipinthelowerright-handcornerofthecontrol(normallyabutton):,xTip:stringtodisplayasthetip,xCtrl:controlyouwantthetiptoshowfor.,XTipControl:controlbeingusedtodisplay,thetip(anSSPanel)PublicSubShowTip(xTipAsString,xCtrlAs_Control,XTipControlAsControl)XTipControl.1.eft=xCtrl.1.eft+xCtrl.WidthXTipControl.Top=xCtrl.Top+xCtrl.HeightXTipControl.Caption=xTipXTipControl.Visible=TrueEndSubThiscodehidesthetooltip:'XTipControl:controlwhichisbeingusedto,displaythetip.PublicSubHideTip(XTipControlAsControl)XTipControl.Visible=FalseEndSubPlacetheShowTipfunctionintheMouseMoveeventofthecontrol(三)forwhichyouwanttodisplayatip.PlacetheHideTipfunctionintheothercontrol(三)forwhichyoudon'twanttodisplayatip:SubCommandl_MouseMove(ButtonAsInteger,ShiftAsInteger,XAsSingle,YAsSingle)ShowTipnCommandl,Commandl,SSPanellEndSubSubCommand2_MouseMove(ButtonAsInteger,ShiftAsInteger,XAsSingle,YAsSingle)ShowTip,Comr11and2,',Command2,SSPanellEndSubSubForm_MouseMove(ButtonAsInteger,ShiftAsInteger,XAsSingle,YAsSingle)'NotooltipforformHideTipTextlEndSub-AndyMclnturff,Erwin,TennesseeVB51.evel:IntermediateUSESUBSCRIPTSANDSUPERSCRIPTSYoucanusesubscriptsandsuperscriptsinaRichTextBoxcontrol.Topreventthecontrolfromtruncatingtextthatisraisedorloweredtoofar,reducethecharacters'sizeaccordingly:PrivateSubForm_1.oad()RichTextBoxl.Font-Name="TimesNewRoman,RichTextBoxl.Font.Size=10RichTextBoxl.Text=,H2SO4",Movethenumbersdown2points.MakeSubscriptRichTextBoxl,1,1,-2MakeSubscriptRichTextBoxl,4,1,-2EndSubPrivateSubOffsetRichText(boxAs_RichTextBox,startAsInteger,lengthAsInteger,offsetAsInteger)box.SelStart=startbox.Sel1.ength=lengthbox.SelFontSize=box.Font.Size+offsetbox.SelCharOffset=-ScaleY(offset,vbPoints,vbTwips)box.SelStart=Obox.Sel1.ength=OEndSub-RodStephens,Boulder,ColoradoVB4321.evel:AdvancedP1.AYWAVSOUNDSFROMRESOURCEFI1.ESEveryonelovesagoodsoundbite.YoucanusethePIaySoundOfunctionintheWindowsMultimediaD1.1.(WINMM.D1.1.)toplayawave(WAV)filethatisstoredasaresource.AlthoughyoucandothisusingtheSndPIaySoundfunction,SndPIaySoundrequiresyoutofind,load,lock,unlock,andfreetheresource.PIaySoundachievesallofthiswithasinglelineofcode.Addthislineofcodetoyourresourcefile(RC)designatinganameforthesoundanditslocation:MySoundWAVEc:musicvanhalen.wavThenameMySoundisaplaceholderforanameyousupplytorefertothisWAVresourceincode.Compiletheresourcefileusingtheresourcecompiler(RC.EXE)tocreateaRESfile.IncludethisfileinyourVBproject.Usethiscodetoplaythesound:PrivateDeclareFunctionPlaySound1.ib_,winmm.dll,'AliasnPlaySoundAn(_ByValIpszNameAsString,ByValhModuleAs1.ong,ByValdwFlagsAs1.ong)As1.ongPrivateConstSND_ASYNC&=&H1,PlayasynchronouslyPrivateConstSND_NODEFAU1.T&=&H2,SilenceifsoundnotfoundPrivateConstSND_RESOURCE&=&H40004,NameisresourcenameoratomDimhlnstAs1.ong,HandletoApplicationInstanceDimSSoundNameAsString'StringtoholdsoundresourcenameDimIFlagsAs1.ong'PlaySound()flagsDimIRetAs1.ong'ReturnvaluePrivateSubCommandl_Click()hlnst=App.hlnstanceSSoundName=nMySoundnIFlags=SND_RESOURCE+SND_ASYNC+_SND_NODEFAU1.TIRet=PlaySound(SSoundName,hlnst,IFlags)EndSubNotethatyoumustcompilethisapplicationandruntheresultingEXEdirectlyforthiscodetoworkbecauseitreliesontheapplicationinstancehandle.WhileintheVBdevelopmentenvironment,AppJnstancereturnsaninstancehandletotherunningVB32.EXEprocess,nottheapplicationunderdevelopment.ForacompletedescriptionofPlaySound(),refertotheMultimediasectionoftheWin32SDK.-SteveDavis,Gaithersburg,MarylandVB3,VB416/32,VB51.evel:IntermediateABETTERWAYTOSWAPTWOINTEGERVARIAB1.ESThealgorithmshowninthetip,"SwapValuesUsingOnlyTwoVariables""101TechTipsforVBDevelopers,SupplementtotheFebruary1997issueofVBPJ5page25,crashesnotonlyif(a+b)>=32K,butif(a+b)<-32Kalso.Iusuallyusethisalgorithminstead:a=aXorb:b=aXorb:a=aXorb.Thisworksforalmostanyprogramminglanguage.-AIexBootman,FosterCity,CaliforniaVB432,VB51.evel:IntermediateWRITE1.ESSCPU-BOUNDANIMATIONSWhendoinganimation,suchasscrollingalabelorusingpictureboxes,IfirstusedthemethoddescribedbyEricBernatchez("SmootherControlAnimation,""101TechTipsforVBDevelopers,"SupplementtotheFebruary1997issueofVBPJ,page21).However,IfoundthatwhileintheDo1.oop,theCPUusageis100percent!WindowsNT,Windows95,andWin32haveanAPIcallnamedS1.EEP.Thiscallsuspendsthecalledapplicationforthesuppliedamountofmilliseconds.Whenyouchangethecode,theCPUusageonaPentium100dropsto10percent:DeclareSubSleep1.ib11kernel3211(_ByValdwMiIlisecondsAs1.ong)PublicSubScrolling()1.abell.1.eft=Me.WidthDoS

    注意事项

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

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




    备案号:宁ICP备20000045号-2

    经营许可证:宁B2-20210002

    宁公网安备 64010402000987号

    三一办公
    收起
    展开