Visual basic 6


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Visual basic 6

  1. 1. Visual Basic 6 Black Book:Table of ContentsVisual Basic 6 Black Book(Publisher: The Coriolis Group)Author(s): Steven HolznerISBN: 1576102831Publication Date: 08/01/98IntroductionWhats On the CD-ROMAbout the AuthorChapter 1Visual Basic OverviewCreating A Project In Visual BasicThe Parts Of A Visual Basic ProjectProject ScopeProjects On DiskUsing The Visual Basic Application WizardVisual Basic Programming ConventionsCode Commenting ConventionsBest Coding Practices In Visual BasicGetting Down To The DetailsChapter 2The Visual Basic Development EnvironmentIn DepthOverview Of The Integrated Development EnvironmentImmediate SolutionsSelecting IDE Colors, Fonts, And Font SizesAligning, Sizing, And Spacing Multiple ControlsSetting A Startup Form Or Procedure (1 of 35) [3/14/2001 1:24:08 AM]
  2. 2. Visual Basic 6 Black Book:Table of ContentsUsing Visual Basic Predefined Forms, Menus, And ProjectsSetting A Projects Version InformationSetting An EXE Files Name And IconDisplaying The Debug, Edit, And Form Editor ToolbarsTurning Bounds Checking On Or OffChecking For Pentium ErrorsManaging Add-InsAdding ActiveX Controls And Insertable Objects To ProjectsCustomizing Menus And ToolbarsSetting Forms Initial PositionsEnabling Or Disabling Quick Info, Auto List Members, Data Tips, And SyntaxCheckingDisplaying Or Hiding IDE WindowsSearching An Entire Project For Specific Text Or A Variables DefinitionOptimizing For Fast Code, Small Code, Or A Particular ProcessorAdding And Removing Forms, Modules, And Class ModulesUsing BookmarksUsing The Object BrowserChapter 3The Visual Basic LanguageIn DepthHow Does Visual Basic Code Look?Immediate SolutionsDeclaring ConstantsDeclaring VariablesSelecting Variable TypesConverting Between Data Types (2 of 35) [3/14/2001 1:24:08 AM]
  3. 3. Visual Basic 6 Black Book:Table of ContentsSetting Variable ScopeVerifying Data TypesDeclaring Arrays And Dynamic ArraysDeclaring SubroutinesDeclaring FunctionsPreserving Variables Values Between Calls To Their ProceduresHandling StringsConverting Strings To Numbers And Back AgainHandling Operators And Operator PrecedenceUsing If&Else StatementsUsing Select CaseMaking Selections With Switch() And Choose()LoopingUsing CollectionsSending Keystrokes To Other ProgramsHandling Higher MathHandling Dates And TimesHandling Financial DataEnding A Program At Any TimeChapter 4Managing Forms In Visual BasicIn DepthThe Parts Of A FormThe Parts Of An MDI FormImmediate SolutionsSetting Title Bar Text (3 of 35) [3/14/2001 1:24:08 AM]
  4. 4. Visual Basic 6 Black Book:Table of ContentsAdding/Removing Min/Max Buttons And Setting A Windows BorderAdding Toolbars To FormsAdding Status Bars To FormsReferring To The Current FormRedrawing Form ContentsSetting Control Tab OrderMoving And Sizing Controls From CodeShowing And Hiding Controls In A FormMeasurements In FormsWorking With Multiple FormsLoading, Showing, And Hiding FormsSetting The Startup FormCreating Forms In CodeUsing The Multiple Document InterfaceArranging MDI Child WindowsOpening New MDI Child WindowsArrays Of FormsCoordinating Data Between MDI Child Forms (Document Views)Creating Dialog BoxesAll About Message Boxes And Input BoxesPassing Forms To ProceduresMinimizing/Maximizing And Enabling/Disabling Forms From CodeChapter 5Visual Basic MenusIn DepthMenu Design Considerations (4 of 35) [3/14/2001 1:24:08 AM]
  5. 5. Visual Basic 6 Black Book:Table of ContentsImmediate SolutionsUsing The Visual Basic Application Wizard To Set Up Your MenusWhat Item Goes In What Menu?Adding A Menu To A FormModifying And Deleting Menu ItemsAdding A Menu SeparatorAdding Access CharactersAdding Shortcut KeysCreating SubmenusCreating Immediate (Bang) MenusUsing The Visual Basic Predefined MenusAdding A Checkmark To A Menu ItemDisabling (Graying Out) Menu ItemsHandling MDI Form And MDI Child MenusAdding A List Of Open Windows To An MDI Forms Window MenuMaking Menus And Menu Items Visible Or InvisibleCreating And Displaying Pop-Up MenusAdding And Deleting Menu Items At RuntimeAdding Bitmaps To MenusUsing The Registry To Store A Most Recently Used (MRU) Files ListChapter 6Text Boxes And Rich Text BoxesIn DepthUse Of Text Boxes And RTF Boxes In Windows ProgramsImmediate SolutionsCreating Multiline, Word-Wrap Text Boxes (5 of 35) [3/14/2001 1:24:08 AM]
  6. 6. Visual Basic 6 Black Book:Table of ContentsAligning Text In Text BoxesAdding Scroll Bars To Text BoxesMaking A Text Box Read-OnlyAccessing Text In A Text BoxSelecting And Replacing Text In A Text BoxCopying Or Getting Selected Text To Or From The ClipboardCreating A Password ControlControlling Input In A Text BoxAdding An RTF Box To A FormAccessing Text In A Rich Text BoxSelecting Text In Rich Text BoxesUsing Bold, Italic, Underline, And StrikethruIndenting Text In Rich Text BoxesSetting Fonts And Font Sizes In Rich Text BoxesUsing Bullets In Rich Text BoxesAligning Text In A Rich Text BoxSetting Text Color In RTF BoxesMoving The Insertion Point In RTF BoxesAdding Superscripts And Subscripts In Rich Text BoxesSetting The Mouse Pointer In Text Boxes And Rich Text BoxesSearching For (And Replacing) Text In RTF BoxesSaving RTF Files From Rich Text BoxesReading RTF Files Into A Rich Text BoxPrinting From A Rich Text BoxChapter 7Command Buttons, Checkboxes, And Option Buttons (6 of 35) [3/14/2001 1:24:08 AM]
  7. 7. Visual Basic 6 Black Book:Table of ContentsIn DepthHow This Chapter WorksImmediate SolutionsSetting A Buttons CaptionSetting A Buttons Background ColorSetting Button Text ColorSetting Button FontsReacting To Button ClicksCreating Button Control ArraysResetting The Focus After A Button ClickGiving Buttons Access CharactersSetting Button Tab OrderDisabling ButtonsShowing And Hiding ButtonsAdding Tool Tips To ButtonsResizing And Moving Buttons From CodeAdding A Picture To A ButtonAdding A Down Picture To A ButtonAdding Buttons At RuntimePassing Buttons To ProceduresHandling Button ReleasesMaking A Command Button Into A Cancel ButtonGetting A Checkboxs StateSetting A Checkboxs StateGrouping Option Buttons TogetherGetting An Option Buttons State (7 of 35) [3/14/2001 1:24:08 AM]
  8. 8. Visual Basic 6 Black Book:Table of ContentsSetting An Option Buttons StateUsing Graphical Checkboxes And Radio ButtonsUsing Checkboxes And Option Buttons TogetherChapter 8List Boxes And Combo BoxesIn DepthImmediate SolutionsAdding Items To A List BoxReferring To Items In A List Box By IndexResponding To List Box EventsRemoving Items From A List BoxSorting A List BoxDetermining How Many Items Are In A List BoxDetermining If A List Box Item Is SelectedUsing Multiselect List BoxesMaking List Boxes Scroll HorizontallyUsing Checkmarks In A List BoxClearing A List BoxCreating Simple Combo Boxes, Drop-Down Combo Boxes, And Drop-Down ListCombo BoxesAdding Items To A Combo BoxResponding To Combo Box SelectionsRemoving Items From A Combo BoxGetting The Current Selection In A Combo BoxSorting A Combo BoxClearing A Combo BoxLocking A Combo Box (8 of 35) [3/14/2001 1:24:08 AM]
  9. 9. Visual Basic 6 Black Book:Table of ContentsGetting The Number Of Items In A Combo BoxSetting The Topmost Item In A List Box Or Combo BoxAdding Numeric Data To Items In A List Box Or Combo BoxDetermining Where An Item Was Added In A Sorted List Box Or Combo BoxUsing Images In Combo BoxesChapter 9Scroll Bars And SlidersIn DepthAdding Scroll Bars And Sliders To A ProgramImmediate SolutionsAdding Horizontal Or Vertical Scroll Bars To A FormSetting Scroll Bars Minimum And Maximum ValuesSetting Up Scroll Bar Clicks (Large Changes)Setting Up Scroll Bar Arrow Clicks (Small Changes)Getting A Scroll Bars Current ValueHandling Scroll Bar EventsHandling Continuous Scroll Bar EventsShowing And Hiding Scroll BarsCoordinating Scroll Bar PairsAdding Scroll Bars To Text BoxesCreating And Using Flat Scroll BarsCustomizing Flat Scroll Bar ArrowsCreating Slider ControlsSetting A Sliders OrientationSetting A Sliders RangeSetting Up Slider Groove Clicks (9 of 35) [3/14/2001 1:24:08 AM]
  10. 10. Visual Basic 6 Black Book:Table of ContentsAdding Ticks To A SliderSetting A Sliders Tick StyleGetting A Sliders Current ValueHandling Slider EventsHandling Continuous Slider EventsHandling Slider SelectionsClearing A Selection In A SliderCreating An Updown ControlSetting An Updown Controls Minimum And MaximumHandling Updown EventsChapter 10Picture Boxes And Image ControlsIn DepthImage ControlsPicture BoxesImmediate SolutionsAdding A Picture Box To A FormSetting Or Getting The Picture In A Picture BoxAdjusting Picture Box Size To ContentsAligning A Picture Box In A FormHandling Picture Box Events (And Creating Image Maps)Picture Box AnimationGrouping Other Controls In A Picture BoxUsing A Picture Box In An MDI FormDrawing Lines And Circles In A Picture BoxUsing Image Lists With Picture Boxes (10 of 35) [3/14/2001 1:24:08 AM]
  11. 11. Visual Basic 6 Black Book:Table of ContentsAdding Text To A Picture BoxFormatting Text In A Picture BoxClearing A Picture BoxAccessing Individual Pixels In A Picture BoxCopying Pictures To And Pasting Pictures From The ClipboardStretching And Flipping Images In A Picture BoxPrinting A PictureUsing Picture Box HandlesSetting Measurement Scales In A Picture BoxSaving Pictures To DiskAdding An Image Control To A FormStretching An Image In An Image ControlChapter 11Windows Common DialogsIn DepthThe Common Dialog ControlImmediate SolutionsCreating And Displaying A Windows Common DialogSetting A Common Dialogs TitleDid The User Click OK Or Cancel?Using A Color Dialog BoxSetting Color Dialog FlagsUsing The Open And Save As DialogsSetting Open And Save As FlagsGetting The File Name In Open, Save As DialogsSetting Maximum File Name Size In Open And Save As Dialog Boxes (11 of 35) [3/14/2001 1:24:08 AM]
  12. 12. Visual Basic 6 Black Book:Table of ContentsSetting Default File ExtensionsSet Or Get The Initial DirectorySetting File Types (Filters) In Open, Save As DialogsUsing A Font Dialog BoxSetting Font Dialog FlagsSetting Max And Min Font SizesUsing The Print Dialog BoxSetting Print Dialog FlagsSetting The Minimum And Maximum Pages To PrintSetting Page OrientationShowing Windows Help From A Visual Basic ProgramChapter 12The Chart And Grid ControlsIn DepthThe Chart ControlGrid ControlsImmediate SolutionsAdding A Chart Control To A ProgramAdding Data To A Chart ControlWorking With A Multiple Data SeriesSetting Chart And Axis Titles And Chart ColorsCreating Pie ChartsCreating 2D And 3D Line ChartsCreating 2D And 3D Area ChartsCreating 2D And 3D Bar ChartsCreating 2D And 3D Step Charts (12 of 35) [3/14/2001 1:24:09 AM]
  13. 13. Visual Basic 6 Black Book:Table of ContentsCreating 2D And 3D Combination ChartsAdding A Flex Grid Control To A ProgramWorking With Data In A Flex Grid ControlTyping Data Into A Flex GridSetting Flex Grid Grid Lines And Border StylesLabeling Rows And Columns In A Flex GridFormatting Flex Grid CellsSorting A Flex Grid ControlDragging Columns In A Flex Grid ControlConnecting A Flex Grid To A DatabaseChapter 13The Timer And Serial Communications ControlsIn DepthThe Timer ControlThe Communications ControlThe MonthView And DateTimePicker ControlsImmediate SolutionsAdding A Timer Control To A ProgramInitializing A Timer ControlHandling Timer EventsFormatting Times And DatesCreating A Clock ProgramCreating A StopwatchCreating An Alarm ClockCreating Animation Using The Timer ControlAdding A Communications Control To A Program (13 of 35) [3/14/2001 1:24:09 AM]
  14. 14. Visual Basic 6 Black Book:Table of ContentsSetting Up The Receive And Transmit BuffersOpening The Serial PortWorking With A ModemReading Data With The Communications ControlSending Data With The Communications ControlSetting Up Communications HandshakingHandling Communications EventsClosing The Serial PortAdding A MonthView Control To Your ProgramGetting Dates From A MonthView ControlAdding A DateTimePicker Control To Your ProgramUsing A DateTimePicker ControlChapter 14The Frame, Label, Shape, And Line ControlsIn DepthThe Frame ControlThe Label ControlThe Shape ControlThe Line ControlForm Drawing MethodsImmediate SolutionsAdding A Frame To A ProgramSetting Frame Size And LocationDragging And Dropping ControlsGrouping Controls In A FrameAdding A Label To A Program (14 of 35) [3/14/2001 1:24:09 AM]
  15. 15. Visual Basic 6 Black Book:Table of ContentsUsing Labels Instead Of Text BoxesFormatting Text In LabelsAligning Text In LabelsHandling Label Control EventsUsing Labels To Give Access Keys To Controls Without CaptionsAdding A Shape Control To A ProgramDrawing RectanglesDrawing SquaresDrawing OvalsDrawing CirclesDrawing Rounded RectanglesDrawing Rounded SquaresSetting Shape Borders: Drawing Width, Dashes, And DotsFilling ShapesDrawing A Shape Without The IDE GridMoving Shapes At RuntimeAdding A Line Control To A ProgramDrawing Thicker, Dotted, And Dashed LinesDrawing A Line Without The IDE GridChanging A Line Control At RuntimeUsing Form Methods To Draw LinesUsing Form Methods To Draw CirclesChapter 15Toolbars, Status Bars, Progress Bars, And CoolbarsIn DepthToolbars (15 of 35) [3/14/2001 1:24:09 AM]
  16. 16. Visual Basic 6 Black Book:Table of ContentsStatus BarsProgress BarsCoolbarsImmediate SolutionsAdding A Toolbar To A FormAligning Toolbars In A FormAdding Buttons To A ToolbarHandling Toolbar Buttons ClicksConnecting Toolbar Buttons To Menu ItemsAdding Separators To A ToolbarAdding Images To Toolbar ButtonsAdding Check (Toggle) Buttons To A ToolbarCreating Button Groups In A ToolbarAdding Combo Boxes And Other Controls To A ToolbarSetting Toolbar Button Tool TipsLetting The User Customize The ToolbarAdding Toolbar Buttons At RuntimeAdding A Status Bar To A ProgramAligning Status Bars In A FormAdding Panels To A Status BarDisplaying Text In A Status BarDisplaying Time, Dates, And Key States In A Status BarCustomizing A Status Bar Panels AppearanceDisplaying Images In A Status BarHandling Panel ClicksAdding New Panels To A Status Bar At Runtime (16 of 35) [3/14/2001 1:24:09 AM]
  17. 17. Visual Basic 6 Black Book:Table of ContentsCreating Simple Status BarsAdding A Progress Bar To A FormUsing A Progress BarAdding A Coolbar To A FormAligning Coolbars In A FormAdding Bands To A CoolbarAdding Controls To Coolbar BandsHandling Coolbar Control EventsChapter 16Image Lists, Tree Views, List Views, And Tab StripsIn DepthImage ListsTree ViewsList ViewsTab StripsImmediate SolutionsAdding An Image List To A FormAdding Images To Image ListsUsing The Images In Image ListsSetting Image Keys In An Image ListAdding A Tree View To A FormSelecting Tree View StylesAdding Nodes To A Tree ViewAdding Subnodes To A Tree ViewAdding Images To A Tree ViewExpanding And Collapsing Nodes (And Setting Node Images To Match) (17 of 35) [3/14/2001 1:24:09 AM]
  18. 18. Visual Basic 6 Black Book:Table of ContentsHandling Tree View Node ClicksAdding A List View To A FormAdding Items To A List ViewAdding Icons To List View ItemsAdding Small Icons To List View ItemsSelecting The View Type In List ViewsAdding Column Headers To A List ViewAdding Column Fields To A List ViewHandling List View Item ClicksHandling List View Column Header ClicksAdding A Tab Strip To A FormInserting Tabs Into A Tab Strip ControlSetting Tab CaptionsSetting Tab ImagesUsing A Tab Strip To Display Other ControlsHandling Tab ClicksChapter 17File Handling And File ControlsIn DepthSequential Access FilesBinary FilesThe FileSystemObjectImmediate SolutionsUsing The Common Dialogs File Open And File Save AsCreating A FileGetting A Files Length (18 of 35) [3/14/2001 1:24:09 AM]
  19. 19. Visual Basic 6 Black Book:Table of ContentsOpening A FileWriting To A Sequential FileWriting To A Random Access FileWriting To A Binary FileReading From Sequential FilesReading From Random Access FilesReading From Binary FilesAccessing Any Record In A Random Access FileClosing A FileSaving Files From Rich Text BoxesOpening Files In Rich Text BoxesSaving Files From Picture BoxesOpening Files In Picture BoxesUsing The Drive List Box ControlUsing The Directory List Box ControlUsing The File List Box ControlCreating And Deleting DirectoriesChanging DirectoriesCopying A FileMoving A FileDeleting A FileWhen Was A File Created? Last Modified? Last Accessed?Creating A TextStreamOpening A TextStreamWriting To A TextStreamReading From A TextStream (19 of 35) [3/14/2001 1:24:09 AM]
  20. 20. Visual Basic 6 Black Book:Table of ContentsClosing A TextStreamChapter 18Working With GraphicsIn DepthGraphics Methods Vs. Graphics ControlsAbout Visual Basic CoordinatesImmediate SolutionsRedrawing Graphics In Windows: AutoRedraw And PaintClearing The Drawing AreaSetting ColorsDrawing TextWorking With FontsDrawing LinesDrawing BoxesDrawing CirclesDrawing EllipsesDrawing ArcsDrawing Freehand With The MouseFilling Figures With ColorFilling Figures With PatternsSetting Figure Drawing Style And Drawing WidthDrawing PointsSetting The Drawing ModeSetting Drawing ScalesUsing The Screen ObjectResizing Graphics When The Window Is Resized (20 of 35) [3/14/2001 1:24:09 AM]
  21. 21. Visual Basic 6 Black Book:Table of ContentsCopying Pictures To And Pasting Pictures From The ClipboardPrinting GraphicsLayering Graphics With The AutoRedraw And ClipControls PropertiesChapter 19Working With ImagesIn DepthPicture Boxes Vs. Image ControlsImage Effects: Working With Images Bit By BitImmediate SolutionsAdding Images To ControlsAdding Images To FormsUsing Image ControlsUsing Picture BoxesAutoSizing Picture BoxesLoading Images In At RuntimeClearing (Erasing) ImagesStoring Images In Memory Using The Picture ObjectUsing Arrays Of Picture ObjectsAdding Picture Clip Controls To A ProgramSelecting Images In A Picture Clip Control Using CoordinatesSelecting Images In A Picture Clip Control Using Rows And ColumnsFlipping ImagesStretching ImagesCreating Image AnimationHandling Images Bit By BitCreating Grayscale Images (21 of 35) [3/14/2001 1:24:09 AM]
  22. 22. Visual Basic 6 Black Book:Table of ContentsLightening ImagesCreating Embossed ImagesCreating Engraved ImagesSweeping ImagesBlurring ImagesFreeing Memory Used By GraphicsChapter 20Creating ActiveX Controls And DocumentsIn DepthAll About ActiveX ComponentsIn-Process Vs. Out-Of-Process ComponentsWhich ActiveX Component Do I Want To Build?Immediate SolutionsCreating An ActiveX ControlDesigning An ActiveX Control From ScratchGiving ActiveX Controls Persistent GraphicsBasing An ActiveX Control On An Existing Visual Basic ControlHandling Constituent Control Events In An ActiveX ControlAdding Controls To An ActiveX Control (A Calculator ActiveX Control)Testing An ActiveX ControlCreating A Visual Basic Project Group To Test An ActiveX ControlRegistering An ActiveX ControlUsing A Custom ActiveX Control In A Visual Basic ProgramAdding A Property To An ActiveX ControlMaking ActiveX Control Properties Persistent (PropertyBag Object)Adding A Method To An ActiveX Control (22 of 35) [3/14/2001 1:24:09 AM]
  23. 23. Visual Basic 6 Black Book:Table of ContentsAdding An Event To An ActiveX ControlAdding Design Time Property PagesCreating An ActiveX DocumentActiveX Document DLLs Vs. EXEsAdding Controls To An ActiveX Document (A Tic-Tac-Toe Example)Handling Constituent Control Events In An ActiveX DocumentTesting An ActiveX DocumentCreating ActiveX Documents That Run Outside Visual BasicDistributed Computing: ActiveX Documents And Integrated BrowsersMaking ActiveX Document Properties Persistent (PropertyBag Object)Chapter 21Visual Basic And The Internet: Web Browsing, Email, HTTP, FTP,And DHTMLIn DepthCreating A Web BrowserCreating A Dynamic HTML PageWorking With EmailUsing FTPUsing HTTPImmediate SolutionsCreating A Web BrowserSpecifying URLs In A Web BrowserAdding Back And Forward Buttons To A Web BrowserAdding Refresh, Home, And Stop Buttons To A Web BrowserCreating DHTML PagesAdding Text To DHTML PagesAdding Images To DHTML Pages (23 of 35) [3/14/2001 1:24:09 AM]
  24. 24. Visual Basic 6 Black Book:Table of ContentsAdding HTML Controls To DHTML PagesAdding ActiveX Controls To DHTML PagesAdding Tables To DHTML PagesAdding Hyperlinks To DHTML PagesUsing MAPI Controls To Support EmailSending Email From Visual BasicReading Email In Visual BasicUsing The Internet Transfer Control For FTP And HTTP OperationsHandling FTP Operations In Visual BasicHandling HTTP Operations In Visual BasicChapter 22MultimediaIn DepthThe Multimedia MCI ControlUsing The Multimedia Control From CodeImmediate SolutionsUsing The Animation ControlAdding A Multimedia Control To A ProgramSetting The Device Type And Opening The DeviceSetting File Information And Opening FilesSetting A Multimedia Controls Time FormatControlling The Multimedia Control From CodeStopping And Pausing The Multimedia ControlDisplaying The Multimedia Controls StatusClosing The Multimedia ControlPlaying CDs From Your CD-ROM Drive (24 of 35) [3/14/2001 1:24:09 AM]
  25. 25. Visual Basic 6 Black Book:Table of ContentsPlaying WAV FilesPlaying MID FilesPlaying AVI FilesPlaying MPG FilesKeeping Track Of Multimedia Command Execution Using NotificationHandling Multimedia ErrorsStepping A Multimedia Control Forward Or Backward Frame By FrameStarting From And To In A Multimedia ControlMaking The Multimedia Control WaitMultimedia Without Multimedia ControlsChapter 23Connecting To The Windows API And Visual C++In DepthDeclaring And Using DLL Procedures In Visual BasicHandling C/C++ And Windows Data TypesWhats Available In The Windows API?Immediate SolutionsGetting Or Creating A Device Context (Including The Whole Screen)Drawing Lines In A Device ContextDrawing Ellipses In A Device ContextDrawing Rectangles In A Device ContextSetting Drawing Colors And Styles (Using Pens)Setting Drawing Modes (ROP2)Handling The Mouse Outside Your Programs WindowCopying Bitmaps Between Device Contexts QuicklyCapturing Images From The Screen (25 of 35) [3/14/2001 1:24:09 AM]
  26. 26. Visual Basic 6 Black Book:Table of ContentsGetting A Window Handle For Any Window On The ScreenGetting A Windows TextPlaying Sounds With API FunctionsAllocating Memory And Storing DataReading Data From Memory And Deallocating MemoryMaking A Window TopmostDetermining Free And Total Disk SpaceDetermining The Windows DirectoryConnecting To Visual C++Chapter 24Databases: Using DAO, RDO, And ADOIn DepthWhat Are Databases?DAORDOADOThe Data-Bound ControlsImmediate SolutionsCreating And Managing Databases With The Visual Data ManagerCreating A Table With The Visual Data ManagerCreating A Field With The Visual Data ManagerEntering Data In A Database With The Visual Data ManagerAdding A Data Control To A ProgramOpening A Database With The Data ControlConnecting A Data Control To A Bound ControlRegistering An ODBC Source (26 of 35) [3/14/2001 1:24:09 AM]
  27. 27. Visual Basic 6 Black Book:Table of ContentsOpening A Database With A Remote Data ControlConnecting A Remote Data Control To A Bound ControlOpening A Database With An ADO Data ControlConnecting An ADO Data Control To A Bound ControlThe Data Form Wizard: Creating A Data FormUsing Database Control Methods: Adding, Deleting, And Modifying RecordsAdding Records To DatabasesDeleting Records In DatabasesRefreshing A Data ControlUpdating A Database With ChangesMoving To The Next RecordMoving To The Previous RecordMoving To The First RecordMoving To The Last RecordThe Data-Bound Controls: From Text Boxes To Flex GridsThe ADO Data-Bound ControlsChapter 25Working With Database Objects In CodeIn DepthDAORDOADOImmediate SolutionsA Full-Scale DAO ExampleUsing The Daocode Example To Create And Edit A DatabaseDAO: Creating A Database (27 of 35) [3/14/2001 1:24:09 AM]
  28. 28. Visual Basic 6 Black Book:Table of ContentsDAO: Creating A Table With A TableDef ObjectDAO: Adding Fields To A TableDef ObjectDAO: Adding An Index To A TableDef ObjectDAO: Creating A Record SetDAO: Opening A DatabaseDAO: Adding A Record To A Record SetDAO: Editing A Record In A Record SetDAO: Updating A Record In A Record SetDAO: Moving To The First Record In A Record SetDAO: Moving To The Last Record In A Record SetDAO: Moving To The Next Record In A Record SetDAO: Moving To The Previous Record In A Record SetDAO: Deleting A Record In A Record SetDAO: Sorting A Record SetDAO: Searching A Record SetDAO: Executing SQLA Full-Scale RDO ExampleRDO: Opening A ConnectionRDO: Creating A Result SetRDO: Moving To The First Record In A Result SetRDO: Moving To The Last Record In A Result SetRDO: Moving To The Next Record In A Result SetRDO: Moving To The Previous Record In A Result SetRDO: Executing SQLA Full-Scale ADO ExampleADO: Opening A Connection (28 of 35) [3/14/2001 1:24:09 AM]
  29. 29. Visual Basic 6 Black Book:Table of ContentsADO: Creating A Record Set From A ConnectionADO: Binding Controls To Record SetsADO: Adding A Record To A Record SetADO: Refreshing The Record SetADO: Updating A Record In A Record SetADO: Moving To The First Record In A Record SetADO: Moving To The Last Record In A Record SetADO: Moving To The Next Record In A Record SetADO: Moving To The Previous Record In A Record SetADO: Deleting A Record In A Record SetADO: Executing SQL In A Record SetChapter 26OLEIn DepthLinking Vs. EmbeddingImmediate SolutionsAdding An OLE Control To A FormCreating And Embedding An OLE Object At Design TimeLinking Or Embedding An Existing Document At Design TimeAutosizing An OLE ControlDetermining How An Object Is Displayed In An OLE Container ControlUsing The OLE Controls Pop-Up Menus At Design TimeInserting An OLE Object Into An OLE Control At RuntimeDeactivating OLE ObjectsUsing Paste Special To Insert A Selected Part Of A Document Into An OLEControlHow To Activate The OLE Objects In Your Program (29 of 35) [3/14/2001 1:24:09 AM]
  30. 30. Visual Basic 6 Black Book:Table of ContentsActivating OLE Objects With A Pop-Up Menu That Lists All OLE VerbsActivating OLE Objects From CodeIs An Object Linked Or Embedded?Handling Multiple OLE ObjectsUsing OLE Control Arrays To Handle Multiple OLE ObjectsLoading New OLE Controls At RuntimeDragging OLE Objects In A FormDeleting OLE ObjectsCopying And Pasting OLE Objects With The ClipboardZooming OLE ObjectsSaving And Retrieving Embedded Objects DataHandling OLE Object Updated EventsDisabling In-Place EditingChapter 27Creating Code Components (OLE Automation)In DepthCode Components: Classes And ObjectsCode Components And ThreadsImmediate SolutionsUsing A Code Component From A Client ApplicationCreating An Object From A ClassUsing A Code Components Properties And MethodsCreating A Code ComponentSetting A Code Components Project Type: In-Process Or Out-Of-ProcessAdding A Property To A Code ComponentAdding A Get/Let Property To A Code Component (30 of 35) [3/14/2001 1:24:09 AM]
  31. 31. Visual Basic 6 Black Book:Table of ContentsAdding A Method To A Code ComponentPassing Arguments To A Code Component MethodPassing Optional Arguments To A Code Component MethodTesting A Code Component With A Second Instance Of Visual BasicCreating And Registering An In-Process Code ComponentCreating And Registering An Out-Of-Process Code ComponentUsing The Class Initialize EventUsing The Class Terminate EventGlobal Objects: Using Code Components Without Creating An ObjectDestroying A Code Component ObjectUsing Forms From Code ComponentsCreating Dialog Box Libraries In Code ComponentsDesigning Multithreaded In-Process ComponentsDesigning Multithreaded Out-Of-Process ComponentsChapter 28Advanced Form, Control, And Windows Registry HandlingIn DepthDrag And Drop And OLE Drag And DropThe Windows RegistryImmediate SolutionsPassing Controls To ProceduresPassing Control Arrays To ProceduresDetermining The Active ControlDetermining Control Type At RuntimeCreating/Loading New Controls At RuntimeChanging Control Tab Order (31 of 35) [3/14/2001 1:24:09 AM]
  32. 32. Visual Basic 6 Black Book:Table of ContentsChanging Control Stacking Position With Z-OrderDrag/Drop: Dragging ControlsDrag/Drop: Dropping ControlsHandling Self-Drops When Dragging And DroppingDrag/Drop: Handling DragOver EventsOLE Drag/Drop: Dragging DataOLE Drag/Drop: Dropping DataOLE Drag/Drop: Reporting The Drag/Drop OutcomeUsing The Lightweight ControlsPassing Forms To ProceduresDetermining The Active FormUsing The Form Objects Controls CollectionUsing the Forms CollectionSetting A Forms Startup PositionKeeping A Forms Icon Out Of The Windows 95 TaskbarHandling Keystrokes In A Form Before Controls Read ThemMaking A Form ImmovableShowing Modal FormsSaving Values In The Windows RegistryGetting Values From The Windows RegistryGetting All Registry SettingsDeleting A Registry SettingChapter 29Error Handling And DebuggingIn DepthTesting Your Programs (32 of 35) [3/14/2001 1:24:09 AM]
  33. 33. Visual Basic 6 Black Book:Table of ContentsImmediate SolutionsWriting Error HandlersUsing On Error GoTo LabelUsing On Error GoTo line#Using On Error Resume NextUsing On Error GoTo 0Using Resume In Error HandlersUsing Resume Label In Error HandlersUsing Resume line# In Error HandlersUsing Resume Next In Error HandlersGetting An Errors Error CodeGetting An Errors DescriptionDetermining An Errors Source ObjectHandling Errors In DLLs: The LastDLLError PropertyCreating An Intentional (User-Defined) ErrorNested Error HandlingCreating An Error Object Directly In Visual BasicTrappable Cancel Errors In Common DialogsDebugging In Visual BasicSetting Debugging BreakpointsSingle-Stepping While DebuggingExamining Variables And ExpressionsAdding Debug Watch WindowsUsing The Immediate Window While DebuggingClearing All Debugging BreakpointsExecuting Code Up To The Cursor While Debugging (33 of 35) [3/14/2001 1:24:09 AM]
  34. 34. Visual Basic 6 Black Book:Table of ContentsSkipping Over Statements While DebuggingChapter 30Deploying Your Program: Creating Setup Programs, Help Files, AndOnline RegistrationIn DepthSetup ProgramsHelp FilesOnline RegistrationThe Designed For Microsoft Windows LogoImmediate SolutionsCreating Your Applications EXE FileUsing The Package And Deployment WizardStep 1: Package TypeStep 2: Build FolderStep 3: FilesStep 4: Distribution TypeStep 5: Installation TitleStep 6: IconsStep 7: Install LocationsStep 8: Shared FilesStep 9: Finished!Creating Help Files With The Microsoft Help WorkshopCreating A Help Projects RTF FileEntering Text In A Help FileCreating A Help HotspotCreating A Help Hotspot TargetTitling A Help Page (34 of 35) [3/14/2001 1:24:09 AM]
  35. 35. Visual Basic 6 Black Book:Table of ContentsAdding Help Topics To The Help IndexCreating Help Pop-Up LinksCreating Help Tool Tips TargetsCompiling Help Files With The Help WorkshopDisplaying A Help File From Visual BasicBuilding Online Help Into Your ApplicationCreating Online User RegistrationUploading Online Registration Information To An FTP ServerConcluding The FTP Transfer Of The Online Registration InformationIndex (35 of 35) [3/14/2001 1:24:09 AM]
  36. 36. Visual Basic 6 Black Book:IntroductionIntroductionWelcome to your Visual Basic support package. Thats what this book has beendesigned to be: your complete VB support package. Have we reached that goal yet? Its up to you to decide. If what youre looking for is not in this edition, well work hardto make sure its in the nextI encourage your suggestions. Please feel free to write.Well put in the time to make sure this book is the most complete one available onVisual Basic, edition after edition. This is the book we want you to come back toagain and again.Ive used Visual Basic back before version 1 even came out publicly and have writtenmany books on the program. I put Visual Basic to work for a very wide range of usesday after day; in fact, its is my favorite programming package of all, and it comesclose to being my favorite program period. But Ive never written a book on VisualBasic as complete as this one and never included as many features, documented orundocumented, examples, and tips in one volume.This book has been designed to give you the coverage you just wont find in any otherbook. Other books often omit not only the larger topics, like deploying your programafter youve created it and creating Help files, but also the smaller ones, like coveringin depth just about every control that comes with Visual Basic, including the ActiveXcontrolsfrom the MS chart control to flat scroll bars, from the serial port commcontrol to the Internet transfer control.Reluctantly, I must admit that its impossible for one volume to be utterlycomprehensive on the subject of Visual Basic (impossible because its not physicallypossible to bind a book that big yet), but were trying our best. Its true that somespecialty books might have more coverage on a few topics, but if you want to seemore on a particular topic, write in and well work seriously on adding more of thattopic to the next edition.How This Book WorksThe task-based format we use in this book is the one most programmers appreciatebecause programming is a task-based business. Rather than reading about subjects inthe order the author thinks best, you can go directly to your topic of interest and findthe bite-sized nugget of information you need, such as opening an FTP connection,adding a Web browser to your program, supporting online user registration fromVisual Basic, adding a method to an ActiveX control, creating an error handler,flipping or stretching an image, opening an RDO database connection, playing CDsfrom the computers CD-ROM drive, and literally hundreds of other topics.And best of all, theres a working example in code for almost every programmingtopic in the book. The actual process of programming is not abstract; its very applied. (1 of 6) [3/14/2001 1:24:11 AM]
  37. 37. Visual Basic 6 Black Book:IntroductionSo instead of vague generalities, we get down to the specificsall the specificsthatgive you everything you need to understand and use Visual Basic.In the old days, programming books used to be very top-down, with chapters onsubjects like conditional branching, loop structures, variable declarations, and soforth. But who sits down to program by saying, Im about to create a conditionalprogram flow branch? Instead, programmers are more interested in performing usefultasks, like adding buttons, menus, list boxes, or toolbars to a window; creatinggraphics animation; creating dialog boxes; creating setup programs; working withfiles; supporting online Help; and so on. And this book is written for programmers.Because this book is written for programmers, each chapter is broken up into dozensof practical programming tasks. After selecting the chapter you want, you can turn tothe table of contents, or to the first page in that chapter, to find the task youreinterested in. Hundreds of tasks are covered in this book, chosen as those thatprogrammers most want to see. In addition, this book is filled with nearly 800examples, covering just about every Visual Basic programming area there is. Theseexamples are bite-sized and to the point, so you dont have to wade through a dozenfiles trying to understand one simple topic. And theyre as comprehensive as we couldmake them, covering every programming area in the book.Besides programming tasks and examples, the book also has overviews designed tobring all the pieces together into a coherent whole, giving you the entire picture. Thefirst chapter is designed specifically to give you an overview of Visual Basic itself,along with some of the best programming practices to use, including thoserecommended by Microsoft. Every subsequent chapter starts with an overview of thesubject it covers before digging into the specifics, making sure we never get lost indetails. Well also see discussions on best programming practices, program design,program testing, what makes a professional Windows application professional, andmuch more, as befits a book that wants to be your complete Visual Basic supportpackage. In addition, the CD that accompanies this book holds the code for all themajor projects we develop. To open and use a project, look for the Visual Basicproject file (for example, browser.vbp for the browser project) and open that projectfile with Visual Basic.Besides the code from the book, note that the CD has hundreds of megabytes of toolsand software, ready for you to use.Whats In This BookJust about everything we could write about Visual Basic is in this book, and thats alot of ground to cover. From language reference to ADO database handling, fromcreating Web browsers to dragging and dropping data across applications, from emailapplications to multimedia players, from creating ActiveX controls and ActiveXdocuments to setup programs, its all here.Heres some of what well see how to create in this book:" ActiveX controls (2 of 6) [3/14/2001 1:24:11 AM]
  38. 38. Visual Basic 6 Black Book:Introduction" ActiveX documents" ADO, DAO, and RDO database applications" Multimedia AVI, MPG, WAV, and MID players" CD players that play CDs from the computers CD-ROM drive" Bitmapped menu items" Full Web browsers" Pie charts, line charts, bar charts, and others" Code clients that call methods in programs like Microsoft Excel" Code components (OLE automation servers)" Graphics animation" Applications that use the Windows Common Dialogs" Customized toolbars with embedded controls like combo boxes" Data entry forms" Database editing applications" Direct connections to the Windows API" Direct connections to code written in Visual C++" Drag/drop operations" Graphics applications that draw arcs, circles, rectangles, lines, and more" Email applications" Error handlers" Applications that use the printer" Word processor applications" File handlers for text and binary data" FTP applications" Dialog boxes" Windows Help files" MDI applications" Pop-up menus activated with right mouse clicks (3 of 6) [3/14/2001 1:24:11 AM]
  39. 39. Visual Basic 6 Black Book:Introduction" Application deployment" HTTP applications" Image handling: blur, emboss, engrave, flip, sweep, stretch images, and more" OLE applications" Applications that use the Windows Registry" List views and tree views" Applications that create controls at runtime" Mouse capture" OLE drags (dragging data between applications)" Online user registration" Picture clip applications" Setup programs" Screen capture" Spreadsheets" Status bars and toolbars" Tab strips, progress bars, and othersThats just some of whats coming up. Visual Basic is a very large topic, and thetopics well cover number in the hundreds. And if you have suggestions for more,please send them in.What Youll NeedTo use this book profitably, you should have some experience with Visual Basicnotnecessarily a lot, but enough to get through Chapter 1 without trouble. We assume youhave some familiarity with the essentials of Visual Basic in this book, although thoseessentials are not very hard to pick up. If you do have trouble with Chapter 1, youmight take a look at an introductory book before proceeding.As far as software goes, just about all you need to use this book is already inMicrosoft Visual Basic (well use version 6 in this book). Visual Basic comes with anenormous set of tools and resources, and well have our hands full putting them towork.We try to be as self-contained in this book as possibleeven creating the database fileswell use in examples with Visual Basic itself, not with a database application. Thegraphics files we use in various examples are on the CD, and the multimedia files well play in our multimedia examples come with Windows. Some of our OLE and OLE (4 of 6) [3/14/2001 1:24:11 AM]
  40. 40. Visual Basic 6 Black Book:Introductionautomation examples use Microsoft Excel, but Excel is not essential to thoseexamplesany OLE server and OLE automation server program will do. Note that touse email from Visual Basic, you must have the Windows MAPI system installed (asrepresented by the Inbox icon on the Windows desktop).Where can you go for additional Visual Basic support? You can find Visual Basicuser groups all over, and more are appearing every day. You can also find VisualBasic information (and advertising) at the Microsoft Visual Basic home page, free Visual Basic downloads at, and technical documents (white papers)at the content varies in accuracy, there are many Usenet groups dedicated toVisual Basic as well, but be careful what you read theretheres no guarantee itsaccurate. About two dozen of those groups are hosted by Microsoft, including:" microsoft.public.vb.bugs" microsoft.public.vb.addins" microsoft.public.vb.controls" microsoft.public.vb.database" microsoft.public.vb.installation" microsoft.public.vb.ole" microsoft.public.vb.ole.automation" microsoft.public.vb.syntaxOther, non-Microsoft groups include some of these popular Usenet forums:" comp.lang.basic.visual" comp.lang.basic.visual.3rdparty" comp.lang.basic.visual.announce" comp.lang.basic.visual.database" comp.lang.basic.visual.miscAnd that all the introduction we needits time to start digging into Visual Basic. Asweve said, we intend this book to be your complete support package for Visual Basic,so, again, if you see something that should be covered and isnt, let us know. In themeantime, happy reading! (5 of 6) [3/14/2001 1:24:11 AM]
  41. 41. Visual Basic 6 Black Book:Introductionhttp:// (6 of 6) [3/14/2001 1:24:11 AM]
  42. 42. Visual Basic 6 Black Book:Whats On the CD-ROMWhats On The CD-ROMThe companion CD-ROM contains the source code and project files used in the VisualBasic 6 Black Book.Also included are demo copies of the following programs:" CoffeeCup HTML Editor++ 98An HTML editor with built in Java and animatedGIFs." CoffeeCup ImageMapper++A fully functional image mapper." Site SweeperProgram that provides an automatic, comprehensive analysis of yourWeb site." QuickSite" SQL-Station" Setup Factory" AutoPlay Menu Studio" VBAdvantage" Olectra Resizer" Q-Diagnostic SoftwareRequirementsTo run all the projects discussed in the book, you will need to have Visual Basic 6installed.Platform486 or higher processorOperating SystemWindows 95, 95, or NTRAM16MB (1 of 2) [3/14/2001 1:24:20 AM]
  43. 43. Visual Basic 6 Black Book:Whats On the CD-ROMhttp:// (2 of 2) [3/14/2001 1:24:20 AM]
  44. 44. Visual Basic 6 Black Book:About the AuthorAbout The AuthorSteven Holzner wrote the book on Visual Basic&a number of times. He co-authoredwith Peter Norton the bestseller Peter Nortons Visual Basic for Windows and PeterNortons Guide to Visual Basic 4 for Windows 95 . He also wrote Advanced VisualBasic 4.0 Programming, a 650-pager that came out in three editions, and InternetProgramming With Visual Basic 5, as well as several other Visual Basic books. All inall, this former contributing editor for PC Magazine has authored 43 books ranging insubjects from assembly language to Visual C++, but Visual Basic is his favorite topic.Stevens books have sold over a million copies and have been translated into 15languages around the world.Steven was on the faculty of Cornell University for 10 years, where he earned hisPh.D. Hes also been on the faculty at his undergraduate school, MassachusettsInstitute of Technology. Steven loves to travel, and has been to over 30 countries,from Afghanistan to India, from Borneo to Iran, from Sweden to Thailand, with moreto come. He and Nancy live in a small, picturesque town on the New England coastand spend summers in their house in the Austrian Alps.AcknowledgmentsThe book you are holding is the result of many peoples dedication. I would especiallylike to thank Stephanie Wall, Acquisitions Editor, for her hard work; Jeff Kellum, theProject Editor who did such a great job of bringing this project together andshepherding it along, as well as Wendy Littley, the Production Coordinator who keptthings on track; Joanne Slike, the copyeditor who waded through everything and got itinto such good shape; and April Nielsen, who did the interior design. Special thanks toHarry Henderson for the terrific tech edit. Thanks to all: great job!Dedication To my Sweetie, Nancy, the best editor in the world, with more kisses than there are pages in this book (and every one of those kisses is well deserved). [3/14/2001 1:24:21 AM]
  45. 45. Visual Basic 6 Black Book:Visual Basic OverviewChapter 1Visual Basic OverviewWelcome to our big book on Visual Basic. Its no secret that Visual Basic is thefavorite programming environment of many programmers. (In fact, youre reading abook written by one of those programmers right now.) When Visual Basic firstappeared, it created a revolution in Windows programming, and that revolutioncontinues to this day. Never before had Windows programming been so easyjustbuild the program you want, right before your eyes, and then run it. Visual Basicintroduced unheard-of ease to Windows programming and changed programmingfrom a chore to something very fun.In time, Visual Basic has gotten more complex, as well as more powerful. In thisbook, were going to see how to use Visual Basic in a task-oriented way, which isthe best way to write about programming. Instead of superimposing some abstractstructure on the material in this book, well organize it the way programmers want ittask by task.This book assumes you have some familiarity with Visual Basic; when you use thisbook, youll usually have some task in mindsetting a programs startup form, forexample, or optimizing for a specific processorand this book will provide theanswer. Well try to be as complete as possible ( unlike the frustrating recordings offrequently asked questionswhich never seem to address your particular problemyou can access while on hold for tech support). This book is designed to be the oneyou come back to time and time again. Its not just to learn new techniques, but it isalso to reacquaint yourself with the forgotten details of familiar methods.Well start with an overview of Visual Basic, taking a look at topics common to thematerial in the rest of the text. In this chapter, well create the foundation well relyon later as we take a look at the basics of Visual Basic, including how to createVisual Basic projects and seeing whats in such projects. Well also get an overviewof essential Visual Basic concepts like forms, controls, events, properties, methods,and so on. And well examine the structure of a Visual Basic program, taking a lookat variables, variable scope, and modules. In other words, were going to lay barethe anatomy of a Visual Basic program here.Well also take a look at programming practices common to all Visual Basicprograms. This overview chapter is the place to take a look at those practicesbecause they involve the rest of the book.Most Visual Basic programmers do not have formal programming training and haveto learn a lot of this material the hard way. As programming has matured,programmers have learned more and more about what are called best practicesthe (1 of 4) [3/14/2001 1:24:34 AM]
  46. 46. Visual Basic 6 Black Book:Visual Basic Overviewprogramming techniques that make robust, easily debugged programs. Well take alook at those practices in this chapter, because they are becoming more and moreessential for programmers in commercial environments these days, especially thoseprogrammers that work in teams. And well look at those practices from theviewpoint of programmers who program for a living; frequently theres a gapbetween the way best practices are taught by academics and how they are actuallyneeded by programmers facing the prospect of writing a 20,000-line program as partof a team of programmers.Well start our overview chapter by creating and dissecting a Visual Basic project,jumping right into the code.Creating A Project In Visual BasicThere are three different editions of Visual Basic:" The Learning Edition, which is the most basic edition. This edition allows you towrite many different types of programs, but lacks a number of tools that the othereditions have." The Professional Edition, designed for professionals. This edition contains allthat the Learning Edition contains and more, such as the capability to write ActiveXcontrols and documents." The Enterprise Edition, which is the most complete Visual Basic edition. Thisedition is targeted towards professional programmers who may work in a team andincludes additional tools such as Visual SourceSafe,