tips_7 面向VisualBasic程序员的杂志 第7版.docx

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

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

1、WelcometotheSeventhEditionoftheVBPJTechnicalTipsSupplement!VB3,VB416/32,VB51.evel:BeginningDeletinganArrayElementConventionalwisdomsuggeststhattodeleteanarrayelement,youmustmoveupallthesubsequentelementstoclosethegapleftbythedeleteditem.However,ifthesequenceoftheelementsisntsignificant(asinanunsorte

2、darray),thisalgorithmquicklydeletesanitem:,Elementtodelete(Delete=5NumberofelementsbeforedeletionnElements三UBound(Array)ReplaceiDeletewithlastiteminarrayArray(IDeIete)=Array(nElements)*UseReDimPreservetoshrinkarraybyoneReDimPreserveArray(1.Bound(Array)_TonElements-1)一BasilHubbard,Hammon,Omario,Canad

3、aVB432,VB5,VBA1.evel:IntermediateInvokehOpenWith.,DialogBoxWhenlaunchingadatafilewiththeSheIIExecuteOfunction,Windowstriestofindtheassociatedapplicationandopenthedatafilewiththisapplication.Butwhathappensifnoassociationexists?SheIIExecuteOsimplyreturnserrorde31(noassociation)andnothinghappens.Wouldn

4、titbeniceifyourprograminvokedthe41Openwith.dialogboxsoyoucanchsewhichapplicationyouwanttoassociatewithyourdatafile?Heresasolution-calltheSheIIDocroutineandpassafullyqualifiedpath/filenameofthedatafileyouwishtoopen:OptionExplicitDeclareFunctionGetDesktopWindow1.ib,tuser32,()As1.ongDeclareFunctionSheI

5、IExecute1.ib_,shell32.drAliasSheIIExecuteA.(ByVaIhW11dAs1.ong,ByVaIIpOperation_AsString,ByVaIIpFiIeAsString,_ByVaIIpParametersAsString,_ByVaIIpDirectoryAsString,_ByVaInShowCmdAs1.ong)As1.ongDeclareFunctionGetSystemDIrectoryUb_“kemel32AliasGetSystemDirectoryA_(ByVaIIpBufferAsString,ByVaInSize_As1.ong

6、)As1.ongPrivateConstSE-ERR-NOASSOC=31PublicSubShellDoc(strFileAsString)DimIngRetAs1.ongDimStrDirAsStringIngRet=SheHEXeCUte(GetDeSktoPWindOw,_open”,StrFiIe,_VbNuIIString1VbNuIIString.VbNormaIFocus)IfIngRet=SE_ERR_NOASSOCThennoassociationexistsStrDir三Space(260)IngRet=GetSyStemDireCtOry(StrDir,_1.en(St

7、rDIr)StrDir三1.eft(strDir,IngRet)showtheOpenwithdialogboxCallShellExecutefGetDesktopWindow,_VbNuIIString,RUND1.1.32.EXE-,Mshell32.dll,OpenAs.RunD1.1.”&_StrFite1StrDir1VbNormaIFocus)EndIfEndSub-ThomaSWeidmannjeceivedbyemailVB432,VB51.evel:BeginningSSTABVs.OptionButtonsAlthoughVB,sSSTabntrolbehavesasif

8、eachtabpageisacontainer,itactuallyusesasinglecontainerforalltabpages.Thiscancauseunexpectedbehaviorifyouhavegroupsofoptionbuttonsondifferentpages.Clickingonanoptionbuttonononepageclearsalltheuncontainedoptionbuttonsontheother,seeminglyunrelated,pages.Solvethisproblembyaddingyourowncontainersframesor

9、pictureboxes)foreachgroupofoptionsyouwanttobemutuallyexclusive.SteveCiSCoandROIandSOUtharaFranklin,TenneSSeeVB432,VB51.evel:BeginningChangetheAppearancePropertyofaTextBoxatRunTimeSorry,youcantchangetheAppearancepropertyofatextboxatruntimebutyoucanmakeitlooklikeyouhave!Ifsettonone,a3-Dpictureboxhasaf

10、latBorderStyIeproperty.Putyourtextbox(withaflatappearance)insideapicturebox(witha3-Dappearance)andchangethepictureboxsborderstyle.UsethiscompletecodebesureyouplaceText1insidePicturel:Privatem_TextVAppearanceAs1.ongPrivateSubForm_1.oad()WithText1Picturel.Width=.WidthPicturel-Height三.Height.MoveO,OEnd

11、WithText1_Appearance1,3DEndSubPublicProperty1.et_Text1_Appearance(nAppearanceAs1.ong)WithPicturelSelectCasenAppearanceCaseOFlat.BorderStyIe三nAppearanceCase1,3D.BorderStyIe=nAppearanceEndSelectm_Text1_Appearance三.BorderStyIeEndWitfCEndPropertyPublicPropertyGetText1_AppearanceOAs1.ongTeXt1.APPearanCe三

12、m_Text1_AppearanceEndPropertyJimDeutch,CaZenOvia,NeWYorkVB432,VB51.evel:BeginningDealingWithNullValuesReturnedFromRDOResultsetsIfyou,rassigningthevaluesoflumnsyoureturnfromRDOqueriesintostringvariables,you,llgetanInvaliduseofNulerrorifoneofthecolumnshasaNullvalue.Formostpurposes,dratherhavethevaluea

13、sanemptystringanyway.RatherthancodeforthateachtimeIaccessacolumn,l,vewrittenafunctioncalledCleanthatturnsNullvaluesintoemptystrings.Icallitlikethis:strMyString=Clean(rdoResultset(MMyVarCharColumnM)IalsoconvertEmptyvaluesaswell,forusewithVariants:PublicFunctionClean(ByValvarDataAsVariant)AsStringIfIs

14、NuII(VarData)ThenClean三ElselfIsEmpty(VarData)ThenClean=ElseClean=CStr(VarData)EndlfEndFunction-JameST.Stanley,MuncieJndianaVB3,VB416/32,VB51.evel:BeginningInSearchofSampleCodemalwayslookingforsamplecode,andthesetup1.vbpfileisanexcellentsourceofreusablecode.ItcomeswithVBandispartoftheVBsetupkit.Theco

15、ntentsvary,dependingonwhatversionofVByouhave,butyoullfindusefulexamplesineachversion.Forexample,theVB5filesamplecodedoesthesethings: GetstheWindowsdirectory. GetstheWindowsSystemdirectory. Determinesifafileordirectoryexists. DeterminesifyourerunningWinNTorWin95.,Determinesdrivetype. Checksdiskspace.

16、 Createsanewpath. ReadsfromanINIfile. Parsesdateandtime. Retrievestheshortpathnameofafilentaininglongfilenames.Plus,awholemoduleworkstologerrorstoanerrorfile.Thisdeiswell-commentedandcaneasilybecutandpastedintoyourproject.CaroleMCCIlISke1.Seattle,WaShingtOnVB416/32,VB51.evel:IntermediateFloatinganEd

17、itBoxTominimizethenumberofcontrolsonmyforms,IuseatextboxasafloatinginputcontrolthatIeitheroverlayontoagridorswapwithalabel.Hereismyswapsubroutine:PublicSubSW叩COntrOIS(CHideAsControl,_eShowAsControl,OptionalValue)WithcHlde.Visible三FalsecShow.Move.1.eft,.Top,.Width,.HeightEndWithIfIsMIssing(VaIue)Then

18、WTypeOfeShowIsTextBoxOr_TypeOfeShowIs1.abelTheneShow=cHideEndIfEISeeShow=ValueEndIfWitheShow.Visible三True.ZOrderHTypeOfeShowIsTextBoxThen.SeIStart三O.SeI1.ength=1.n(cShow)If.VisibleThen.SetFocusEndHEndIfEndWithEndSubWhenIenterthestatementwSwapControIsIbIData,txtData,IbIDatadisappearsandtxtDataappears

19、initsplacewiththevalueofIbIDataselectedandthefocussettoit.Afteryoumakeyourentry,executethestatementSwapControlstxtData,IbIData.-CaIogeroS.Cumbo,Waterloo,Ontario,CanadaVB432,VB51.evel:IntermediateYetAnotherCenterFormRoutineIntheApril1997issueofVBPJ,youpublishedatipcalledConsidertheTaskbarWhenCenterin

20、gForms.YoucancenterformsmoreeasilywiththeSystemParametersInfoAPIcall:PrivateDeclareFunction_SystemParametersInfo1.ibuser32Allas_SystemParametersInfoAt(ByVaIuAction_As1.ong,ByVaIuParamAs1.ong,RAsAny,_ByVaIfuWinlniAs1.ong)As1.ongPrivateTypeRECT1.eftAs1.ongTopAs1.ongRightAs1.ongBottomAs1.ongEndTypePriv

21、ateConstSPI_GETWORKAREA=48PublicSubCenterForm(frmAsForm)DimRAsRECT,IResAs1.ong,DimIWAs1.ong,IHAs1.ongIRes三SystemParameterslnfo(_Splgetworkarea,o,r,o)IfIResThenWithR.1.eft=Screen-TwipsPerPixeIX.1.eft.Top=Scrn.TwlpsPrPlxlY.Top.RightsScreensTwipsPerPixeIXw.Right.Bottom=Screen.TwipsPerPixeIY*.BottomIW=.

22、Right-.1.eftIH=.Bottom-.Topfrm.Move.1.eft(IW-frm.Width)2,_.Top(IH-frm.Height)2EndWithEndIfEndSubNiCholaSSorokin,Sarasota,FloridaVB51.evel:IntermediateTieaMessageBoxtoDebg.AssertforAdvancedDebuggingPlacingamessageboxinanerrortrapcanprovideusefuldebugginginformation,butitdoesntallowyoutoreturntothesub

23、routineorfunctiontopokearoundandfurtherdebugthecode.Thisversionofamessageboxexpeditesdesign-timedebuggingbybreakingexecutionifthedeveloperpressesOK:PrivateFunctionMyDebugMsg(ByValaMessage_AsString)AsBooleanThisfunctionisusedforexpeditingdevelopmentIfMSgBOX(aMessage,VbOKCanceI,_,0KputsyouintotheError

24、Trap)=vbOKThenMyDebugMsg=FalseElseMyDebugMsg=TrueEndIfEndFunctionSamplesubPublicSubSetColor()OnErrorGoToSetCoIorErrorbodyofthesubroutinewouldgohere,forceanerrortodemonstrateError5SetCoIorErrorExit:ExitSubSetCoIorError:*InanerrortrapplacethislineinadditiontoanyothererrorhandlingcodeDebugaAssertMyDebu

25、gMsg(Err.Description&InSetCoIoru)othererrorhandlingcodeResumeSetCoIorErrorExitEndSub一SianMlynek,Burlington,Ontario,CanadaVB432,VB51.evel:IntermediateModernizeYourToolbar1.ookUsingonlyafewWindowsAPIcalls,youcanchangethestandardVB5toolbarintoanOffice97lk-alike.I,veimplementedtwodisplaystylesforthetool

26、bar.ThefirstallowsyoutochangethetoolbartoanOffice97-styletoolbar(similartotheoneusedbyVB5),andthesecondallowsyoutochangethetlbartotheInternetExplorer4.0-styletoolbar.Ifyouwanttousethesecondstyle,youmustsupplyeachbuttonwithsometextinordertoachievetheeffect.Inbothcases,thebuttonedgesareflatandonlyappe

27、arraisedwhenthemousepassesoverthebutton.Toimplementit,addthiscodetoaBASmodule:PrivateDeclareFunctionSendMessage1.ibusr32Alias_SendMessageA(ByVaIhwndAs1.ong,ByVaIWMSgAs1.ong,_ByVaIwParamAsInteger,ByVaIIParamAsAny)As1.ongPrivateDeclareFunctionFindWindowEx1.ibusr32Alias_FIndWIndowExA(ByVaIhWnd1As1.ong,

28、ByVaIhWnd2_As1.ong,ByVaIIpsz1AsString,ByVaIIpsz2As_String)As1.ongPrivateConstWM_USER=&H400PrivateConstTB_SETSTY1.E=WM_USER56PrivateConstTB_GETSTY1.E=WM_USER+57PrivateConstTBSTY1.E_F1.AT=&H800PrivateConstTBSTY1.E_1.IST=&H1000PublicSub0ffice97Toolbar(tlbAsToolbar,_tlbToolbarStyteAs1.ong)DimIngStyIeAs1

29、.ongDimIngResuttAs1.ongDimIngHWNDAs1.ongFindchildwindowandgetstylebitsIngHWND=FindWindowEx(tlb.hwnd,0&,_TlbarWindow32,VbNuIIString)IngStyIe=SendMeSSage(IngHWND,一TB_GETSTY1.E,0&,0&)UseacasestatementtogettheeffectSelectCaseIlbTooIbarStyIeCase 1:CreatesanOffice97liketoolbarIngStyIe=IngStyIeOrTBSTY1.E_F

30、1.ATCase 2:CreatesanExplorer4.0liketoolbar,withtexttotherightofthepicture.Youmustprovidetextinordertogettheeffect.IngStyIe=IngStyIeOrTBSTY1.E_F1.AT_OrTBSTY1.E_1.ISTCaseElseIngStyIe=IngStyIeOrTBSTY1.E_F1.ATEndSelectUsetheAPIcalltochangethetoolbarIngResuIt=SendMessage(lngHWND,_TB_SETSTY1.E,0,IngStyIe)

31、Showtheeffectstlb.RefreshEndSubCallthisroutinewhileaformwithatoolbarisloading:PrivateSubForm_1.oad()CallOffice97Toolbar(Me.Toolbar1,2)whatever.EndSub-Michiel1.eij,TheNetherlandsVB3,VB416/32,VB51.evel:IntermediateForceanMDIWindowRefreshIsometimeswantanMDIparentwindowtoberepainted.Forexample,ifamodald

32、ialogisdisplayedovertheMDIformandyouclickonOK,thedialogishiddenandanoperationoccurs,whichtakesafewsecondstocomplete.Inthemeantime,remnantsofthedialogarestillvisiblebecauseWindowsdoesnthavetimetocompletethepaintoperation,andthescreenlooksmessy.MDIformsdonthaveaRefreshmethod,andIdontwanttothrowaDoEven

33、tsintomycodebecauseitsdangerous.ThiscodegivesmyMDIformaRefreshmethod:PublicSubRefresh()CallRedrawWindow(Me.hWndt0&,0&,_RDW_A1.1.CHI1.DRENOrRDWjJPDATENOW)EndSubYouneedtodeclaretheseAPInstants:PublicConstRDW_A1.1.CHI1.DREN=&H80PublicConstRDWeUPDATENOW=&H100Note:ThedatatypeoftheIprcUpdateparameterhasbe

34、enchanged,fromRECTtoAnyso0&(NU1.1.)canbepassed.MfWin32ThenDeclareFunctionRedrawWincJow1.ib_,user32,t(ByVaIhwndAs1.ong,_IprcUpdateAsAny,ByVaIhrgnUpdate_As1.ong,ByVaIfuRedrawAs1.ong)As1.ong#EISelfWin16ThenDeclareFunctionRedrawWindow1.ib”User”_(ByVaIhWndAsInteger,IprcUpdateAsAny,_ByVaIhrgnUpdateAsInteg

35、er,ByVaIfuRedrawAs_Integer)AsInteger#EndifThomasWeiss,BUffaloGroveJIinoisVB51.evel:BeginningTakeAdvantageofRelatedDocumentsAreainProjectWindowIfyouusearesourcefileinyourapplication,youcanseetheRESfileappearintheprojectwindowunderRelatedDocuments.ThisistheonlytypeoffilethatVBautomaticallyaddstothisno

36、deoftheprojecttree.Youcanaddanytypeoffileyouliketothisareamanually,though.FromtheProjectmenu,selectAddFile,orright-clickontheprojectwindowandselectAddFilefromthecontextmenu.Inthedialogbox,selectAllFilesforthefiletypeandchecktheAddAsRelatedDocumentoption.Addingadditionalrelatedfilesherehelpsorganizey

37、ourprojectandgivesyouquickaccesstousefulitems,includingdesigndocuments,databases,resourcescripts,help-projectfiles,andsoon.Onceafilehasbeenadded,double-clickonitintheprojectwindowtoopenitwiththeappropriateapplication.JoeGarrick,CoonRapids,MinneSe)IaVB432,VB51.evel:AdvancedCopyDrawnPicturetoClipboard

38、TheVBPicturecontrolcanholdseveraldifferentformatsofpictures:BMP1DIB,ICO,CUR,WMF,andothersunderVB5.Additionally,youcanusegraphicsmethodstodrawonthecontrol.Theonlynativemethodthatnvertstheimageonthepicturecontrol,includingthedrawngraphics,toabitmapandtransfersthebitmaptothesystemclipboardrequiresyouto

39、useAutoRedraw.However,thistechniquecausesproblems.ThiscodeshowsthedeclarationsandfunctionsrequiredtotransfertheimageonaVBpicturentroltothesystemclipboardasabitmap.AddthiscodetoaBASmodule,callPicToCIip,andpassthepictureboxastheonlyparameter:#APIDeclarations#BitmapPrivateDeclareFunctionBItBIt1.ibMgdl3

40、2M_(ByVaIhDestDCAs1.ong,ByVaIxAs1.ong,_ByVaIyAs1.ong,ByVaInWidthAs1.ong._ByVaInHeightAs1.ong.ByVaIhSrcDCAs_1.onglByVaIxSrcAs1.ong,ByVaIySrcAs_1.ong1ByVaIdwRopAs1.ong)As1.ongPrivateDeclareFunction_CreateCompatibIeBitmap1.ibMgdi320(ByVaIhDCAs1.ong,ByVaInWidthAs1.ong,ByVaInHeightAs1.ong)As1.ongPrivateD

41、eclareFunctionCreateCompatibIeDC_1.ib,gdi32,(ByVaIhDCAs1.ong)As1.ongPrivateDeclareFunctionDeIeteDC1.lb_“gdi32(ByVaIhDCAs1.ong)As1.ongPrivateDeclareFunctionGetDC1.ibMuser32M_(ByVaIhWndAs1.ong)As1.ongPrivateDeclareFunctionReIeaseDC1.ibuser32_(ByVaIhWndAs1.ong,ByVaIhDCAs1.ong)As1.ongPrivateDeclareFunct

42、ionSeIectObject1.ib”gdi32_(ByVaIhDCAs1.ong.ByVaIhbjectAs1.ong)As1.ongClipboardPrivateDeclareFunctionOpenCIipboard1.ib_Muser32M(ByVaIhWndAs1.ong)As1.ongPrivateDeclareFunctionCloseCIIpboard1.ib_uuser32()As1.ongPrivateDeclareFunctionEmptyCIipboard1.ib_*,user32,()As1.ongPrivateDeclareFunctionSetCIipboar

43、dData1.lb,user32*-(ByVaIwFormatAs1.ong,ByVaIhMemAs1.ong)As1.ong*#APIConstants#ClipboardformatsPrivateConstCF_BITMAP=2ROPPrivateConstSRCCOPY=&HCC0020PublicSubPicToClip(picAsPictureBox)DimhSourceDCAs1.ongDimhMemoryDCAs1.ongDimIWidthAs1.ongDimIHeightAs1.ongDimhBltmapAs1.ongDimhOldBitmapAs1.ong#NOTE:Err

44、ortrappinghasbeenremovedforthesakeofclarity*WithpicDeterminebitmapsizeIWidth=.Parent.ScaleX(.ScaleWidth,_.ScaIeMode,vbPIxels)IHeight=.Parent.ScaleY(.ScaleHeight,_.ScaIeMode,vbPixels),GethBltmaploadedwithImageon,PicturecontrolhSourceDC=GetDC(.hWnd)KMemoryDC=CreateCompatibleDC(.hDC)hBltmap=CreateCompa

45、tlbleBltmap(_.hDC,!Width,!Height)hOIdBitmap=SelectObject(hMemoryDC,_hBrtmap)CallBitBlt(hMemoryDC,O,O,IWidth,_(Height,pic.hDC,O.O.SRCCOPY)hBitmap三SelectObject(hMemoryDC,_hOldBltmap)CopytoclipboardCallOpenClipboard(.Parent.hWnd)CallEmptyCIIpboardCallSetCliPboardData(CF_BlTMAP,_hBitmap)CallCloseCIipboa

46、rdCleanupGDICallReleaseDC(.hWnd,hSourceDC)CallSelectObject(hMemoryDC,hBitmap)CallDeleteDC(hMemoryDC)EndWithEndSubTomMcCormick.Bedford.MaSSaChUSettSVB416/32,VB51.evel:BeginningEraseaVariantArrayYoullfindtheIsArrayOfunctionhelpfulwhenyouuseVariantarraysthatyoucansetorunsetthroughyourcodeandneedtotesto

47、ften.However,onceyoudeclarethearray,IsArrayOreturnsTrue,evenifthearrayhasbeenerasedusingtheErasekeyword.Tosolvethis,resetaVariantarraybyassigningzeroornull,sotheIsArrayOfunctionreturnsthepropervalue:DimmyVarAsVariantDebug.PrintlsArray(myVar)ReturnsFalseReDimmyVar(OTo5)Debug.PrintlsArray(myVar)ReturnsTrueErasemyVarDebug.PrintlsArray(myVar)ReturnsTruemyVar三ODebug.Printls

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

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


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号