gbCodeLib Source Code Snippets Gary Beene's Information Centers http://www.garybeene.com 2005-03-06 22:42:23 ----T 01 Common features _Language Summary Language Comparisons 2005-02-17 22:33:34 ----O 0 0 0 ----E ----D ----E ----C Most languages share common features, different in their details, but similar in functionality. A programmer skilled in one language can typically learn a new language by starting on the similar aspects and then branching out into the differences between the two languages. The gbCodeLib tutorials are modelled after the following language comparisons. As the tutorials grow they will contain sections on each of these common areas, as well as sections on capabilities unique to each language: //Languages reflect the following common programming concepts: 1. Syntax (how the language is written) 2. IDE - Integrated Development Environment, is it exists. Sometimes third party IDEs are available 3. Data types / operators / variables 4. Strings 5. Arrays 6. Flow control 7. Functions and Subroutines //Languages also provide functionality in all of these common areas: 8. Files and Folder 9. System functions 10. Graphics 11. Sound 12. Date/time 13. Math 14. Printing 15. Error handling 16. Objects / Classes / Heirarchy //Languages differ in the extent to which they provide access to external capabilities such as: 17. Windows API access 18. Components and libraries, such as DLLs and OCXs ----E ----H ----E ----T 02 Language famillies _Language Summary Language Comparisons 2005-02-17 22:33:38 ----O 0 0 0 ----E ----D ----E ----C Based on similarities in structure and syntax, most languages can be grouped with other, similar languages. //The Visual Basic Family - run uncompiled in IDE, compile for distribution VB VB.net VBA (Excel, Outlook, Access) //OOP Languages - compile before use C++ Java C# //CGI Scripts - no compiliation Perl ASP //Web page and scripting technologies - intrepreted by the browser HTML XML JavaScripot VBScript ----E ----H ----E ----T 03 IDE _Language Summary Language Comparisons 2005-02-17 22:48:50 ----O 0 0 0 ----E ----D ----E ----C Languages differ greatly in the type of IDE (Integrated Development Environment) they use. //Most come with an IDE as part of the language VB, VBA, VB.net, Delphi, Excel, Outlook, Access, C++ //Some have no IDE (from the language manufacturer) HTML, XML, DOS, Perl, ASP, PHP, C#, Java, JavaScript, Java, SQL, PL1 Third party IDE as available for most of the ones which do not comes with and IDE as part of the original language purchase: Common third-party IDEs include the following: //Perl OptiPerl http://www.xarka.com ----E ----H ----E ----T 04 Commenting _Language Summary Language Comparisons 2005-02-17 22:51:23 ----O 0 0 0 ----E ----D ----E ----C Commenting is the placement of text in the source code that is to be ignored by the compiler or interpreter. It is there to explain the code. Most iDE's usually color the comments green to highlight them from executable code. Comments are typically identified by the use of special characters, as follows: //Visual Basic family: Text to the right of an apostrophe (') is highlighted, provided the apostrophe is not enclosed within quotes //HTML, XML Text between is highlighted //ASP Text to the right of an apostrophe (') is highlighted, provided the apostrophe is not enclosed within quotes, and lines which start with "REM" //Perl, PHP Text to the right of "//" Text to the right of a "#" is highlighted //Delphi Text to the fight of "//" or between curly braces "{}" or between "(*" and "*)" //JavaScript, Java, C++, C# Text to the right of "//" on a line, or between "/*" and "*/" on multiple lines are highlighted //DOS, VB, VB.net, VBA Any line that starts with "REM" ----E ----H ----E ----T 05 Case-sensitivity _Language Summary Language Comparisons 2005-02-17 22:49:05 ----O 0 0 0 ----E ----D ----E ----C Some languages are case sensitive and others are not. //Case sensitive Java, JavaScript, C++, C#, Perl, PHP //Not case sensitive VB, VBA, VB.net, Delphi, HTML, XML, ASP, DOS, Excel, Outlook, Access, Cobol, PL1, SQL ----E ----H ----E ----T 06 Keywords _Language Summary Language Comparisons 2005-02-17 22:49:10 ----O 0 0 0 ----E ----D ----E ----C While there are some similarities, keywords are considerably different from language to language ----E ----H ----E ----T 07 Top 100 Snippets (applications) _Language Summary Language Comparisons 2005-02-18 21:35:46 ----O 0 0 0 ----E ----D ----E ----C //For stand alone applications, regardless of the language, these are the Top 100 //capabilities which most applications will feature, and which programmers will need //to know. //As the gbCodeLib database grows, a snippet will be added under each language //for these Top 100 snippets. //In some languages, particularly the CGI and scripting languages, where programming //does not generally result in standalone applications, the Top 100 list will be much //different. //The gbCodeLib database will reflect different Top 100 snippets for such each language //Top 100 snippets have the keyword 'Top100' so you can list them as a search result Applications 1. Associate an extension with an application 2. Create a shortcut to an application (to a specified folder, including Windows special folders) 3. Open a Color dialog 4. Open a File dialog 5. Open a Folder dialog 6. Open a Font dialog 7. Put app icon in the system tray 8. Put app in the Explorer context menu 9. Put app in the SendTo context menu 10. Start a new application and wait for it to finish 11. Start an application when Windows starts up 12. Test whether the application is running within the IDE 13. Maintain MRU file (most recent files updated) 14. Read/write INI files 15. Create context menus 16. Resize controls when form resizes Arrays 17. Cycle througn an array 18. Randomly shuffle an array 19. Remove an element of an array (by content or by position) 20. Search an array Clipboard 21. Copy or retrieve text and images from the clipboard Controls 22. Automatically highlight textbox content on focus 23. Capture any key (Enter, TAB, arrow keys, home/end, F-keys, ...) 24. Forces lower/upper case on text input 25. Richtextbox manipulation (word wrap, find and replace, TAB control, flicker control, merge two controls, ...) 26. Toolbar manipulation (customize, dropdowns, images, sync with menus, ...) 27. Statusbar manipulation Date-Time 28. Compute elapsed time between 2 dates 29. Compute elapsed time between 2 events (ms accuracy) 30. Display time in multiple formats Files 31. Create valid full pathname from folder and file names 32. Extract file name from a full path 33. Determine if a file exists 34. Get file properties (size/date/attributes) 35. Delete a file to the recycle bin 36. Backup/restore a file File - Text 37. Read file one line at a time or all at once 38. View content File - Binary 39. Read/write data at a specific location 40. Read entire file at once 41. View contents in hex or binary-stripped format Folders/Drives 42. Determine if a file exists 43. Delete a folder and its subfolders 44. Get list of dirve letters 45. Get type of drive 46. Open DOS windows at a specific folder 47. Open a Window at a specific folder 48. Open Windows Explorer at a specific folder 49. Create a fll path of folders Forms 50. Center a form 51. Keep form on top 52. Set min/max size of form 53. Add a splitter (vertical/horizontal) 54. Unload all forms Graphics 55. Convert between Long, RGB, VB, and web colors 56. Get image size without reading entire file (JPG/GIF/BMP) 57. Get screen resolution 58. Generate a gradient fill 59. Overlay an image with transparency control 60. Read/write/display/convert images (JPG/GIF/BMP) 61. Resize and image, keeping aspect ratio 62. Capture the screen or any part of the screen 63. Set wallpaper - center/stretch/tile Internet 64. Check for Internet connection 65. Create URL shortcut 66. Create web page (HTML) from code 67. Download text/binary file, with progress indicator 68. Upload text/binary file, with progress indicator 69. Get remote file information (size/date0 70. Open a web page in a browser 71. Send email using default email application 72. Update file via FTP Math 73. Create random integer within specified range 74. Round number to specified number of decimals Multimedia 75, Play CD 76. Play sound or video file (.wav, .mp3, ..mid, avi, .mpg) 77. Record sound or video Navigation 78. List all files and folders beneath a specified full path Printing 79. Print images (positioned, scaled, or tiled) 80. Print preview 81. Color text printing 82. Send page eject to the printer 83. Print justified text (left/right) Registry 84. Clear application setting from registry 85. Write/edit application settings 86. Write/edit/delete anywhere in the registry Security 87. Calculate checksum 88. Encrypt/decrypt a file/string (with or without a password) 89. Disable Ctrl-Alt-Del Sort 90. Bubble sort 91. QuickSort Strings 92. Convert strings to upper/lower case 93. Find/replace a string within a string 94. Split string into an array based on delimeters 95. Find text between two strings System 96. Get computer name 97. Get user name 98. Get name of special folders (Windows, System, SendTo, Startup, 99. Get Windows version 100. Reboot / restart / logoff system ----E ----H ----E ----T 08 Top 25 Snippets (HTML) _Language Summary Language Comparisons 2005-02-26 19:31:11 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T - Tutorial 01 - Overview ASP _tutorials 2005-02-23 18:07:46 ----O 0 0 0 ----E ----D ----E ----C ASP - Active Server Pages An Active Server Page is an HTML file with some additional code (ASP) in it, separated from the HTML markup by a different delimiter: <% %> <% ASP Code evaluated here %> As with HTML, you can use any text editor to create ASP code. ASP files use the extension .asp. The HTML page is fed to an HTTP server, which in turn pages the ASP code to the IIS server (a microsoft application) for execution. The ASP code is executed on the server and the results displayed within the page on the browser. The ASP code can be written using one of many scripting languages - as long as the server can execute it. VBScript is the default and is well supported by the Microsoft IIS server. IIS stands for Internet Information Services and is free from Microsoft. PSW stands for Personal Web Server. It is a smaller, but fully fully functional -version of IIS. It is free from Microsoft. Both IIS and PWS can be run on your PC to help try out ASP pages locally. PWS require Win95+, whereas IIS requires NT4 or higher. When a browser requests an HTML file, the server returns the file When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML. ----E ----H ----E ----T - Tutorial 02 - Sample Code ASP _tutorials 2005-02-23 07:47:51 ----O 0 0 0 ----E ----D ----E ----C <%@ Language=VBScript %> Example 1

<% Response.Write("Hello, world!") %> If you save this file as .asp and put it on an ASP-ready server, you'll see the "Hello, world!" in the page above. The important thing to note is that the server will assume that anything between the delimiters is code and will then try to execute it. Don't put HTML there, or else it'll break. The first line, <%@ Language=VBScript %> is optional. If you leave it out, the server will assume you're using VBScript ----E ----H ----E ----T - Tutorial 03 - Syntax ASP _tutorials 2005-02-23 18:07:46 ----O 0 0 0 ----E ----D ----E ----C The Write method of the ASP Response Object is used to send content to the browser. For example, the following statement sends the text "Hello World" to the browser: <% response.write("Hello World!") %> The ASP code can be any script of your chosing - VBScript, JavaScript. But you must specify the language at the top of the page. <%@ language="javascript"%> ... <% Response.Write("Hello World!") %> Note that JavaScript is case sensitive. You must write your ASP code to match the requirements of the script language you use. ASP is shipped with VBScript and JScript (Microsoft's implementation of JavaScript). You can use other CGI scripts to, such as Perl or Python, but the server has to support them. Because the server hands off the ASP (script) code, the browser does not need to support scripting al all. ----E ----H ----E ----T - Tutorial 04 - Using IIS / PWB ASP _tutorials 2005-02-23 07:47:49 ----O 0 0 0 ----E ----D ----E ----C PSW on Windows 98: - Install PWS - Run the web server - From within your browser type in "http://localhost/myweb/test.asp" to view the test.asp page IIS on Windows XP Professional - IIS will not run on Windows XP Home Edition - Install IIS - Run the web server - From within your browser type in "http://localhost/myweb/test.asp" to view the test.asp page ----E ----H ----E ----T Detect browser ASP navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C <%@ Language=VBScript %> <% dim BrowserType set bc = Server.CreateObject("MSWC.BrowserType") if bc.browser="IE" then BrowserType = "MSIE" elseif bc.browser="Netscape" then BrowserType = "Netscape" elseif bc.browser="Lynx" then BrowserType = "Lynx" end if %> <% select case BrowserType case "Lynx" Response.Write("You're using Lynx! How do you manage to live without 3-D backgrounds and endless download times? Whatever!") case "MSIE" Response.Write("You're using Internet Explorer! Thank you for helping keep Microsoft afloat!") case "Netscape" Response.Write("You're using Netscape! And you're wearing those great pink pants! ASP knows everything about you!") case else Response.Write("You're using some other browser I don't know about.") End select %>
----E ----H ----E ----T - Tutorial 01 - Overview C++ _tutorials 2005-02-17 22:16:28 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T Snippet 13 Cobol _tutorials 2005-02-17 22:16:32 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T - Tutorial 01 - Overview CSharp _tutorials 2005-02-17 22:16:36 ----O 0 0 0 ----E ----D ----E ----C C# competes with C++ and VB as a language to write Windows applications. C# uses the .NET software development kit Every C# program contains a Main method where program execution begins and ends. ----E ----H ----E ----T - Tutorial 02 - Basic Code (Hello World) CSharp _tutorials 2005-02-17 22:16:36 ----O 0 0 0 ----E ----D ----E ----C class HelloWorld { static void Main() { System.Console.WriteLine("Hello World!"); } } Save this file as HelloWord.cs Compile in a DOS window by typing in: csc HelloWorld.cs This creates an EXE files called HelloWorld.exe ----E ----H ----E ----T - Tutorial 03 - Syntax CSharp _tutorials 2005-02-17 22:16:36 ----O 0 0 0 ----E ----D ----E ----C C# is case sensitive C# statements end with the semicolon ; memory = 2 + 5; Each line consists of only 1 statement C# programs consist of sequences of C# statements that execute in ascending order like the following example: { statement 1 statement 2 statement 3 } Comments: // This text will be treated as a comment /* As are these text lines treated as comments */ ----E ----H ----E ----T - Tutorial 01 - Overview Delphi _tutorials 2005-02-17 22:16:41 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T - Tutorial 01 - Overview DOS _tutorials 2005-02-17 22:16:45 ----O 0 0 0 ----E ----D ----E ----C Microsoft DOS (Disk Operating System) is a command line user interface. MS-DOS 1.0 was released in 1981 for IBM computers and the latest version of MS-DOS is MS-DOS 6.22, released in 1994. A command line interface (MS-DOS or an emulation of it) continues to be available in each new version of Microsoft. To get a DOS window , click Start / Run and type "command" (Win9.x and Windows ME) or by typing "cmd" in Windows NT, Windows 2000 or Windows XP. To see a list of all commands, type 'Help' in a DOS window. To capture the information in a file, type Help > doscommands.txt The > symbols directs the output of the DOS command to the fle. ----E ----H ----E ----T - Tutorial 02 - Internal Commands DOS _tutorials 2005-02-17 22:16:45 ----O 0 0 0 ----E ----D ----E ----C ASSOC Displays or modifies file extension associations. AT Schedules commands and programs to run on a computer. ATTRIB Displays or changes file attributes. BREAK Sets or clears extended CTRL+C checking. CACLS Displays or modifies access control lists (ACLs) of files. CALL Calls one batch program from another. CD Displays the name of or changes the current directory. CHCP Displays or sets the active code page number. CHDIR Displays the name of or changes the current directory. CHKDSK Checks a disk and displays a status report. CHKNTFS Displays or modifies the checking of disk at boot time. CLS Clears the screen. CMD Starts a new instance of the Windows command interpreter. COLOR Sets the default console foreground and background colors. COMP Compares the contents of two files or sets of files. COMPACT Displays or alters the compression of files on NTFS partitions. CONVERT Converts FAT volumes to NTFS. COPY Copies one or more files to another location. DATE Displays or sets the date. DEL Deletes one or more files. DIR Displays a list of files and subdirectories in a directory. DISKCOMP Compares the contents of two floppy disks. DISKCOPY Copies the contents of one floppy disk to another. DOSKEY Edits command lines, recalls Windows commands, and creates macros. ECHO Displays messages, or turns command echoing on or off. ENDLOCAL Ends localization of environment changes in a batch file. ERASE Deletes one or more files. EXIT Quits the CMD.EXE program (command interpreter). FC Compares two files or sets of files, and displays the differences between them. FIND Searches for a text string in a file or files. FINDSTR Searches for strings in files. FOR Runs a specified command for each file in a set of files. FORMAT Formats a disk for use with Windows. FTYPE Displays or modifies file types used in file extension associations. GOTO Directs the Windows command interpreter to a labeled line in a batch program. GRAFTABL Enables Windows to display an extended character set in graphics mode. HELP Provides Help information for Windows commands. IF Performs conditional processing in batch programs. LABEL Creates, changes, or deletes the volume label of a disk. MD Creates a directory. MKDIR Creates a directory. MODE Configures a system device. MORE Displays output one screen at a time. MOVE Moves one or more files from one directory to another directory. PATH Displays or sets a search path for executable files. PAUSE Suspends processing of a batch file and displays a message. POPD Restores the previous value of the current directory saved by PUSHD. PRINT Prints a text file. PROMPT Changes the Windows command prompt. PUSHD Saves the current directory then changes it. RD Removes a directory. RECOVER Recovers readable information from a bad or defective disk. REM Records comments (remarks) in batch files or CONFIG.SYS. REN Renames a file or files. RENAME Renames a file or files. REPLACE Replaces files. RMDIR Removes a directory. SET Displays, sets, or removes Windows environment variables. SETLOCAL Begins localization of environment changes in a batch file. SHIFT Shifts the position of replaceable parameters in batch files. SORT Sorts input. START Starts a separate window to run a specified program or command. SUBST Associates a path with a drive letter. TIME Displays or sets the system time. TITLE Sets the window title for a CMD.EXE session. TREE Graphically displays the directory structure of a drive or path. TYPE Displays the contents of a text file. VER Displays the Windows version. VERIFY Tells Windows whether to verify that your files are written correctly to a disk. VOL Displays a disk volume label and serial number. XCOPY Copies files and directory trees. ----E ----H ----E ----T - Tutorial 03 - External Commands DOS _tutorials 2005-02-17 22:16:45 ----O 0 0 0 ----E ----D ----E ----C bootcfg (XP only) This utility allows you to set up your boot options, such as your default OS and other loading options. cacls (XP, 2000, & NT4.0) Changes the ACLs (security Settings) of files and folders. Very similar to chmod in Linux. comp (XP & 2000) This utility is very similar to diff in Linux. Use the /? switch to get examples of command usage. Contig (NT4.0 and newer) A great defrag utility for NTFS partitions. defrag (XP only - NT4.0 and Win2k use contig) Yes, XP comes with a command line disk defrag utility. If you are running Win2k or NT4.0 there is still hope. Contig is a free defrag program that I describe on the defrag page. diskpart (XP only) Use this command to manage your disk partitions. This is the text version for the GUI Disk Manager. driverquery (XP only) Produces a list of drivers, their properties, and their versions. Great for computer documentation. fsutil (XP only) This is a utility with a lot of capability. Come back soon for great examples. getmac (XP & 2000) This command gets the Media Access Control (MAC) address of your network cards. gpresult (XP & 2000) This generates a summary of the user settings and computer group policy settings. ipconfig (XP, 2000 & NT4.0) This handy tool displays IP settings of the current computer and much more. netsh (XP & 2000) A network configuration tool console. At the 'netsh>' prompt, use the '?' to list the available commands and type "exit" to get back to a command prompt. openfiles (XP Only) Allows an administrator to display or disconnect open files in XP professional. Type "openfiles /?" for a list of possible parameters. Pathping (XP & 2000) A cross between the ping and traceroute utilities. Who needs Neotrace when you can use this? Type "pathping " and watch it go. recover (XP & 2000) This command can recover readable information from a damaged disk and is very easy to use. reg (XP & 2000) A console registry tool, great for scripting Registry edits. schtasks (XP only) A newer version of the AT command. This allows an administrator to schedule and manage scheduled tasks on a local and remote machines. secedit (XP & 2000) Use this utility to manually apply computer and user policy from your windows 2000 (or newer) domain. Example to update the machine policy: secedit /refreshpolicy machine_policy /enforce To view help on this, just type secedit. sfc (XP & 2000) The system file checker scans important system files and replaces the ones you (or your applications) hacked beyond repair with the real, official Microsoft versions. shutdown (XP & 2000) With this tool, You can shut down or restart your own computer, or an administrator can shut down or restart a remote computer. systeminfo (XP only) Basic system configuration information, such as the system type, the processor type, time zone, virtual memory settings, system uptime, and much more. This program is great for creating an inventory of computers on your network. tasklist (XP only) Tasklist is the command console equivalent to the task manager in windows. taskkill (XP only) Taskkill contains the rest of the task manager functionality. It allows you to kill those unneeded or locked up applications. ----E ----H ----E ----T - Tutorial 04 - Batch Files DOS _tutorials 2005-02-17 22:16:45 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T - Tutorial 05 - Utilities DOS _tutorials 2005-02-17 22:16:45 ----O 0 0 0 ----E ----D ----E ----C bat2exe converts batch files to EXE files ----E ----H ----E ----T - Tutorial 06 - XP Changes to DOS DOS _tutorials 2005-02-17 22:16:45 ----O 0 0 0 ----E ----D ----E ----C MS-DOS commands were changed in XP - some changes, some deletions. Functionality of these commands were changed. Changes code pages for all Command Prompt windows. Command-line options /1 and /8 are not supported. diskperf No longer needed to act upon a server computer. You can still use diskperf for remote administration. Command-line option /1 is not supported. Available for all character-based programs that accept buffered input. Doskey has been improved by a series of enhancements. Supports 1.44 MB floppy drive only. 20.8 MB floptical (magneto-optical) drive is no longer supported. Command-line options /b, /s, /u, /1, /4, and /8 are no longer supported. The caret (^) and ampersand (&) symbols can be used in a volume label. The mode lptn[:][cols=c][lines=n] and mode lptn[:][c][,[n]] syntaxes are not supported. Command-line options /b, /c, /m, /p, /q, /s, /t, and /u are not supported. New character combinations enable you to add ampersands ($a), parentheses ($c and $f), and spaces ($s) to your prompt. Recovers files only. New /s command-line option deletes directories that contain files and subdirectories. Does not require TEMP environment variable. File size is unlimited. New /g command-line option creates decrypted destination files. Unavailable MS-DOS Commands assign Not currently supported. backup Not currently supported. choice Not currently supported. ctty Not currently supported. dblspace Not currently supported. deltree The rmdir /s command deletes directories containing files and subdirectories. For more information about the rmdir command, see Rmdir dosshell Function is now inherent. drvspace Not currently supported. emm386 Function is now inherent. fasthelp Not currently supported. Use the help command at the command prompt. For more information about the help command, see Help For a complete list of command-line tools, see Command-line reference A-Z fdisk Not currently supported. Use the diskpart command, which enables you to manage disks, partitions, or volumes. For more information about the diskpart command, see Diskpart include Multiple configurations of the MS-DOS subsystem are not supported. interlnk Not currently supported. intersrv Not currently supported. join Increased partition size and an improved file system eliminate the need to join drives. memmaker MS-DOS subsystem memory usage is automatically optimized. menucolor Multiple configurations of the MS-DOS subsystem are not supported. menudefault Multiple configurations of the MS-DOS subsystem are not supported. menuitem Multiple configurations of the MS-DOS subsystem are not supported. mirror Not currently supported. msav Not currently supported. msbackup Use the ntbackup command for computers with tape drives, or the xcopy command for computers without tape drives. For more information about the ntbackup command, see Ntbackup For more information about the xcopy command, see Xcopy mscdex It is unnecessary to configure the MS-DOS subsystem to use CD-ROM drives. Windows XP provides access to CD-ROM drives for the MS-DOS subsystem. msd Use the System Information snap-in. To start System Information, click Start, click Run, and then type msinfo32. numlock Not currently supported. power Not currently supported. restore Not currently supported. scandisk Not currently supported. Use the chkdsk command, which enables you to create and display a status report for a disk based on the file system. Chkdsk also lists and corrects errors on the disk. For more information about the chkdsk command, see Chkdsk smartdrv Caching for the MS-DOS subsystem is automatic. submenu Multiple configurations of the MS-DOS subsystem are not supported. sys Windows XP does not fit on a standard 1.2 MB or 1.44 MB floppy disk. undelete Not currently supported. unformat Not currently supported. vsafe Not currently supported. ----E ----H ----E ----T Delete all files in a directory without requiring confirmation DOS files-folders 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C echo y | del *.* ----E ----H ----E ----T Delete backup files DOS files-folders 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C del *.bak ----E ----H ----E ----T List all *.bat files in a folder DOS files-folders 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C @echo off for %%F in (c:\bat\*.bat) do call listall2 %%F ----E ----H ----E ----T List directories DOS files-folders 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C dir /ad ----E ----H ----E ----T List directory of drive a: (on screen) DOS files-folders 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C dir a:\ ----E ----H ----E ----T Go to root directory DOS navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C cd \ ----E ----H ----E ----T Go up one directory DOS navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C cd .. ----E ----H ----E ----T Make sub-directory and change to that directory DOS navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C md %1 cd %1 ----E ----H ----E ----T Open current directory in Window DOS navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C start .\ ----E ----H ----E ----T Print current directory DOS navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C dir > prn ----E ----H ----E ----T - Tutorial 01 - Overview Excel _tutorials 2005-02-17 22:16:50 ----O 0 0 0 ----E ----D ----E ----C Excel is an application, not a language, but it contains the Microsoft Visual Basic for Applications langauge. Please use the online code update (using the File > Import menu option) to check for new code releases. ----E ----H ----E ----T 01 Overview HTML _tutorials 2005-02-25 11:19:44 ----O 0 0 0 ----E ----D ----E ----C ..HTML files are text files. HTML files contain information to be displayed, along with special instructions on how to display the information. An HTML file is read by a browser such as Microsoft Explorer which displays the content according to the instructions it finds. The instructions are called "tags", which usually come in pairs. An example of a tag pair is: Hello The is the starting tag and the is the ending tag. This particular pair of tags tells the browser to display the word 'Hello' in bold. Each of the tab pairs start and end with the < and > symbols. Another example is to display an image: This tag is an exception to the rule - it has no end tag. In this example it displays the image mypicture.jpg aligned to the left side of the page. This tag also shows the concept of an attribute to which you can assign a value. In this case, the attribute is 'src' and the value assigned to it is "mypicture.jpg". Usually, an HTML file is saved with an extension of .html or .htm. Doing so in Windows enables you to double-click on the file name and have it opened in the web brower. Many people edit the files with the simplest of all text editors - Notepad - which is supplied with Windows. Specialty applications exists which provide HTML-specific features, including the ability to FTP completed files to the server. ----E ----H ----E ----T 02 Basic HTML code HTML _tutorials 2005-02-24 08:56:41 ----O 0 0 0 ----E ----D ----E ----C HTML files typically consist of several basic sections, described by the following tags: HTML files may contain comments, which are bordered at the start and end as follows: HTML is not case sensitive. HTML ignores white space. ----E ----H ----E ----T 03 IDE HTML _tutorials 2005-02-24 08:53:10 ----O 0 0 0 ----E ----D ----E ----C ..HTML is not a product that you can purchase. It is a specification on how to write web pages. This means that there is no Integrated Development Environement (IDE), such as VB, C++, Delphi, and other languages. However, since HTML pages are simple text, any text editor on the market can be used to create web pages. I have personally used NotePad extensively on my web pages. It comes free with Windows and allows your write compact HTML code. I also have used NoteTAB, which is also a text editor but which costs only $10. It provides highlighting of HTML keywords and comments, making it much easier to review your code. It also includes a spell checker and can open many files at one time. I've found these features to speed up my web page creation and maintenance. Other text editors which provide special features for HTML editing include Macromedia Homesite, Coffeecup HTML Editor, Hippie and UltraEdit. There are also some high-end HTML editors which provide many more features, notably WYSIWYG - real time viewing of the results of your editing . With simple text editors you have to load your page into a browser to see the results of your editing. With WYSIWYG editors you need no other tool to check the results. Also, the high-end editors provide such features as web page templates, mass changes to an entire web site of pages to maintain a certain look-and-feel, automatic transfer of files to the server (synchronization), plus embeddment and trial of CGI scripts. Most large commercial sites use these kinds of editors. Examples of high-end editors include Macromedia Dreamweaver, Microsoft FrontPage, Adobe GoLive, NetObjects Fusion and Hotmetal Pro. Some excellent text and WYSIWYG editors, such as Arachnophilia, NoteTab Light and 1st page 2000 are free. ----E ----H ----E ----T 04 Syntax HTML _tutorials 2005-02-24 20:30:57 ----O 0 0 0 ----E ----D ----E ----C ..Basically, HTML code is displayed start to end in the browser viewing window, wrapping to fit the horizontal width of the viewing window. Line breaks are ignored. Contiguous spaces are ignored (actually, treated as a single space). To create line breaks the
tag is used. To create paragraph divisions the

tag is used. HTML will display in the same case that it was typed. In the case where attribute values of tag are entered, HTML is case-insensitive, with some specific exceptions: - text within quotes may be used by the browser in the case it is typed - case sensitivity of embedded scripts are handled by the script compiler/interpreter - file names and URLs are almost always case-sensitive HTML can also be broken into sections with the

tags. The
tag supports align and nowrap attributes which allow you to apply formatting to entire sections of a document:
... content
or
... content
HTML tags may recognize several attributes. The order attributes are placed in a tag is not important. Spacing between an attribute, the = sign, and the value is not important. width=5 and width = 5 are both the same. If an attribute is a single word or number (no spaces) you can add it after the equal sign with no quotations. All other values should be enclosed in quotes. HTML accepts either single or double quotes. Values cannot be more than 1024 characters. ----E ----H ----E ----T 05 Text Formatting HTML _tutorials 2005-02-24 20:35:14 ----O 0 0 0 ----E ----D ----E ----C ..Because, in the following example, there are NO HTML tags telling the browser how to display the content, the following HTML would be read by a browser as one long line, in the browsers default font: hello hello hello HTML supports several tag pairs which you can use to tell the browser how to display text. Simply place the text between one of the tag pairs to have it displayed per the tag pair meaning:

Large, bold header (actually there are 6 header tags, h1 thru h6) Bold Italic Underline

Paragraph - browser places a blank line before a paragraph
	
Display the text exactly as written, including recognition of spaces, in mono-spaced font Monspaced, sans serfic to resemble computer code Subscript Superscript These tags can be embedded within one another, such as this bold-italic combination: This will display as bold-italic ----E ----H ----E ----T 06 Fonts HTML _tutorials 2005-02-25 11:08:23 ----O 0 0 0 ----E ----D ----E ----C ..The tag lets you change the size and color of text. There are three ways to set the size attribute: - Virtual. use a value of 1 to 7 size = 1 - Absolute. set the value to any font size size = 22 - Relative. with respect to current font size size= +1 size= -2 Use the color attribute as you would any other color attribute color = &FF000 use hexadecimal color string or color = red where named colors are used ----E ----H ----E ----T 07 Images HTML _tutorials 2005-02-24 20:32:17 ----O 0 0 0 ----E ----D ----E ----C ..Browsers can display images. The tag is used for this and can also be used to determine where the image is displayed and how surrounding text will flow around the image. Here's an example of an image tag: Once a browser sees the img tag it will download the image file and display it at normal size - in the browser at the point in the text where the img tag is placed. Text elsewhere in the HTML page will flow around the image. There is no implied line or paragraph break - the image is considered 'inline'. Here's another example of an image tag, showing some of the common attributes that are used: By telling the browser the size of the image, using width/height, the browsere can allocate a space for the image and continue loading the rest of the document, then filling in the image when it arrives from its source. The border attribute provides a simple black border as many pixels thick as the HTML code defines. The browser default is to have no border. An image can be aligned to the left or right of a page using the align attribute. Or, the image can be aligned with respect to the line of text it is on, using the top/bottom/middle align attribute values. There are many more attribute for the tag. These are just some of the more commonly used ones. Image Formats All browsers support JPG or GIF image formats. Some browsers support additional formats. GIFs support transparency, interlacing, and animation. JPGs are better suited for pictures and tend to be smaller because they have a higher compression ratio than GIFs. On the downside, JPGs suffer from loss of image quality when compressed too much. ----E ----H ----E ----T 08 Links HTML _tutorials 2005-02-24 20:32:24 ----O 0 0 0 ----E ----D ----E ----C ..Click on a link and it will take you to the location specified in the anchor tag. In the following example, clicking on the text 'My Web Site' will direct the browser to go to the URL 'http://www.garybeene.com': My Web Site The anchor tag can also be used to move to a new position on the current page like this: First, put this line of HTML code in the document as a point to which you want to be able to jump: Then, this line of HTML code will create a link to jump to that location: Jump The #-sign notation can also be used in the first example, like this: My Web Site This allow you to jump to the middle of a web page instead of only being able to go to the top of a web page as a normal link would allow. An image can also be made to act as a link by placing the tag inside the anchor tag, as in this example: ----E ----H ----E ----T 09 Lists HTML _tutorials 2005-02-24 20:32:28 ----O 0 0 0 ----E ----D ----E ----C ..The three common HTML list tags provides useful ways to present common lists of data - providing indentation, bullets, or numbering to enhance the readability of the lists. 1. Unordered list - provides simple graphical bullets for members of the list
  • First item
  • Next item
2. Ordered list - provides numerical bullets for members of the list
  1. First item
  2. Next item
3. Definition list - indented list without bullets of any kind
First term
Definition
Next term
Definition
----E ----H ----E ----T 10 Forms HTML _tutorials 2005-02-25 11:07:59 ----O 0 0 0 ----E ----D ----E ----C ..Aside from the simple formatted display of content (fonts, colors, lists, tables), the most important use of web pages is to provide the ability of a user to input information for submittal to the web server. A web page page can have one or more forms on a page, each acting independently of each other. Forms provide several elements for data entry, such a textboxs or dropdown selection lists. Once the data is entered into a form, the user can simply press the Submit button on the form to send the entered data to the server for processing. HTML itself provides no server-side capability for processing the data. See the CGI mini-tutorial for a description of how servers use CGI scripts to process form data. Here's the HTML code for a form with one of each possible form elements:
To email a form, use this version of the form tag:
The Method attribute of the tag has 3 values - Post, Get, or Head. The value selected must match the requirements of the CGI script on the server. Input Elements There are 8 basic attributes that form input elements support. - name Gives a name for the input element. It is used by the CGI script on the server to keep the incoming data separate. All input elements use this attribute. - type Determines which of the input elements are displayed (see the full list below). - value Determines the initial content of a textbox, hidden, or password input elements. Also defines the label for the submit and reset buttons. - checked Determines whether the starting state of a checkbox or radio button is checked. - size Determines the display length of an input element (text or password) - maxlength Determines the maximum length of a string that can be captured and sent to the server. - src Used only with the image element, this identifies the source URL of the image that is to be displayed. - rows, cols Used only with the textarea element. Determines the display size of the area where text can be entered. Now, here are the input elements which can be inserted in a form on a web page: -Text - Checkbox - Radio Button Allowed attributes: name, type, value. Only one radio button can be selected at time. When you click on one, all the others become unselected. Each radio button must use the same name attribute. You can have one or more groups of radio buttons. Simply give each member of the second group a new name. This will create a second group of radio buttons which acts independently of the first group. - Password Only "*" characters are displayed but it is NOT encrypted. - Hidden Remember, the hidden element is not displayed but its value is sent to the web server. - Image When a user clicks on the image you get the same effect as though the Submit button was pressed. The location on the image where the mouse was clicked will be sent as part of the form's information. - Button Pressing a standard button will not cause anything to happen unless you use one of the scripting languages to respond to the Click event. See my - Reset Sets all the input elements will be set to their "value" attribute value. - Submit Sends all information in the form per the action attribute setting Note: On a form with only 1 text input element (nothing else, including no buttons), pressing enter while the cursor is in the text box will cause the form to act just as though Submit button were pressed Select Element Dropdown list for selection by user. Multiple attribute allows more than one item to be selected. Textarea Element Similar to a textbox, ----E ----H ----E ----T 11 Tables HTML _tutorials 2005-02-24 20:37:45 ----O 0 0 0 ----E ----D ----E ----C Tables rival images as the most-used feature of HTML pages. Getting information, both text and images, aligned for easier viewing is done on virtually every web site and is made possible by the HTML tags that specifically support table generation. Even though creating tables is a bit tedious (less so if you're using one of the many WYSIWYG HTML Editor applications), it is well worth the effort to create a clean-looking, orderly web page. Of the ten HTML tags that support the creation of tables within an HTML page (web page), only a few are commonly used: * table - start of a table * tr - start of a row * th - start of a header for a column * td - start of a cell (column) in a row * caption - text to put at top or bottom of a table (outside the border) The tag pair starts and ends a table. Then the table is built row by row (the tags), with as many columns (the tags) as desired. Here's the code again with some sample data, and the tables it would be displayed. Here is the basic code for a table of two rows and two columns:
And the same table with sample content:
Sample Caption
upperleft upperright
lowerleft lowerright
As with most other HTML tags, these tags support several attributes which are useful in adjusting the appearance of the table. The next two sections go over all ten table-related tags and their attributes. Tags The tags mentioned above, and are used in most tables but there are 10 table-related HTML tags available. Here's the complete list, including some of the most frequently used attributes of those tags. Tag Description Frequently Used Attributes table border, cellspacing, cellpadding, bgcolor, align row align, nowrap header none body none footer none column span, align, bgcolor column group span, align The , , and tags work together to partition the table into sections. All three can be used to group rows together. The and row groups will display as normal rows but when the table is printed both row groups will be included at the top and bottom, respectively, of the printed table. The basic HTML table model is row-centric. With the and tags a table can be dealt with as a collection of columns, with attributes set at the column level rather than at the row level. Return to top of document Attributes Here are some of the commonly-used attributes for the primary table-related tags. Most require a numerical value. Where specific values must be used, the allowed values are shown in brackets []. The nowrap attribute requires no value. To use it, simply insert it into the appropriate tag. For information how to enter color values, see the colors section of this site.
cell align, valign, colspan, rowspan, nowrap header align, valign, colspan, rowspan, nowrap
caption none tag simply puts a caption next to the table. The caption can be above or below the table, and is placed outside any table border. The
border: thickness of the border around the table (pixels) cellpadding: space between the edge of a cell and its contents (pixels) cellspacing: space between cells (pixels) bgcolor: color of the background align: alignment of the table to surrounding text [left | right] align: horizontal alignment of cell contents [left | center | right] valign: vertical alignment of cell contents [top | middle | bottom | baseline] bgcolor: color of the background and are not usually needed. Today's browsers will automatically fill them in as needed. - If you want a table indented from the left side of the page, enclose it between a pair of unordered list tags (
    ...
), with no
  • tag. - Tables can be embedded. The contents of a cell in one table can be an entire table. - Use the
  • or align: horizontal alignment of cell contents [left | center | middle | right] valign: vertical alignment of cell contents [top | middle | center | bottom | baseline] colspan: number of columns the cell extends rowspan: number of rows the cell extends nowrap: do not use word wrap within the cell (no value) bgcolor: color of the background Tables are pretty straight-forward but there are a few things to know about that might cause you some trouble. - Empty Cells - when tables are built they do not create borders around empty cells. Use the special code &nbsp, which represents a space to put something in the cell so that the border is displayed. - The end tags
    tag to create a title for a table. This is easier than creating a row with a single cell which spans the entire width of the table. - The
    header tags can be used anywhere in the table. They don't have to go only in the first row. I often put them at the top and bottom of the table, especially for long tables. ----E ----H ----E ----T 12 Colors HTML _tutorials 2005-02-24 20:32:52 ----O 0 0 0 ----E ----D ----E ----C ..Colors in Windows programs are represented by a 24 bit number, consisting of 8 bits for each of the colors Red, Green, and Blue. This allows computers to display about 16.8 million colors, The 8 bits simply means that the value for each of the Red, Green, or Blue components can be any number from 0 to 255. There are two basic ways to write the value of a color - as regular number (0 to 16,777,216) or as a hexadecimal string. HTML is normally written using the hexadecimal string for a color. To get the hexadecimal string representing a color, simply concatenate the hexadecimal representation of each Reg, Green, Blue component as follows (note the pound sign in front of the hex color string): Color HEX Color RGB #000000 R, G, B values are 0, 0, 0 (black) #FF0000 R, G, B values are 0, 255, 0 (red) #00FF00 R, G, B values are 0, 255, 0 (green) #0000FF R, G, B values are 0, 255, 0 (blue) #C0C0C0 R, G, B value are 192, 192, 192 (dark gray) #FFFFFF R, G, B values are 255, 255,255 (white) The W3C HTML specification supports 16 standard colors, which can be use by name anywhere an HTML attribute requires a color: aqua gray navy silver black green olive teal blue lime purple white fuchsia maroon red yellow Most browsers additionally support names for a larger number of colors than the W3C standard. Web Safe Colors At one time, when many computers were limited to 256 display colors, attempts were made to standardize on 216 Web Safe Colors (not 255 so as to allow for OS reserved colors). This standard is of little value now. ----E ----H ----E ----T 13 Cascading Style Sheets (CSS) I - Basics HTML _tutorials 2005-03-05 13:44:46 ----O 0 0 0 ----E ----D ----E ----C CSS provides a more capable replacement to the use of attributes within tags to control how an HTML is formatted. Instead of using attributes for every tag on the HTML page, CSS allows the creation of a single set of rules which can control the display of one, or all, tags in the entire documents. Even better, the CSS rules can be kept in external files - to be applied to every web page on a web site, controlling the look of a web site from a single, common set of rules. There are roughly 3 ways in the CSS rules, or styles, can be applied. 1. Placed within the HTML document between a tag pair. 2. Placed within an individual HTML tag 3. Placed in a separate file which can be called by the HTML page. Style rules are written to apply to the contents of one or more HTML tags. In this example, a style rule is written which applies to all

    tags, causing the text to be displayed in green. When placed in the section of the HTML page, every

    in the entire document will be affected. The rule takes the form of tag { attribute : value } More than one attribute can be placed in a rule like the following example, where the attribute:value pairs are separated by semicolons. More than one rule can be included between the This could be written as a single rule, like this, where multiple HTML tags are listed in front of the one or more attribute:pairs You can give an individual rule a name of its own, which would be called a class, like this: Then, in any HTML tag where you want the rule to apply, add the class attribute like the next example to have the rule apply to this instance of the HTML tag:

    You can narrow down the range of HTML tags to which a class applies by changing the classname as shown in the next example: Here, the class would only apply to

    tags whose class attribute is 'myclassname'. The rules would not apply to any other type of HTML tag, regardless of what the value of the class attribute. If desired, you can write a style which can be applied to one, and only one, element of a given type of HTML tag - such as a specific instance of a

    or an

    tag. This is done by setting the HTML tag 'id' attribute to a unique value, as in the following example: This rule would apply to the tag whose id was set to 'uniqueID', as in this HTML tag example:

    Used in this way, the rule can be applied to only one tag of a particular HTML tag type, but there can be multiple (different) HTML tags types which have the id, as in these examples of HTML tags:

    Finally, the ID definition can be restricted to apply to a single HTML tag type by placing the HTML tag in front of the pound sign, like this: The p# which starts the rule means this applies to the single

    tag which has a matching ID. Another use for the ID of an element is found with the getElementByID() method of the document object. By assigning an HTML tag (element) with an ID attribute value, the getElementByID() method can be use to get a reference to that element for use within your JavaScript programs. Here's an example:

    Content of the tag

    Finally, CSS recognizes comments, which is text surrounded by /* and */ ----E ----H ----E ----T 14 Cascading Style Sheets (CSS) II - Inline/External Styles HTML _tutorials 2005-03-05 13:44:52 ----O 0 0 0 ----E ----D ----E ----C External Style Sheets When designing a web site with many pages it is often desirable to maintain the same look and feel from one page to another. CSS makes that an easy task by allowing an HTML page to call up style sheets saved in separate files. The first step is to save the style rules (everything normally found between ) into a text file. The .css extension is normally used but is not required. The The @import rule causes the content of the external file to inserted into the ----E ----H ----E ----T 20 Error handling JavaScript _tutorials 2005-03-03 13:28:27 ----O 0 0 0 ----E ----D ----E ----C JavaScript fires an onerror event if an error occurs. The user must add onError code into any tags where an error must be caught. You can tell JavaScript to run a custom error handling function like this: window.onerror = myErrorHandler; where the windows onerror proprery is assigned the name of your customized error handling function. The function must accept 3 parameters - a string message, URL of page causing error, and line number of error. function myErrorHandler ( msg, url, line) { //your code goes here return true; } ----E ----H ----E ----T 21 Databases JavaScript _tutorials 2005-03-03 13:33:23 ----O 0 0 0 ----E ----D ----E ----C JavaScript provides no built-in functions for handling databases. It cannot read files from the user's PC, but any filename entered by the user into the fileupload control can also be read or changed by JavaScript. ----E ----H ----E ----T 22 Objects JavaScript _tutorials 2005-03-01 20:33:06 ----O 0 0 0 ----E ----D ----E ----C The various interface elements of a form are treated as objects - having properties and methods which JavaScript can access or modify. See the next tutorial for the standard object heirarchy of a browser page. In code, an ways to reference a form (window part can be optional) - window.document.forms[index] - window.document.forms["name"] - window.documents.forms.name . window.document.name Objects have properties and methods Variables can be defined as an object type or as a ref variables are objects - have properties and methods X = myobject["property_name"] = 6 object.property = "value" // literal string or number var MyVar = window.open("hello.html","html_name","width=200,height=200"); //variable can be made to refer to an object x = object.method(); // shows how to use methods // note that the parentheses are required, even though the method has no arguments // the parentheses () provide a visual that a function/method is being used x = x.toUpperCase(); // uses the variable method to change its case x = x.fontcolor('red'); // uses the variable method to change fontcolor X = document.forms(0).elements(0).name X = document.MyForm.MyText.name you can add properties or methods at will - property - simply assign - methods - create function first i.e., such as oldfunction - myobj.newmethodname=oldfunction you can create a new object of your own creation: - define structure function AnyObject (a,b,c){ this.a this.b } - create instance X = new AnyObject Web Page Objects: document table form button image link Built-in Objects - string - math - date - array - option - function How to use objects in a window: The first image in an HTML document is document.images[0] the second is document.images[1], and so on. If you want to know how many images are in a document, you can find out by checking the length of the images array: document.images.length. On a web page with a form named "myform", access the form with: window.document.myform On a web page with a form named "myform", access the form with: window.document.myform Common Properties/ Methods ---------------------------------------------- methods are always followed by parenthesis, whether they have arguments or not window methods: open window.open("URL","name","features"); close blur focus properties: status window.status="hello"; document methods: writeln window.writeln("test line of text"); // add \n character write window.writeln("test line of text"); // does not add \n character properties: array methods: properties: length document.images.length -- gives number of images in the document date methods: getSeconds getMinutes getHours properties: length document.images.length -- gives number of images in the document Sample .open usage window.open("URL","name","location,menubar"); window.open("URL","name","location=no,status=no"); window.open("URL","name","location,height=100,width=100"); ----E ----H ----E ----T 23 Browser Object Model JavaScript _tutorials 2005-03-04 20:09:54 ----O 0 0 0 ----E ----D ----E ----C --------- Browser Object Model --------------------------------------------------------------------- Window - Navigator - Frames - Location - History - Screen - Document location applets images anchors embeds links plugins stylesheets forms form button text reset text area password select options radio checkbox submit hidden fileupload --------- Properties and Methods --------------------------------------------------------------------- Window Document Forms Properties Methods Properties Methods Properties Methods closed alert() alinkColor clear() action submit() defaultStatus blur() anchors open() elements reset() document clearInterval() applets close() enctype frames clearTimeout() bgColor write() length history close() cookie writeln() method location focus() domain setInterval() name name moveBy() embeds clearInterval() target navigator moveTo() fgColor setTimeout() opener open() forms clearTimeout() parent prompt() images parent resizeTo() lastModified screen scroll() linkColor status scrollTo() links top confirm() location plugins referrer title URL vlinkColor ???? menubar - include File, Edit, ... etc. scrollbars - resizable - when available, window can be resized width - width of the window in pixels. height - height of the window in pixels. toolbar - browser toolbar, which contains the Back, Forward, Stop ... buttons location - text area of a browser into which you can type URLs. Referencing Forms and Elements--------------------------------------- Forms window.document.forms[index] window.document.forms["name"] window.documents.forms.name window.document.name Elements form.elements[index] form.elements["name"] form.name Elements of a form ------------------------------------------ command buttons submit, reset, button text elements text password fileupload textarea hidden buttons radio checkbox lists select (single) select (multiple) option Form Element Properties/Methods/Events ------------------------ Common properties of elements: form, name, type text Property: value Methods: blur, focus, handleEvent, select Events: blur, change, focus, select, keydown, keypress, keyup textarea Property: value Methoods: blur, focus, handleEvent, select Events: keydown, keypress, keyup password Property: value Methoods: blur, focus, handleEvent, select Events: keydown, keypress, keyup fileupload Property: value Methoods: blur, focus, handleEvent, select Events: blur, change, focus hidden Property: value Methoods: - Events: - checkbox Property: checked, value, checked Methoods: click, handleEvent Events: click, mouseDown, mouseUp radio Property: checked, value, length Methoods: click, handleEvent Events: click, mouseDown, mouseUp select Property: length, options, selectedIndex Methoods: blur, focus, handleEvent Events: blur, change, focus option Property: index, selected, text, value Methoods: - Events: - ----E ----H ----E ----T 24 Objects - built-in JavaScript _tutorials 2005-03-05 14:12:59 ----O 0 0 0 ----E ----D ----E ----C String, Math , Date, Array, Location and History are built-in objects --------- Properties and Methods --------------------------------------------------------------------- String Math Date Properties Methods Properties Methods Properties Methods --------------- ------------- ---------------- ------------- ---------------- -------------- length anchor E abs none getDate big LN2 acos getDay blink LN10 asin getHours bold LOG2E atan getMinutes charAt LOG10E ceil getMonth fixed PI cos getSeconds fontColor SQRT1_2 exp getTime fontSize SQRT2 floor getTimeZoneOffset indexOf log getYear italics max setData astOf min setHours link pow setMinutes small random setMonth strike round setSeconds sub sin setTime substring sqrt setYear sup tan toGMTString toLowerCase toUpperCase Location History Properties Methods Properties Methods --------------- -------------- ----------------- --------------- hash reload length back host replace forward hostname go href pathname port protocol search See individual tutorials on String, Math, Date, and Array objects ----E ----H ----E ----T 25 Event handlers JavaScript _tutorials 2005-03-03 09:07:08 ----O 0 0 0 ----E ----D ----E ----C Event handlers - are code that is called when an event occurs - are placed in HTML tag pair just like attributes - not all tags support all events (see list below) - can be one or more JavaScript statements, sepearated by semicolons - long statements can be broken across several lines Syntax for an event handler is: - Notice the semicolon - You can have multiple event handlers inside an HTML tag (one for each event you wish to respond to) - code can call other JavaScript functions - 'this' keyword refers to the object in which the attirbute is contained Other Examples: Click
    //1 event handler in a tag Click
    //multiple event handlers in a tag Click
    // redirect to function Update() document.onClick = "MyFunction()" // event handlers are properties of that object! onClick = "location:'my.gif'" // has browser display this image onClick = "location:'http://www.vbinformation.com'" // sends browser to the new URL Description of event handlers --------------------------------------------- onClick - click on form element or link onChange - change value of text, textarea, or select element onFocus - form element gets input focus onBlur - form element loses input focus onMouseOver - mouse over a link or anchor onMouseOut - mouse leaves link or anchor onSelect - user selects form element's input field onSubmit - submit a form onResize - browser window is resized onLoad - window loads onUnload - window unloads Events and the Elements That Support Them ------------------------------------------------------------------------------- abort img blur body, frameset, all form objects (except hidden) change input, select, textarea click most tags dblclick most tags error img focus body, frameset, all form objects (except hidden) keydown most tags keypress most tags keyup most tagsg load body, frameset mousedown most tags mousemove most tags mouseout most tags mouseover most tags mouseup most tags reset form select input, textarea submit form unload body, frameset ----E ----H ----E ----T 26 Cascading Style Sheets (CSS) I - Basics JavaScript _tutorials 2005-03-05 08:05:23 ----O 0 0 0 ----E ----D ----E ----C CSS provides a more capable replacement to the use of attributes within tags to control how an HTML is formatted. Instead of using attributes for every tag on the HTML page, CSS allows the creation of a single set of rules which can control the display of one, or all, tags in the entire documents. Even better, the CSS rules can be kept in external files - to be applied to every web page on a web site, controlling the look of a web site from a single, common set of rules. There are roughly 3 ways in the CSS rules, or styles, can be applied. 1. Placed within the HTML document between a tag pair. 2. Placed within an individual HTML tag 3. Placed in a separate file which can be called by the HTML page. Style rules are written to apply to the contents of one or more HTML tags. In this example, a style rule is written which applies to all

    tags, causing the text to be displayed in green. When placed in the section of the HTML page, every

    in the entire document will be affected. The rule takes the form of tag { attribute : value } More than one attribute can be placed in a rule like the following example, where the attribute:value pairs are separated by semicolons. More than one rule can be included between the This could be written as a single rule, like this, where multiple HTML tags are listed in front of the one or more attribute:pairs You can give an individual rule a name of its own, which would be called a class, like this: Then, in any HTML tag where you want the rule to apply, add the class attribute like the next example to have the rule apply to this instance of the HTML tag:

    You can narrow down the range of HTML tags to which a class applies by changing the classname as shown in the next example: Here, the class would only apply to

    tags whose class attribute is 'myclassname'. The rules would not apply to any other type of HTML tag, regardless of what the value of the class attribute. If desired, you can write a style which can be applied to one, and only one, element of a given type of HTML tag - such as a specific instance of a

    or an

    tag. This is done by setting the HTML tag 'id' attribute to a unique value, as in the following example: This rule would apply to the tag whose id was set to 'uniqueID', as in this HTML tag example:

    Used in this way, the rule can be applied to only one tag of a particular HTML tag type, but there can be multiple (different) HTML tags types which have the id, as in these examples of HTML tags:

    Finally, the ID definition can be restricted to apply to a single HTML tag type by placing the HTML tag in front of the pound sign, like this: The p# which starts the rule means this applies to the single

    tag which has a matching ID. Another use for the ID of an element is found with the getElementByID() method of the document object. By assigning an HTML tag (element) with an ID attribute value, the getElementByID() method can be use to get a reference to that element for use within your JavaScript programs. Here's an example:

    Content of the tag

    Finally, CSS recognizes comments, which is text surrounded by /* and */ ----E ----H ----E ----T 27 Cascading Style Sheets (CSS) II - Inline/External Styles JavaScript _tutorials 2005-03-04 19:35:42 ----O 0 0 0 ----E ----D ----E ----C External Style Sheets When designing a web site with many pages it is often desirable to maintain the same look and feel from one page to another. CSS makes that an easy task by allowing an HTML page to call up style sheets saved in separate files. The first step is to save the style rules (everything normally found between ) into a text file. The .css extension is normally used but is not required. The The @import rule causes the content of the external file to inserted into the





    Move your mouse over the image above. Try clicking on it also!
    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Make table rows disappear JavaScript graphics 2005-03-06 20:35:34 ----O 0 0 0 ----E ----D ----E ----C Make table rows disappear ----------------------------------- ----E ----H ----E ----T Move an image across the screen JavaScript graphics 2005-03-06 20:33:17 ----O 0 0 0 ----E ----D ----E ----C
    ----E ----H ----E ----T Preload images JavaScript graphics Top100 2005-03-06 20:22:11 ----O 0 0 0 ----E ----D ----E ----C images can be kept in a page, invisible, by loading them into a JavaScript variable that is delcared as an image object var HiddenImage = new Image() HiddenImage.src = "myPicture.jpg" You can use the hidden image to set the property of a visible control. Create a normal tag: Then change it's image with JavaScript document.theimage.src = HiddenImage.src ----E ----H ----E ----T Rainbow text JavaScript graphics Top100 2005-03-06 20:11:41 ----O 0 0 0 ----E ----D ----E ----C



    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Random image JavaScript graphics Top100 2005-03-06 20:10:27 ----O 0 0 0 ----E ----D ----E ----C



    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Rollover JavaScript graphics Top100 2005-03-04 08:22:41 ----O 0 0 0 ----E ----D ----E ----C when mouse moves over the image, the image changes. when mouse moves away from the image, the image returns to it's prior state can use the
    or tag - both support the onMouseover event Method 1 ------------------------------------------------- Method 2 (faster) ------------------------------------- ----E ----H ----E ----T Screen size JavaScript graphics Top100 2005-03-06 20:15:03 ----O 0 0 0 ----E ----D ----E ----C alert('Your screen is:\n\n' + screen.width + ' pixels by ' + screen.height + ' pixels'); ----E ----H ----E ----T Show or hide content JavaScript graphics Top100 2005-03-06 20:34:46 ----O 0 0 0 ----E ----D ----E ----C Hide and show an article ---------------------------- Sample ----E ----H ----E ----T Slideshow JavaScript graphics Top100 2005-03-06 20:10:33 ----O 0 0 0 ----E ----D ----E ----C


    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Slideshow II JavaScript graphics Top100 2005-03-06 20:14:59 ----O 0 0 0 ----E ----D ----E ----C


    Previous Auto/Stop Next
    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Change all images on a page JavaScript images 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C for (var loop = 0; loop < document.images.length; loop++) { document.images[loop].src = 'spacer.gif'; } ----E ----H ----E ----T Image of the day-of-the-week JavaScript images 2005-03-06 17:50:41 ----O 0 0 0 ----E ----D ----E ----C Create gifs name monday.gif to sunday.gif ----E ----H ----E ----T Wait until page loads to animate GIF JavaScript images Top100 2005-03-06 20:16:47 ----O 0 0 0 ----E ----D ----E ----C



    ----E ----H ----E ----T Infinite loops JavaScript loops 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C // first version while (true) {statements} // second version do {statements} while (true) ----E ----H ----E ----T Add commas to a number JavaScript math Top100 2005-03-06 20:16:53 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T Calculator - advanced JavaScript math 2005-03-06 10:37:48 ----O 0 0 0 ----E ----D ----E ----C



    //Thanks to David Pye for his JavaScript Vaule contribution. ----E ----H ----E ----T Calculator - simple JavaScript math Top100 2005-03-06 20:16:57 ----O 0 0 0 ----E ----D ----E ----C








    ----E ----H ----E ----T Random value JavaScript math Top100 2005-03-04 08:23:03 ----O 0 0 0 ----E ----D ----E ----C X = math.floor ( (upper-lower+1) * math.random() + lower ) ----E ----H ----E ----T Round a value JavaScript math Top100 2005-03-06 20:17:02 ----O 0 0 0 ----E ----D ----E ----C x = math.round(x) ----E ----H ----E ----T Menu - dropdown select JavaScript menu 2005-03-06 18:39:26 ----O 0 0 0 ----E ----D ----E ----C
    ----E ----H ----E ----T Menu - always visible JavaScript menus Top100 2005-03-06 20:24:59 ----O 0 0 0 ----E ----D ----E ----C



    The rest of your site goes here
    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Menu - cascading JavaScript menus Top100 2005-03-06 20:24:59 ----O 0 0 0 ----E ----D ----E ----C
    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Menu - movable JavaScript menus Top100 2005-03-06 20:24:59 ----O 0 0 0 ----E ----D ----E ----C



    Click on "Moveable Menu" to pick
    it up and Double Click to drop it!

    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Menu - navigation buttons JavaScript menus Top100 2005-03-06 20:24:59 ----O 0 0 0 ----E ----D ----E ----C



    Category 1 | Category 2 | Category 3 | Category 4

    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Menu - slide JavaScript menus Top100 2005-03-06 20:24:59 ----O 0 0 0 ----E ----D ----E ----C

    Try the menu out for yourself! Move your mouse over the yellow border to the left.
    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Change status bar content on mouseover JavaScript mouse Top100 2005-03-04 08:23:09 ----O 0 0 0 ----E ----D ----E ----C Mouse me for an answer! ----E ----H ----E ----T Display link info in statusbar JavaScript mouse Top100 2005-03-06 20:17:19 ----O 0 0 0 ----E ----D ----E ----C /* the JavaScript statements are executed when the mouse goes over the link, placing new text in the statusbar */ Go There ----E ----H ----E ----T onClick and MouseOver event examples JavaScript mouse 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C --onClick and onMouseOver event samples (link events) Link Event Example

    Link Events

    Click on me!
    Mouse over me!
    ----E ----H ----E ----T Button as a link - 2 methods JavaScript navigation Top100 2005-03-06 20:15:17 ----O 0 0 0 ----E ----D ----E ----C // JavaScript URL // onClick calls a function to set window.location ----E ----H ----E ----T Directory header JavaScript navigation Top100 2005-03-06 20:16:07 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T Display all event handlers of an object JavaScript navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C document.onClick is a property of document, so use FOREACH to walk through for (var X in Form) { document.write(X+'
    ')} or document.write Forms[X] } ----E ----H ----E ----T Forward-Backward buttons JavaScript navigation Top100 2005-03-06 20:15:25 ----O 0 0 0 ----E ----D ----E ----C
    ----E ----H ----E ----T Go back one page JavaScript navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C history.back ----E ----H ----E ----T Highlight links JavaScript navigation Top100 2005-03-04 21:31:12 ----O 0 0 0 ----E ----D ----E ----C The CSS specification offers several built-in pseudoclasses which represent common situations where you might want to change the appearance of an elements. The four available pseudoclasses are related to links. They are: link visited hover active ----E ----H ----E ----T List all links on a page JavaScript navigation Top100 2005-03-06 20:11:04 ----O 0 0 0 ----E ----D ----E ----C



    List all links on this page
    or
    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Open file JavaScript navigation 2005-03-06 11:12:08 ----O 0 0 0 ----E ----D ----E ----C



    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Remove underline from links JavaScript navigation Top100 2005-03-06 20:15:42 ----O 0 0 0 ----E ----D ----E ----C

    No underline here!

    ----E ----H ----E ----T Slideshow JavaScript navigation Top100 2005-03-04 09:24:17 ----O 0 0 0 ----E ----D ----E ----C To cycle through a number of pages (or images), use the Refresh in each page, pointing to the next page. The last page should point to the first page. /* page 1 */ /* page 2 */ /* page 3 */ /* page 4 */ ----E ----H ----E ----T Stop a form from reloading the page when you click on a Submit button JavaScript navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C put onSubmit="return false;" in the
    tag ----E ----H ----E ----T Stop browser from jumping to top of page when link is clicked JavaScript navigation 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C // Using the # sign may cause the browser to // jump to the top of the page // when the link is clicked. To stop that from // happening, change the link to this: Click on me! ----E ----H ----E ----T Ball drop JavaScript physics Top100 2005-03-06 20:10:43 ----O 0 0 0 ----E ----D ----E ----C



    Click anywhere to start script
    Static ball
    //Thanks to David Pye for his JavaScript Vault contribution ----E ----H ----E ----T Email address protection JavaScript security 2005-03-06 18:40:03 ----O 0 0 0 ----E ----D ----E ----C Look at the souce code of this script to see how to do it. ----E ----H ----E ----T Alternate background sounds JavaScript sound 2005-02-24 22:55:01 ----O 0 0 0 ----E ----D ----E ----C testing ----E ----H ----E ----T Detect browser and play sound JavaScript sound Top100 2005-03-06 20:17:43 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T Play a sound file JavaScript sound Top100 2005-03-04 09:25:06 ----O 0 0 0 ----E ----D ----E ----C /* 1st Method */ Make the embedded player hidden and control it from JavaScript. There are two parts to this: firstly a function (here called EvalSound) which takes the "name" of the hidden embedded player and calls its Play() method. Secondly a link, image or button which calls the function on demand when the component is clicked or has the mouse rolled onto it. /* embed a player and make it hidden */ /* mouseover to play sound */ Move mouse here /* click image to play sound */ /* press button to play sound */ /* 2nd Method */ Use the JavaScript getElementById() function in the EvalSound definition. Note that we specify name of the embedded sound using its ID attribute now. The function calls however are the same as above. For example: /* mouseover to play sound */ Move mouse here /* click image to play sound */ /* press button to play sound */
    ----E ----H ----E ----T External source for script JavaScript syntax Top100 2005-03-04 09:25:31 ----O 0 0 0 ----E ----D ----E ----C //the external file extension does not have to be .js ----E ----H ----E ----T Information Report JavaScript user-system Top100 2005-03-06 20:11:38 ----O 0 0 0 ----E ----D ----E ----C

    (Be sure to pick a mimeType or plugin from the pulldown menu!)


    //Thanks to David Pye for his JavaScript Vault contribution. ----E ----H ----E ----T Close a window JavaScript windows Top100 2005-03-06 20:17:56 ----O 0 0 0 ----E ----D ----E ----C window.close() Note: if JavaScript code tries to close its parent window the browser will open a dialog to confirm the closing of the window. ----E ----H ----E ----T Create content in a new window JavaScript windows Top100 2005-03-06 20:17:59 ----O 0 0 0 ----E ----D ----E ----C Once a window is created, and you know the name of it, you can create content by simply using multiple calls of the .write() method. For example, if you created a new Window named myWindow, then to create content using JavaScript use this code: myWindow.document.open() myWindow.document.write( ""> myWIndow.document.write( "

    Hello

    "> myWIndow.document.write( ""> myWIndow.document.close() You can make the content as complicated as you want, with combinations of HTML tags. ----E ----H ----E ----T Open a new URL in the current window JavaScript windows Top100 2005-03-06 20:18:03 ----O 0 0 0 ----E ----D ----E ----C just use JavaScript to se the .location property of the current window document.location = "http://www.garybeene.com" ----E ----H ----E ----T Open a new window (in current window) JavaScript windows Top100 2005-03-06 20:18:06 ----O 0 0 0 ----E ----D ----E ----C window.open() is the method to use. it support 4 optional arguments - URL - name - featuresList -replace //new empty window window.open() or var blankWindow = window.open() // sets a JavaScript variable reference to the window //new window with specified URL window.open ( "http://www.garybeene.com") or var filledWindow = window.open ( "http://www.garybeene.com") featuresList has the following flags that can be used in the string. To set a flag, just enter 'flagname = yes' in the string. Separate flags by commas: directoriies yes/no if window should have a set of directory buttons height positive integer height in pixels width postive integer width in pixels location yes/no if window should have box user can type URL into menubar yes/no if window should have main menu bar resizable yes/no if user is allowed to resize the window scrollbars yes/no if the window should have scroll bars status yes/no if there should be a status bar at the bottom of the window toolbar yes/no if window should have a main toolbar ----E ----H ----E ----T Open window of specific size JavaScript windows Top100 2005-03-06 20:18:11 ----O 0 0 0 ----E ----D ----E ----C window.open('window-sizer.html','640x480','toolbar=yes,status=yes,scrollbars=yes,location=yes,menubar=yes,directories=yes,width=640,height=480')} window.open('window-sizer.html','800x600','toolbar=yes,status=yes,scrollbars=yes,location=yes,menubar=yes,directories=yes,width=800,height=600')} ----E ----H ----E ----T Pass data between windows JavaScript windows Top100 2005-03-06 20:18:15 ----O 0 0 0 ----E ----D ----E ----C The window from which a second window is created is referred to a the 'operner' of the second window. The first window can access the properties of the second window by using the window object returned from the .open() method: var newWindow = document.open ( "http://www.garybeene.com" , "newWin" ) After this code, the new window is named 'newWin' and the current window has a JavaScript variable which is a reference to the new window and can be used to access the properties and methods of the new window. The child window can also access the first window by using its 'opener' property, which refers to the parent window (the one that created the child window). In the new window, use this code to create a variable reference to the parent window: if (self.opener != null ) { var parentWindow = self.opener } Now, the parentWindow variable (that is contained in the child window) can access all of the methods and properties of the parent window Note: an exception is that if the JavaScript in the two windows comes from different servers, the JavaScript will not be able to communicate. ----E ----H ----E ----T Pass data to a new HTML file JavaScript windows Top100 2005-03-06 20:18:17 ----O 0 0 0 ----E ----D ----E ----C ..When a URL is called using the get method, the query string is contained in the location.search property of the new page. An HTML page can send a get request by setting the .href property of the location object: document.location.href="http://www.garybeene.com/newpage.htm?first=hello&second=newcomer" The new page could retrieve the "?first=hello&second=newcomer" from the location.search property like this: alert ( location.search ) ----E ----H ----E ----T Popup window - controlled position JavaScript windows Top100 2005-03-06 20:18:21 ----O 0 0 0 ----E ----D ----E ----C
    Open Window ----E ----H ----E ----T View page source JavaScript windows Top100 2005-03-06 20:18:24 ----O 0 0 0 ----E ----D ----E ----C Type in a full URL and click "View Source"

    ----E ----H ----E ----T Show time/day visitor comes to a web page JavaScript write Top100 2005-03-04 09:25:41 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T Write text to HTML page (write line) JavaScript write 2005-03-04 09:25:48 ----O 0 0 0 ----E ----D ----E ----C document.writeln("Hello people"); // write a specific text string document.writeln(MyVar); // write the value of a variable ----E ----H ----E ----T - Tutorial 01 - Overview Outlook _tutorials 2005-02-17 22:17:17 ----O 0 0 0 ----E ----D ----E ----C Outlook is an application, not a language but it contains the Microsoft Visual Basic for Applications langauge. Please use the online code update (using the File > Import menu option) to check for new code releases. ----E ----H ----E ----T - Tutorial 01 - Simple Perl script Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C #Put the following two lines in a text file, such as myscript.pl: #!/usr/bin/perl print "Hello World"; That's it - the entire Perl script. To run the program type in the following at the command line: perl myscript.pl #The Perl executable reads the text file #and executes any statements it finds. #The first line "#!/usr/bin/perl is the location #of the Perl executable. Is only needed in #UNIX. It is not needed in Windows. #Text after the # symbol is treated as comments ----E ----H ----E ----T - Tutorial 02 - Using Perl on the web (CGI) Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C Perl scripts often reside on a server and may be called into action via submission of a form from a web page. In its most common usage, a Perl script responds to the request from a form and creates a web page (text file that is formatted to HTML standards) that is returned to the requestor - dynamic page generation. Here's a sample calling HTML page, which has a form with a single submit button that sends a request to the server to run the Perl script called decide.pl.

    Decide

    Here's the script that would be run: #!/usr/bin/perl print "Content-type: text/html\n\n"; print ""; print "Your answer is " + $answer; print " In general, the output of the Perl program (via the print statement) is fed to the HTTP server, which in turns sends it back to the requestor. The first line of the script provides the only HTTP header information needed for the browser to correctl interpret the output of the script as an HTML page. ----E ----H ----E ----T - Tutorial 03 - Overview Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C Perl source code is simply lines of text (a script) which the perl.exe program executes one by one, starting from the top. Perl has a very loose formatting requirement - freespace to left of statement is ignored - indent all you want - freespace anywhere except in string literals is ignored - end all statements in semicolon ; - anything on a line after a # is ignored - is a comment - Perl executes top to bottom - Sub routines can be placed anywhere within the code - convention is at bottom - Sub routines can be referenced before they appear - Perl is case sensitive - () parenthesis, when normally used, are optional - term "escape" is means to prevent character from being interpolated within quotes Data types $ scalar (numbers and strings) @ arrays % associative arrays & Subroutines ----E ----H ----E ----T - Tutorial 04 - Variables Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C Variables can be number or strings. Perl handles the conversions. Variables start with $ $string = "Gary Beene" Arrays start with @ @myarray Associative arrays begins with % %myarray You create a variable by using it. No separation definition or dimensioning is required. $myvar = 5 ----E ----H ----E ----T - Tutorial 05 - Operators Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C 0 is False "0" is False "" is False undef is False all else is True print True; # prints a blank print False; # prints a blank undef # variables which have not been set have a value of undef # using -w will catch # some functions return undef on failure Numeric: $x==$y True if $x equals $y $x > $y $X < $y $x >= $y $x <= $y $x != $y True is $x is not equal to $y AlphaNumeric: $x eq $y $x gt $y $x lt $y $x ge $y $x le $y $x ne $y Logical Operators: And/Or/Not can each be written in two ways: && and # $a && $b $a and $b || or # $a || $b $a or $b ! not # ! $b not $b Special operators: $c++ # same as $c = $c + 1 $c-- # same as $c = $c - 1 $a+=3 # same as $a = $a + 3 $y*=$x # same as $y = $y * $x $r%=67 # same as $r = $r % 67 qq() # quote-quote (double quotes) q() # quote (single quote - no interpolation) qw() # list with no interpolation (uses whitespace to separate list items) $#myarray # used to resize @myarray ----E ----H ----E ----T - Tutorial 06 - Strings Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C $mystring = "Gary Beene" $mystring = 'Gary Beene' $total = $mystring1 + $mystring2 Single or double quotes are allowed. If double quotes are used, variables placed inside the quotes are replaced with their value (interpolated). If single quotes are used, interpolation is not performed. Example: $mystring1 = "X" $mystring2 = "aaa$mystring1bbb" In this example, $mystring2 contains "aaaXbbb" Some important built-in Perl string functions include: split 1. @myarray = split (/ /,"The dog is mine") # split string into array # / / gives pattern for the split 2. @myarray = split (//, "The dog is mine") # // splits string into individual characters 3. @myarray = split ("The dog is ming") # if // is left out, whitespace is used 4. @myarray = split (/,/) # if string is left out, split uses $_ 5. ($a, $b, $c) = split(/,/,"One,Two,Three") # string is split and assigned to variables join 1. @myarray = join (/ /, ($a, $b, $c) # split string into array # / / gives pattern for the split 2. @myarray = split (//, "The dog is mine") # // splits string into individual characters 3. @myarray = split ("The dog is ming") # if // is left out, whitespace is used 4. @myarray = split (/,/) # if string is left out, split uses $_ 5. ($a, $b, $c) = split(/,/,"One,Two,Three") # string is split and assigned to variables reverse 1. string $newstring = reverse "1234" # reverses the string 2. array @newarray = reverse @myarray # reverses the elements search 1. index index string, substring, start_position # return position of substring # 0 is far left position 2. rindex index string, substring, start_position # from right, not left 3. substr string, offset, length # extract part of a string # negative offset start from right replace substr ($a,0,1) = "replacestring" # replace 1st character with replacestring substr ($a,0,0) = "replacestring" # put string at front of replacestring substr ($a,-7,7) = "replacestring" # replace last 7 characters with replacestring tr/searchlist/replacementlist # replace 1st list with 2nd list tr/ABC/XYZ/; # replace A's with X's, B's with Y's, C's, with Z's # work on $_ ----E ----H ----E ----T - Tutorial 07 - Conditional Flow Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C Perl has 4 loop modifiers: while, until, for, foreach if (expression) BLOCK elsif BLOCK else BLOCK while (expression) BLOCK # while(1) BLOCK will loop forever. use "last" to exit for ( initialization; test; increment) BLOCK last # exit while once current loop is complete # example: last if ($i == 10) redo # redo next # next goto LABEL # absolute flow control foreach $element (@myarray) # $element is a reference to each value of @myarray { print "$element\n"} # the (@myarray) can also be a list ("one", "two", "three") until (expression) Block Label-control statements # label can be used with next/last/redo to control looping next # jumps to the next iteration - if used with label, jumps to loop marked by label last # immediately breaks out of the loop - if used with label, jumps to loop marked by label redo # causes loop to execute again - if used with label, jumps to loop marked by label LBL: foreach (@fruit) { Foreach $place (@state) { last LBL if $place eq "Texas"; # use of label drops out of nested loops! } } Simplest is to execute a statement based on True/False condition of an expression: # Perl has four modifiers: if, unless, while, until if (test-expression) BLOCK # primary format -or- (expression) if (test-expression) # alternate format lets if come last # example: last if ($i == 10) Examples of modifier at end of line: $max = 100 if $min < 100 ; # executes first statement if ($min < 100) is True print "Success" unless $error > 2; $total++ while $total < 500 # executes repeatedly $a = $a + 6 until $a > 100 # executes repeatedly Compound statements: Execution of expressions can depend on other expressions using one of the modifiers if, unless, while or until, for example: EXPR1 if EXPR2 ; EXPR1 until EXPR2 ; The logical operators ||, && or ?: also allow conditional execution: EXPR1 || EXPR2 ; EXPR1 ? EXPR2 : EXPR3 ; Statements can be combined to form a BLOCK when enclosed in {}. Blocks may be used to control flow: if (EXPR) BLOCK [ [ elsif (EXPR) BLOCK ... ] else BLOCK ] unless (EXPR) BLOCK [ else BLOCK ] [ LABEL: ] while (EXPR) BLOCK [ continue BLOCK ] [ LABEL: ] until (EXPR) BLOCK [ continue BLOCK ] [ LABEL: ] for (EXPR; EXPR; EXPR) BLOCK [ LABEL: ] foreach VAR† (LIST) BLOCK [ LABEL: ] BLOCK [ continue BLOCK ] Program flow can be controlled with: goto LABEL Continue execution at the specified label. last [ LABEL ] Immediately exits the loop in question. Skips continue block. next [ LABEL ] Starts the next iteration of the loop. redo [ LABEL ] Restarts the loop block without evaluating the conditional again. Special forms are: do BLOCK while EXPR ; do BLOCK until EXPR ; which are guaranteed to perform BLOCK once before testing EXPR, and ----E ----H ----E ----T - Tutorial 08 - Arrays Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C pop @myarray # remove from top of array push @myarray, new_list # add to top of array - return removed item shift @myarray # remove from bottom of array - return removed item unshift @myarray, new_list # add to bottom of array pop/shift/unshift/push act on @_ in a subroutine (if not specified) pop/shift/unshift/push act on @ARGV outside a subroutine (if not specified) splice @myarray, offset # remove elements starting from offset splice @myarray, offset, length # only remove length elements splice @myarray, offset, length, list # replace removed elements with list @sortedarray = sort @myarray # sort by ASCII Range operators: (1..10) #range operator (1..10, 21..30) #range operator (a..z) #range operator (aa..zz) #range operator ----E ----H ----E ----T - Tutorial 09 - Associative array Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C # associative array is a list of values indexed by strings (called keys) # a regular array uses numbers for indexes, starting with 0 %myhash = ("Name", "Gary", "Age", 51) # key-value pairs # assign list to hash $myhash{'Name'} = "Billy" # assign single k-v pair $a = $myhash{'Name'} # assign hash value to variable @keylist = keys @MyHash # keys function retrieves all the keys of a hash # random order @valuelist = values @MyHash # values function retrieves all values of a hash # same order as keys @reversehash = reverse @MyHash # reverses key-value pairs (keys become values) # duplicate values are dropped $num_keys = scalar keys %hash # find number of entries in a hash array %hash = %myhash # copies entire %myhash into %hash2 Iterate over a hash 1. foreach $key ( keys %MyHash) # 'keys %myhash' creates list of all keys { print "$key :$MyHash{$key} \n"; } # print each key, then its value 2. while ( ($key , $vlaue) = each %MyHash) # goes through keys 1 at a time { print "$key :$MyHash{$key} \n"; } # print each key, then its value delete a key: delete $Hash{keyvalue} remove all keys: %Hash = () reverse the key/value pairs: %reversehash = reverse %hasharray ----E ----H ----E ----T - Tutorial 10 - Subroutines Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C sub mysubroutine # Example: sub yesno BLOCK # Note no arguments listed in the "sub" line { print "you made it!"; } # there is no fixed number of arguments To call a subroutine: $mysubroutine(); # ok anywhere in the Perl code -or- mysubroutine(); # if sub was already defined in the code -or- $mysubroutine ($var1, 23.5, "mother") # includes arguments -or- $mysubroutine $var1, 23.5, "mother" # without () if sub already seen Returning a value: all subroutines return a single value - can be scalar, array, assoc array default is to return the last expression's value -or- return (expression) # example: return ($temp) --> return a scalar value # example: return (0) --> return a specific value # example: return (@myarray) --> return an array Sub test { print "hi" $result; # to clarify return value, put the value to be returned on the last line } Pass values to subroutine: $mysubroutine ($var1, 23.5, "mother") # includes arguments Retrieve returned values: @_ is an array that has all the passed arguments To simplify access to @_, use: ($a, $b, $c) = @_ To simplify as above, pass scalar variables first, then array You can effectively pass only 1 array to sub (and keep it distinct) $_[0] is the 0th element of the array @_ $_[2] has nothing to do with scalar special variable $_ If you change a value of @_, the passed argument changes also To retrieve multiple arrays, use references Pure function: can be used by another program without relying on context it's being called in Subroutine example: #!/usr/local/bin/perl # # Declare and Define subrouting MY_SUB # call MY_SUB three times # # subroutine MY_SUB # sub MY_SUB { local ( $param_1, $param_2 ) = @_ ; print "\n Called MY_SUB \n \t $param_1 \n \t $param_2 \n" ; } # # MAIN part of the program # for ( $i=0; $i<3; $i++ ) { &MY_SUB ( "text", 123 ) ; } # # DONE # ----E ----H ----E ----T - Tutorial 11 - Databases Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C dbmopen (%myhash, "hashname", 0644); # opens hashname.pag & hashname.dir dbmclose (%myhash); # change the %myhash values changes the content of the dbm file # %myhash content before dbmopen is removed # %myhash content after dbmclose is removed delete $Hash{keyvalue} # delete a pair %Hash = () # remove all entries ----E ----H ----E ----T - Tutorial 12 - Regular expressions Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C /xxx/ is a string between slashes. The string is called a Regular Expression ($a =~ /abc/) # the expression is true if "abc" is found in $a $string =~ /the/ # is True if "the" is in the variable $string $string !~ /the/ # is True if "the" is NOT in the variable $string Special characters between the slashes affect how the matching is tested match m// # m/abc/ matches if abc is found in $_ substitute s/// # s/abc/123/ substitue 123 for abc list matching grep # metacharacters \n newline \t TAB . any single character * ? character class [abcde] # match any of a,b,c,d,e [a-e] # match any of a,b,c,d,e [0-9] # match a digit [*!@#$%&()] # match any of these punctuation marks ^ # caret as first character negates the match anchors /^xxx/ # matches if line starts with xxx /$xxx/ # matches if line ends with xxx Assertions: used to anchor parts of the pattern Example Matches Doesn't Match to word or string boundaries ^ start of string ^fool folish tomfoolery $ end of string fool$ April fool foolish \b word boundary be\bside be side beside \B nonword boundary be\Bside beside bd side Atoms: building blocks of a regular expression . any character b.b bob bb [] list of characters in brackets ^[Bb] Bob, bob Rbob () regular expression ^a(b.b)c$ abobc abbc Quantifiers: modifier for an atom * zero or more instances of the atom ab*c ac, abc abb + one or more instances of the atom ab+c abc ac ? zero or one instances of the atom ab?c ac, abc abbc {n} n instances of the atom ab{2}c abbc abbbc {n,} at least n instances of the atom ab{2,}c abbc, abbbc abc {n,m} at least n, at most m instances of the atom ab{2,3}c abbc abbbbc Special Characters: \n \d any digit b\dd b4d bad \D nondigit b\Dd bdd b4d \n newline \t TAB \s white space character \S non white space char \w alphanumeric char a\wb a2b a^b \W nonalphanumeric char a\Wb aa^b aabb Match Options: g perform global matching - even after first match has been found i perform case-insensitive matching o evaluate regular expresssion one time only Backreferences: When performing matches, you can direct Perl to track all of the parts of the string in which the match succeeded. The results will be stored in variables $1 $2 ... Examples: $string =~ /^x/ tests for x at the start of the string $string =~ /$x/ tests for x at the end of the string $string =~ /./ tests for any single character $string =~ /t.e/ tests for t and e separated by any one character $string =~ /^$/ tests for a string with nothing in it $string =~ /[a-z]/ test for any one character of any lower case letter $string =~ /[a-zA-Z]/ test for any one character of any letter $string =~ s/dog/cat/ replaces dog with cat first time it appears in the string $string =~ s/dog/cat/gi replaces dog with cat anywhere in the string, case insensitive ----E ----H ----E ----T - Tutorial 13 - File handling Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C < open for reading - default > open for writing >> open for appending +< open for both reading and writing +> open for both reading and writing | (before file name) treat file as command into which Perl is to pipe text | (after file name) treat file as command from which input is to be piped to Perl <> # special operator for reading from files # returns 1 line if used in scalar context # returns all lines is used in array context --- Open for reading: open (filehandle, pathname) # make up your own name for filehandle open (Handle, "file.txt") # returns nonzero value if open is successful open (Handle, "file.txt") || die # right side is not executed if open is successful open (Handle, 'c:\temp\file.txt') # note single quotes that allows use of backslash # if Handle is re-used, old file is closed close (Handle) $filedata = # read one line from the file into the scalar $filedata @filedata = # read all lines from the file into the array @filedata <> angle operator used for reading/writing files $c=; # reads from a keyboard (also gets the newline character) chomp $c; # removes the newline character while (defined ($a=)) { print $a ; } while () # while puts input line int0 special variable $_ until EOF { print $_ ; } --- Open for writing: open (filehandle, ">pathname") # open to overwrite open (filehandle, ">>pathname") # open to append --- Write to file: print MYFILE LIST # no comma (except in list) --- File Test Operators: $a = (-e 'file.txt') # True if file exists $a = (-s 'file.txt') # returns size of file in bytes $a = (-d 'c:\temp') # True if 'c:\temp' is a directory --- Rename a file: rename($old, $new); --- to delete line at end of a file, use 'tell' and 'truncate' statements --- Read a single character from a file: use the 'getc' function ----E ----H ----E ----T - Tutorial 14 - Command Summary Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C int int(50.5) # returns integer portion, use printf function for rounding) length length ("mylist") # length of string lc uc("Dog Star") # lower case uc uc("dog star") # upper case cos cos(50) # cosine in radians rand rand(5) # random number 0 to less than argument, 0-1 if argument omitted ----E ----H ----E ----T - Tutorial 15 - Common mistakes Perl _tutorials 2005-02-17 22:17:21 ----O 0 0 0 ----E ----D ----E ----C Adapted from Programming Perl, page 361. Testing "all-at-once" instead of incrementally, either bottom-up or top-down. Optimistically skipping print scaffolding to dump values and show progress. Not running with the perl -w switch to catch obvious typographical errors. Leaving off $ or @ or % from the front of a variable, or omitting & when invoking a subroutine in Perl 4. Forgetting the trailing semicolon. Forgetting curly braces around a block. Unbalanced (), {}, [], "", '', ``, and sometimes <>. Mixing '' and "", or / and \. Using == instead of eq, != instead of ne, = instead of ==, etc. ('White' == 'Black') and ($x = 5) evaluate as (0 == 0) and (5) and thus are true! Using "else if" instead of "elsif". Not chopping the output of backquotes `date` or not chopping input: print "Enter y to proceed: "; $ans = ; chop $ans; if ($ans eq 'y') { print "You said y\n";} else { print "You did not say 'y'\n";} Putting a comma after the file handle in a print statement. Forgetting that Perl array subscripts and string indexes normally start at 0, not 1. Using $_, $1, or other side-effect variables, then modifying the code in a way that unknowingly affects or is affected by these. Forgetting that regular expressions are greedy, seeking the longest match not the shortest match. ----E ----H ----E ----T Does an array contain an element Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $is_there = grep $_ eq $whatever, @array; # why author didn't like it? $is_there = grep /$whatever/, @array; # why author didn't like it? ----E ----H ----E ----T Extract unique elements of an array Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $prev = 'nonesuch' @out = grep($_ ne $prev && ($prev = $_) , @in); ----E ----H ----E ----T look up a hash by value Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C %by_value = reverse %by_key $key = $by_value($value) ----E ----H ----E ----T modify each element of an array #2 Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C for (@radii) { $_ **=3; $_ *= (4/3) * 3.14159; } ----E ----H ----E ----T print lines r through s of an array Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open (SOURCE, "file.txt"); @all = ; # put all lines in an array close (SOURCE) open (DEST, "file2.txt"); print DEST @all[$r-$s] ; # print lines r through s close (DEST) ----E ----H ----E ----T print only the first n elements of an array to a file Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open(DEST, "test.txt") $i=1; foreach (DEST) { print DEST $_ ; last if $i==9 ; # print only 9 items $i++; } close (DEST) ----E ----H ----E ----T process an entire hash Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C while (($key,$value) = each %hash) { print "$key = $value\n"; } ----E ----H ----E ----T randomly extract from an array until all are gone Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C for (0 .. $#myarray) { # $index = int(rand $#myarray); print “$myarray[$index] ; splice @myarray, $index, 1 } ----E ----H ----E ----T select random element from an array Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C srand; # not needed for 5.004 and later $index = rand @array $element = $array[$index] ----E ----H ----E ----T shuffle an array randomly Perl arrays 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C while (@old) { push (@new, splice(@old, rand @old, 1)); } # randomly pick element for swapping ----E ----H ----E ----T CGI script for web page with complete form Perl cgi 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/usr/bin/perl print < My Web Page

    My Web Page

    This page brought to you by ...
    Dog Cat Pig

    Please pick me!

    WEBPAGE #no trailing spaces allowed ----E ----H ----E ----T CGI script for web page with embedded variables Perl cgi 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/usr/bin/perl $value = "Sample Information" # create your own values or draw them from %ENV print < My Web Page

    My Web Page

    This page brought to you by ...


    $value

    Note that the checkbox name-value pair is not included if it was not checked on the calling form.

    Thank you for trying out this sample Perl script. WEBPAGE #no trailing white spaces allowed ----E ----H ----E ----T CGI script to return a file from the server inside an HTML file Perl cgi 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/usr/local/bin/perl # # Read in the data file # Print out HTML formatted lines # $file = 'data.txt' ; # Name the file open(INFO, "<$file" ) ; # Open the file @lines = ; # Read it into an array close(INFO) ; # Close the file print " PERL output \n" ; print " \n" ; foreach $line (@lines) # assign @lines to $line, one at a time { # braces {} are required, bracket code print "\n

    $line

    " ; # print formatted lines to screen } print "\n \n\n" ; # # DONE # ----E ----H ----E ----T CGI script to return existing page Perl cgi 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/usr/bin/perl #do whatever Perl stuff you want first, then the next line sends the user to an existing page print "Location: http://www.vbinformation.com/index.htm" ; ----E ----H ----E ----T CGI script to return web page with no data Perl cgi 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/usr/bin/perl print < stop_html ----E ----H ----E ----T Get variables from QUERY_STRING Perl cgi 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C if ($ENV{'REQUEST_METHOD'} eq "GET") { $qstring = $ENV{'QUERY_STRING'}; } else { $qstring = ; # read(STDIN, $qstring, $ENV{'CONTENT_LENGTH'}); } @pairs = split(/&/, $qstring); # split the name-value pairs foreach $pair (@pairs) # loop through each pair { ($name, $value) = split(/=/, $pair); # Create a Name/Value pair set $name =~ tr/a-z/A-Z/; # make keys uppercase (optional) $value =~ s/\+/ /g; # change + signs to spaces $value =~ tr/+/ /; # change + signs to spaces (alternate) $value =~ s/%(..)/pack("c",hex($1))/ge; # convert the URI code $in{$name} = $value; # put in hash array %in } print %in ----E ----H ----E ----T Everlasting loop Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C while (1) { print "going and going ….\n" ; } ----E ----H ----E ----T For loop Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/user/bin/perl for ($a=0 ; $a<1000 ; $a=$a+2) { print "Counting .. $a \n"; } sfflow ----E ----H ----E ----T loop through a file Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open (SOURCE, "text.txt") while () # without condition, file is read one line at a time til EOF { chomp; print; } # each line is put into $_. chomp/print operate on $_ close (INPUT) print '\n.. Done!'; ----E ----H ----E ----T loop through a hash Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C foreach $key ( keys %MyHash) { print "$key :$MyHash{$key} \n"; } # print each key, then its value ----E ----H ----E ----T loop through a hash array #2 Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C foreach $key ( keys %MyHash) # 'keys %myhash' creates list of all keys { print "$key :$MyHash{$key} \n"; } # print each key, then its value ----E ----H ----E ----T loop through an array Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C foreach $element (@myarray) # $element is a reference to each value of @myarray { print "$element\n"} ----E ----H ----E ----T loop through array using FOR #2 Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C for $x (0 .. $#myarray) # uses range operator to indicate list over which for operates { print “$myarray[$x]\n”; } ----E ----H ----E ----T loop through array using FOREACH with $_ Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C ----- Loop through array using FOREACH ------- foreach $element (@myarray) # $element is a reference to each value of @myarray { print "$element\n" ; } ----E ----H ----E ----T short circuiting Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C Use OR/AND to determine if a statement is to be exectued: Two ways to use it: Use OR: $value > 10 || print "value is low"; # print right side if left is false Use AND: $value > 10 && print "value is high"; # print right side if left is true ----E ----H ----E ----T while loop Perl conditional looping 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/user/bin/perl $counter=0; while ($counter<10) { print "Still counting .. $counter\n"; $counter' } ----E ----H ----E ----T sendmail Perl email 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq") or die "Can't fork for sendmail: $!\n"; print SENDMAIL <<"EOF"; From: User Originating Mail To: Final Destination Subject: A relevant subject line Body of the message goes here after the blank line in as many lines as you like. EOF close(SENDMAIL) or warn "sendmail didn't close nicely"; ----E ----H ----E ----T print formatting Perl formatting 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C print printf formatstring, list printf filehandle formatstring, list # note that there is no comma after filehandle sprintf # same as printf, except returns a string formatstring: "%-w.dx" # prints all characters except those begining with % (mandatory) # - is left justifed, otherwise right justified (optional) # w is width (optional) # d for numbers is numbers to left of decimal position (optional) # d for strings total width (optional) # x type of data to be printed c-character, s-string # x type of data to be printer d-integer (truncated), f-floating point ----E ----H ----E ----T print samples Perl formatting 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C printf("%20s","Jack"); # right-justify "Jack" in a 20 characters printf("%-20s","Jack"); # left-justify "Jack" in a 20 characters $amt=7.12; printf("%6.2f",$amt); # prints " 7.12" $amt=7.127; printf("%6.2f",$amt); # prints " 7.13" extra digit rounded printf("%c", 65); # print ASCII character for 65, "A" $amt=9.4 printf("%6.2f",$amt); # prints " 9.40" $amt=9.4 printf("%6d",$amt); # prints " 9" $amt=9.4 printf("%06d",$amt); # prints "000009" 0 in front of the 6 says to show leading zeros ----E ----H ----E ----T Find primes Perl math 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/usr/bin/perl -w $maxprimes=20; # Stop when you've found this many $value=1; $count=0; while($count < $maxprimes) { $value++; $composite=0; OUTER: for ($i=2; $i<$value; $i++) { for($j=$i; $j<$value; $j++) { if (($j*$i)==$value) { $composite=1; last OUTER; } } } if (! $composite) { $count++; print "$value is prime\n"; } } ----E ----H ----E ----T perform operation on series of integers Perl math 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C @results = map { my_func($_) | @array; ----E ----H ----E ----T print an array to a file Perl print 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open(DEST, "test.txt") print DEST @myarray; close (DEST) ----E ----H ----E ----T print to more than one file at once Perl print 2005-02-22 15:50:45 ----O 0 0 0 ----E ----D ----E ----C for $fh (FH1, FH2, FH3) { print $fh "whatever\n" } ----E ----H ----E ----T sort array numerically Perl sort 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C sub sort_numerically { return (sort { $a <=> $b } @_ } ; ----E ----H ----E ----T sort hash by a key Perl sort 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C foreach $key ( sort keys %Words ) { print "$key \n"; } ----E ----H ----E ----T sort on several fields Perl sort 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $sorted = sort { field1($a) <=> field1($b) || # see PerlFAQ on this field2($a) cmp field2($b) || field3($a) cmp field3($b) } @data; ----E ----H ----E ----T Code data for reading as records Perl strings 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C print DEST "$a::$b::$c\n"; # print 3 variables to a single line in a file # "::" was chosen because is unlikely to occur in real data ($a,$b,$c) = split (/::/$line) # read 3 variables form a @line in the file $a = $line[0] # same result as above (don't really need $a $b = $line[1] # same result as above (don't really need $b $c = $line[2] # same result as above (don't really need $c ----E ----H ----E ----T List of all files then separate file from path Perl strings 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C #!/usr/bin/perl -w use strict; my @all_files = `dir \\*.* /s/b`; my %filecounts; foreach my $file_and_path (@all_files) { $file_and_path =~ m/(.*)\\(.*)$/; # (Windows only) my ($path, $name) = ($1, $2); $filecounts{$name}++; } foreach my $this_file (sort keys %filecounts) { print "$this_file: $filecounts{$this_file}\n"; } ----E ----H ----E ----T remove newline character from end of string Perl strings 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C chomp $c; # removes newline character from end of string (anywhere in the string) ----E ----H ----E ----T return last 5 characters in a string Perl strings 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $a = substr ($b, -5) ; ----E ----H ----E ----T trim a string #2 Perl strings 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $string =~ s/^\s+//; $string =~ s/\s+$//; ----E ----H ----E ----T swap two variables Perl syntax 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C ($a, $b) = ($b, $a) ----E ----H ----E ----T CGI script to display all environmental variables Perl system info 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C foreach $key (sort keys(%ENV)) { print "$key=$ENV{$key}

    "; } Environmental Variables are contained in %ENV, an associate array: CONTENT_LENGTH Length in bytes of the input stream CONTENT_TYPE Content type of the data passed with the query DATE_LOCAL Current local data and time LAST_MODIFIED Date and time of the last modification of the current document DOCUMENT_ROOT Directory over which all www document paths are resolved by the server HTTP_REFERER URL that referred the web client to the script HTTP_USER_AGENT Name/version of the client (browser) issuing the request to the script PATH_INFO The extra path information following the script's path in the URL PATH_TRANSLATED The PATH_INFO mapped onto DOCUMENT_ROOT QUERY_STRING Query information, following a question mark after the script location REMOVE_ADDR IP address from which the client is issuing the request REMOTE_HOST Name of the host form which the client issues the request REQUEST_METHOD GET, POST, or HEAD SCRIPT_NAME The virtual path from which the script is executed SERVER_NAME The web server's hostname or IP address SERVER_PORT The web server's listening port SERVER_SOFTWARE Name/version of the information server software answering the request ----E ----H ----E ----T Count the number of lines in a file Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $lines = 0; open(FILE, $filename) or die "Can't open `$filename': $!"; while (sysread FILE, $buffer, 4096) { $lines += ($buffer =~ tr/\n//); } close (FILE); ----E ----H ----E ----T Delete last line of a file Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open (FH, "+< $file"); while ( ) { $addr = tell(FH) unless eof(FH) } truncate(FH, $addr); ----E ----H ----E ----T read a file and write it to a second file #2 Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open(SOURCE, "test.txt") # use single quotes if a backslash for the pathname open(DEST, "test2.txt") # use single quotes if a backslash for the pathname print DEST ; close (DEST) close (SOURCE) ----E ----H ----E ----T read a random line from a file Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C srand; rand($.) < 1 && ($line = $_) while <>; ----E ----H ----E ----T read a text file into a scalar Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $var = 'cat $file' # where $file is the file name ----E ----H ----E ----T read a text file into an array then print it Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open (FFF, "file.txt"); @all = ; print @all ; # print "@all\n"; joins elements of @all with a space close (FFF) ----E ----H ----E ----T read a text file one line at a time Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C open (SOURCE, "file.txt"); while $line (SOURCE) { ($a,$b,$c) = split (/::/$line) # read 3 variables form a line in the file } close (SOURCE) ----E ----H ----E ----T select a random line from a file Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C srand; rand($.) < 1 && ($line = $_) while <>; ----E ----H ----E ----T selectively save part of file Perl text file 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C $old = $file; $new = "$file.tmp.$$"; $bak = "$file.orig"; open(OLD, "< $old") or die "can't open $old: $!"; open(NEW, "> $new") or die "can't open $new: $!"; # Correct typos, preserving case while () { s/\b(p)earl\b/${1}erl/i; (print NEW $_) or die "can't write to $new: $!"; } close(OLD) or die "can't close $old: $!"; close(NEW) or die "can't close $new: $!"; rename($old, $bak) or die "can't rename $old to $bak: $!"; rename($new, $old) or die "can't rename $new to $old: $!"; ----E ----H ----E ----T print current time Perl time 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C ($sec, $min, $hour, $mday, $mon, $year_off, $wday, $yday, $isdat) = localtime print $sec , " seconds (0-59)\n" ; print $min , " minutes (0-59)\n" ; print $hour , " hour (0-23)\n" ; print $mday , " day of the month (1-31)\n" ; print $mon , " month of the year (1-12)\n" ; print $year_off , " number of years since 1900\n" ; print $wday , " day of the week (0-6)\n" ; print $yday , " day of the year (0-365)\n" ; print $isdat , " True if Daylight Savings Time is in effect\n" ; ----E ----H ----E ----T time handling Perl time 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C localtime # function that returns local time @timeinfo = localtime # puts 9 entries into array @timeinfo ($sec, $min, $hour, $mday, $mon, $year_off, $wday, $yday, $isdat) = localtime ----E ----H ----E ----T - Tutorial 01 - Overview PHP _tutorials 2005-02-17 22:17:27 ----O 0 0 0 ----E ----D ----E ----C PHP stands for "PHP: Howmany Processors" PHP is a server-side scripting language. The code is embedded in an HTML file. The server extracts the PHP code and runs the script (at the server). The PHP code is run as it is found - before any following HTML code is executed. ----E ----H ----E ----T - Tutorial 02 - Basic Code (Hello World) PHP _tutorials 2005-02-17 22:17:27 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T - Tutorial 03 - Syntax PHP _tutorials 2005-02-17 22:17:27 ----O 0 0 0 ----E ----D ----E ----C In PHP, a variable does not require formal declaration. It will automatically be declared when a value is assigned to it. Variables are prefixed by a dollar sign: ($VariableName). Variables are prefixed by a dollar sign Variables do not have declared types. A variable's type does not have to be fixed, meaning it can be changed over the variable's lifetime. The table below list's PHP's variable types ----E ----H ----E ----T Snippet 14 PL1 _tutorials 2005-02-17 22:17:31 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T - Tutorial 01 - Overview SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C SQL - Structured Query Language Standard language between most databse applications (although Microsoft has added it's own proprietary statements) In general, SQL is a way to select certain records from database tables, using criteria you choose. SQL consists of creating a query - a string - that the database server interprets With SQL you can: -Modify a database's structure (create tables) -Change system security settings -Add user permissions on databases or tables -Query a database for information -Update the contents of a database (add/delete data) -Store your queries within your program or database. A database server application receives the query and returns information (usually databse records according to the instructions in the query Example of SQL query (string): SELECT * FROM employee * means all records employee is the table of employees Commonly available applications which support SQL include: Microsoft Access, Oracle, Microsoft Query ----E ----H ----E ----T - Tutorial 02 - Syntax SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C An SQL query is not case sensitive Most used keywords: SELECT FROM WHERE Keywords: SELECT, FROM, WHERE Clause: SELECT column1, column2 Statement complete SQL query Common keyword usage: UNION returns the results of two queries minus the duplicate rows INTERSECT returns only the rows found by both queries MINUS returns the rows from the first query that were not present in the second JOIN returns results of both queries AND, OR IN shorthand function BETWEEN shorthand function Operators supported: = != < > >= <= * - + \ % (or MOD) ----E ----H ----E ----T - Tutorial 03 - Sample Queries SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C SELECT * FROM customers SELECT firstname, lastname, age FROM customers SELECT * FROM customers WHERE name LIKE "%David%" SELECT item, price, price*1.07 (Sale Price) FROM inventory SELECT * FROM customers WHERE name LIKE "David%" SELECT name FROM customers WHERE state="TX" OR state="CA" SELECT * FROM friends WHERE areacode IN(100,381,204) SELECT * FROM friends WHERE areacode BETWEEN (100,200) ----E ----H ----E ----T - Tutorial 04 - Functions - Aggregate SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C COUNT: returns the number of rows that satisfy the condition in the WHERE clause. SUM: returns the sum of all values in a column AVG: computes the average of a column MAX: returns the largest value in a column, use MAX MIN: returns the lowest member of a column VARIANCE: returns the square of the standard deviation STDDEV: returns the standard deviation of a column of numbers ----E ----H ----E ----T - Tutorial 05 - Functions - Date and Time SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C ADD_MONTHS: adds a number of months to a specified date LAST_DAY: returns the last day of a specified month MONTHS_BETWEEN: how many months fall between month x and month y NEW_TIME: adjust the time according to the time zone you are in NEXT_DAY finds the name of the first day of the week that is equal to or later than another specified date SYSDATE returns the system time and date: ----E ----H ----E ----T - Tutorial 06 - Functions - Arithmetic SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C ABS: returns the absolute value of a number CEIL: returns the smallest integer greater than or equal to its argument FLOOR: returns the largest integer equal to or less than its argument COS, COSH, SIN, SINH, TAN, and TANH: returns the appropriate trigonometric value. argument is in radians EXP: raise e to a power LN: returns the logarithm to base e of the argument LOG: returns the logarithm to base 10 of the argument MOD: returns remainder of a division POWER: raise one number to the power of another SIGN: returns -1 if its argument is less than 0, 0 if its argument is equal to 0, and 1 if its argument is greater than 0 SQRT: returns the square root of an argument (cannot use SQRT on negative numbers) ----E ----H ----E ----T - Tutorial 07 - Functions - Character SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C CHR: returns the character equivalent of the number it uses as an argument CONCAT: splices two strings together INITCAP: capitalizes the first letter of a word and makes all other characters lowercase. LOWER: changes all the characters to lower case UPPER: changes all the characters to upper case LPAD: pads the left side of a string with a specified character RPAD: pads the right side of a string with a specified character LTRIM: removes all spaces on the left side of a string RTRIM: removes all spaces on the right side of a string REPLACE: replaces all occurences of a string with a specified string SUBSTR: returns a specified length from within a given string TRANSLATE" s three arguments: the target string, the FROM string, and the TO string. Elements of the target string that occur in the FROM string are translated to the corresponding element in the TO string INSTR: determines where a string is found within another LENGTH: returns the length of its lone character argument ----E ----H ----E ----T - Tutorial 08 - Functions - Conversions SQL _tutorials 2005-02-17 22:17:36 ----O 0 0 0 ----E ----D ----E ----C TO_CHAR: convert a number into a character TO_NUMBER: converts a string into a number GREATEST: finds the largest number from a series of expressions LEAST: finds the smallest number from a series of expressions ----E ----H ----E ----T AND SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C use of AND OR SELECT name FROM customers WHERE state="TX" AND name="Beene" SELECT name FROM customers WHERE state="TX" OR state="CA" SELECT name FROM customers WHERE state="TX" OR state="CA" ----E ----H ----E ----T BETWEEN SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C shorthand notation: SELECT * FROM friends WHERE areacode BETWEEN (100,200) ----E ----H ----E ----T Concatenation SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C the || (double pipe) concatenates two string: note that some applications use the plus (+) sign to concatenate strings: SELECT firstname || lastname (EntireName), phone FROM customers or SELECT firstname || "," || lastname (EntireName), phone FROM customers ----E ----H ----E ----T Create a column on the fly SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C create a column on the fly: SELECT item, price, price*1.07 FROM inventory ----E ----H ----E ----T Create a column on the fly and rename it SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C SELECT item, price, price*1.07 (Sale Price) FROM inventory ----E ----H ----E ----T IN SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C shorthand notation: SELECT * FROM friends WHERE areacode IN(100,381,204) ----E ----H ----E ----T INTERSECT SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C use of INTERSECT - returns only the rows found by both queries SELECT name FROM customers INTERSECT SELECT name FROM friends ----E ----H ----E ----T JOIN SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C use of JOIN - SELECT name from customer JOIN SELECT name from friends ----E ----H ----E ----T Limit selection to match criteria SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C limit selection to match criteria: note that while SQL is not case senstive, data is: SELECT * FROM bikes WHERE name = "Beene" ----E ----H ----E ----T MINUS SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C use of MINUS - returns the rows from the first query that were not present in the second SELECT name from customer MINUS SELECT name from friends ----E ----H ----E ----T Pattern search SQL examples 2005-02-21 22:42:43 ----O 0 0 0 ----E ----D ----E ----C limited search criteria. note can use NOT in front of LIKE: note that LIKE is case sensitive: SELECT * FROM customers WHERE name LIKE "David%" or SELECT * FROM customers WHERE name NOT LIKE "David%" ----E ----H ----E ----T Select all fields from a table SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C SELECT * FROM customers ----E ----H ----E ----T Select multiple fields from a table SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C select multiple fields (columns) from a table: SELECT name, age FROM employee ----E ----H ----E ----T Test for absence of a field value SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C note that some applications use IS NULL instead of the following: SELECT * FROM inventory WHERE price = NULL ----E ----H ----E ----T UNION SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C use of UNION - meets 2 queries less duplicates: SELECT name FROM customers UNION SELECT name FROM friends ----E ----H ----E ----T Wildcard character SQL examples 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C underscore _ is single-character wildcard: SELECT * FROM customers WHERE state LIKE "T_" ----E ----H ----E ----T - Tutorial 01 - Overview VB.Net _tutorials 2005-02-17 22:17:40 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T - Tutorial 01 - Overview VBA _tutorials 2005-02-17 22:17:45 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T 01 Overview Visual Basic _tutorials 2005-02-28 10:18:02 ----O 0 0 0 ----E ----D ----E ----C ..Early computer languages were Command Line languages. A user wrote a program, compiled it, and ran the EXE from the Command Line (DOS prompt- C:\). If a visual interface (such as a display graph or location to type in information) was needed, the user had to write the code to manipulate every pixel on the screen that was needed to create the display. Visual Basic greatly simplified this process by providing the capability to create user interface items (windows, buttons, textboxes, etc.) easily using just a mouse. All of the code for the user interface Object was pre-written and stored in "runtime" files, which handled the details of interfacing with the Windows OS. All a user had to do was draw the button and write the code to respond to events such as a mouse click or the pressing of keys on the keyboard. VB3 was the first version to achieve popularity. VB6 has been the most popular of all and is still used by more programmers than the most recent edition - VB.net. Another key feature of VB is that it uses an event-driven model. When a VB program starts it goes through some initialization and then basically waits for an event to occur. Events are such things are mouse clicks or button presses by the user. A VB program consists primarily of the code which responds to these events. ----E ----H ----E ----T 02 Sample code visual basic _tutorials 2005-02-21 11:03:52 ----O 0 0 0 ----E ----D ----E ----C Sub Command1_click 'create a new VB program with a single window and a single button 'put the line below in the button click event . The line is executed when the button is pressed 'MsgBox Is a built-In VB function which pops up a window with the specified text MsgBox "Hello world!" End Sub ----E ----H ----E ----T 03 IDE Visual Basic _tutorials 2005-02-21 08:47:57 ----O 0 0 0 ----E ----D ----E ----C ..VB comes with a graphical inteface for entering and executing code (some languages still use the command line). The interface is called the Integrated Developement Environment (IDE) The IDE and compiler are integrated. The basic function of the IDE is to provide a text editor for writing your code. The second basic function of the IDE is to allow you to run your program immediately (simply press F5), without first having to compile your program. The third primary function of the IDE is to allow your to compile your program. VB's IDE allows you to open one or more projects or to combine projects into groups. The IDE also manages the addition/deletion of forms, modules and class files to your projects. The IDE provides some other very key features: 1. code editor with syntax highlighting 2. Intellisense (displays possible options to finishing a line of code) 3. programs can be executed immediately from the IDE 4. programs can be compiled to create an EXE for later execution 5. debug features, including step-by-step execution of a program 6 expression watches, where you can pause when specified conditions are met ----E ----H ----E ----T 04 Syntax Visual Basic _tutorials 2005-02-21 08:48:40 ----O 0 0 0 ----E ----D ----E ----C 'VB code is written one line at a time, A line of code is called a statement. (Not all languages 'recognize the end of a line as the end of a statement). MyString = "hello" 'There are two variations on the rule of one line per statement: '1. The underline character can be used to allow a long line of code to span multiple physical lines (simply a visual aide) MyString = "the boys are about" & _ "where we want them" '2. A colon can be used to put two or more statements on a single line MyString = "hello" : YourString = "goodbye" 'VB allows the placement of comments in a line - comments are descriptive text which 'will be ignored during execution of the program. Comments are usually shown in 'the IDE as green-colored text. There are two ways to comment code: '1. start the line with 'REM' REM this is a comment line '2. all code to the right of an apostrophe is treated as a comment My String = "hello" 'comments go here ----E ----H ----E ----T 05 Data types / variables Visual Basic _tutorials 2005-02-21 09:02:01 ----O 0 0 0 ----E ----D ----E ----C VB, like most programming languages, stores information in multiple formats. The basic data types supported by VB are: 'Integer whole numbers -32,768 to +32,767 2 bytes 'Long whole numbers -2,147,483,648 to +2,147,483,647 4 bytes 'Single numbers with decimal points -1.4E-45 to +3.4E38 4 bytes 'Double numbers with decimal points -4.9E-324 to 1.8E308 8 bytes 'Boolean value of True or False only 'Strings sequences of characters, such as "abc123" 'Byte single character 0 to 255 'Date includes date and time 'Variant any type from the list above 'Variables are names assigned to store values. Variable naming rules are: '1. Start with a letter '2. Consist of letter, numbers, or an underscore '_' '3. Cannot exceed 255 characters 'To create a variable of a certain type, use the Dim function Dim MyString as String MySring = "abc" Dim Y as Integer Y = 2 'VB also supports a user-defined type (UDT), which is a combination 'of the other types Type Address Address as String City as String State as String Zip as String End Type Dim R as Address R.Address = "101 Clover Lange" R.City = "Tulsa" R.State = "OK" R.Zip = "72310" 'These VB function are available to convert 1 data type into another CBool(expression) CByte(expression) CCur(expression) CDate(expression) CDbl(expression) CDec(expression) CInt(expression) CLng(expression) CSng(expression) CStr(expression) CVar(expression) ----E ----H ----E ----T 06 Operators Visual Basic _tutorials 2005-02-21 10:20:31 ----O 0 0 0 ----E ----D ----E ----C 'VB supports the following operators 'Arithmetic + addition for numbers - substraction / division \ integer division, discards the decimal part of the answer * multiply ^ exponentiation Mod division, returning only the remainder 'Comparison = equal < less than > greater than <> not equal >= greater than or equal to <= less than or equal to Is two variables/objects are the same Like variable matches a pattern 'Concatenation & combines two strings into one + combines two strings into one (is addition for numbers) 'Logical And logical conjunction (both values True) Or logical disjunction (either value True) Not logical negation (reverses True/False value) Xor logical exclusion (True if one, and only one, is True) Imp logical implication (e9e9 Eqv logical equivalence (True if both have same logical value) ----E ----H ----E ----T 07 Boolean logic Visual Basic _tutorials 2005-02-21 10:20:51 ----O 0 0 0 ----E ----D ----E ----C 'Boolean refers to logical relationships - True or False, and is named 'after mathematician George Boole. 'VB supports the following Boolean opertors Or And Not Xor 'The following operators are also supported but see very little use by VB programmers Eqv Imp Is 'To create a Boolean variable, use this: Dim X As Boolean 'Mathematical values used in Boolean expresssion are converted to Boolean values as follows: 0 becomes False all other values become True. 'Boolean values used in mathematical expressions are converted to mathematical values as follows: False becomes 0 i.e. False * 2 = 0 True becomes -1 i.e. True * 5 = -5 'results of applying Val to Boolean Val(True) = 0 Val(False) = 0 Abs(True) = 1 Abs(False) = 0 CInt(True) = -1 CInt(False) = 0 Print True ---> True Print False ---> False If A Then '0 value is treated as False 'non-zero value is treated as True End If ----E ----H ----E ----T 08 Strings Visual Basic _tutorials 2005-02-21 09:16:57 ----O 0 0 0 ----E ----D ----E ----C ' "abc" is a String consisting of the three letters a, b, and c 'a string variable is assigned content as follows: mystring = "abc" 'two strings can be merged with the & operator mystring = "abc" & "def" = "abcdef" 'VB has really wide range of functions that perform string operations Left 'returns # of characters at left of string Right 'returns # of characters at right of string Trim 'removes spaces from both ends of a string LTrim 'removes spaces from left side of a string RTrim 'removes spaced from right side of a string UCase 'make entire string upper case LCase 'makes entire string lower case Mid 'returns any or all of a string (substring) Chr 'returns string character associated with an integer (see Ascii values) Asc 'returns Ascii integer value of a single character Len 'retruns the length of a string (number of characters in the string) LSet 'left justifies a string in a string of specified width, padding with spaces as needed RSet 'right justifies a string in a string of specified width, padding with spaces as needed String 'retuns a string consisting of a character, repeated a specified number of times Space 'returns a specified number of spaces InStr 'finds position of one string inside a larger string (position defined as starting from the left of the string) InStrRev 'finds position of one string inside a larger string (position defined as starting from the right of the string) Like 'compares two string and returns a Boolean result Replace 'replaces a part of a string with a specified replacement string Join 'joins the elements of an array into a single string, separated by a specified delimeter Split 'separates a string into an array. separation is made at a specified delimeter StrComp 'compares two strings for equality - with various options StrReverse 'reverse the order of characters in a string StrConv 'converts a string to various formats (upper, lower, proper, ...) Format 'formats an expression to a user-define format. format is defined by a string FormatCurrency 'formats a number as currency FormatDateTime 'formats an expression as date and time FormatNumber 'formats a number with various options FormatPerCent 'formats a number as a percent ----E ----H ----E ----T 09 Arrays Visual Basic _tutorials 2005-02-21 11:31:10 ----O 0 0 0 ----E ----D ----E ----C 'Arrays are variables which hold multiple values. Each of the values is indexed. 'Declare an array with Dim 'Arrays default to a lower bound of zero but the user must specify the upper bound Dim MyArray(5) as Long '6 elements, 0-6 'Users can define the upper/lower bounds Dim MyArray(1 to 15) Dim MyArray(-10 to 10) 'Arrays can have multiple dimensions Dim MyArray(5,5) Dim MyArray(1 to 10, 1 to 50) 'Arrays whose dimensions are set with Dim are fixed-size arrays. The dimensions 'cannot be changed. 'Arrays whose dimensions can be changed are called dynamic arrays. 'They are declared with ReDim and later dimensioned again, as often as needed ReDim MyArray() 'dynamic array 'then later in code: ReDim MyArray(15) 'the dimensions can be changed at any time to any value 'ReDim loses values in the array unless Preserve is used ReDim Preserve MyArray(15) 'Control arrays Variables can contain objects, such as textboxes or pictureboxes, and VB supports arrays of objects as well. ----E ----H ----E ----T 10 Flow control Visual Basic _tutorials 2005-02-21 11:03:47 ----O 0 0 0 ----E ----D ----E ----C 'VB offers 6 basic methods of flow control 1. For ... Next 2. If ... Then 3. Select Case ... End Select 4. While ... Wend 5. Do ... Loop 6. GoTo 'For ... Next ================================= For i = 1 To j Step k ... Next i 'Example For i = 1 To 10 Print i Next i 'If ... Then ================================= If (expression) Then ... ElseIf (expression) ... Else ... End If 'Example If j > 6 Then Print "big" ElseIf i <> 32 Print "hello" Else Print "none of the above End If 'Select Case ... End Select ================================= Select Case (expression) Case (variable list) Case (variable list) Case Else End Select 'While ... Wend ================================= While (expression) ... Wend 'Do ... Loop ================================= Do While | Until (expression) ... Loop While | Until (expression) For Each (variable) In (Collection) Next 'Example Do While j < 10 j = j + 1 Print J Loop 'Example Do j = j + 1 Print J Loop Until j = 25 'GoTo ================================= GoTo Line 'Example GoTo Start 'skips the next two lines j = j + 1 Print j Start: Print j ----E ----H ----E ----T 11 Variable scope and lifetime Visual Basic _tutorials 2005-02-21 09:40:48 ----O 0 0 0 ----E ----D ----E ----C 'Scope ------------------------------------------------------------------------------- 'The scope of a variable defines which parts of your program are aware of 'the variable. When you declare a variable within a procedure (sub/function) 'only code within that procedure can access or change the value of that variable. 'The variable's scope is local to the procedure. 'Scope of a variable can be controlled by the programmer. Variables are 'declared in one of two locations - procedures or modules. In each case, 'VB allows the declaration to define the procedure as Private or Public: 'Procedure-level variables Private 'variables are private to the procedure Public 'n/a. procedure variables cannot be Public 'Module-level variables Private 'variables are private to the module 'they can be accessed from within any procedure in the module Public 'variables are available to all modules 'Example: to make a public variable, put this in the declaration section of a module 'Note: Public replaces Dim in the declaration Public MyVar as Long 'Example: to make the same variable private to the module, use this: Private MyVar as Long 'Lifetime ------------------------------------------------------------------------------- 'Normally, when a variable is declared in a procedure (sub/function) it exists only as long 'as the procedure is executing. For example: Sub MySub () Dim j as Long j = 5 End Sub 'When the program call MySub, the variable j is created. When the program exits 'MySub the variable i no longer exists. 'The exception is that if the declaration uses the keyword Static, the variable continues 'to exist between calls of the procedure: Sub MySub() Static Dim j as Long i = j + 5 End Sub 'In this example, the value of j is kept. Each time the procedure is called, j is incremented 'by an additional 5. 'These comments apply to module variables also ----E ----H ----E ----T 12 Functions / subroutines Visual Basic _tutorials 2005-02-21 09:17:17 ----O 0 0 0 ----E ----D ----E ----C 'VB supports two kinds of functions - Subroutines and Functions 'Both allow passing variables to the Sub/Function for use 'Subroutines execute code and return control of program to calling point Sub MySub () Print "Hello" End Sub 'Functions execute code, return a value to the program and return control of program to calling point Function MyFunction () As String MyFunction = Date End Function 'usage MyString = MyFunction 'Date is placed in MyString 'Passing variables - Sub declaration defines data type of passed variable Sub MySub (i As Long, s As String, a() As Variant) Print i Print s Print a(5) End Sub 'Passing variables - Sub declaration defines how passed variables are treated 'ByVal cannot alter the passed variable 'ByRef can alter the passed variable Sub MySub (ByVal i As Long, ByRef s As String) i = 5 'the original variable passed has not changed - ByVal s = 10 'the original variable passed is now changed - ByRef End Sub ----E ----H ----E ----T 13 Files / Folders Visual Basic _tutorials 2005-02-21 09:17:21 ----O 0 0 0 ----E ----D ----E ----C 'Files =========================== 'VB can access files as text or as binary data ' generally text files are separated into lines - string data followed by a pair of LF+CR characters ' binary files have no such LF+CR separator 'basic functions Name rename a file Kill delete a file FileCopy copy a file To a New location FileLen Get length of a file In bytes FileDateTime Get Date/Time file was last modified GetAttr Get readonly/system/hidden/directory/archive attribute of a file Or folder SetAttr Sets readonly/system/hidden/archive attribute of a file Or folder 'Open - most important VB function for reading and writing files ' files can be opened in 4 modes - append, binary, input, output, random 'Input - error if file does not exist Open "myfile.txt" For Input As #1 Line Input #1, temp 'read a line of text at a time Input #1, a,b,c 'reads list of variables Close #1 'Example of reading text file from start to end Open "myfile.txt" For Inpu As #1 While Not EOF(1) Line Input #1, temp Wend 'output - creates file if it does not exist. erases the file before creating it. Open "myfile.txt" For Output As #1 Print #1, "information" 'prints data into file. auto-inserts LF+CR Write #1, "dog", "cat" 'prints data into file. quotes around strings, commas between items. auto-inserts LF+CR Close #1 'binary - Open "myfile.txt" For Binary As #1 Get #1, 32, i Close #1 'append - text mode. write only. writing starts at end of file Open "myfile.txt" For Append As #1 Put #1, 128, j Close #1 'random - reads fixed lenght data, but may be text or binary Open "myfile.txt" For Append As #1 Get #1, 32, MyUDT 'reads the 32nd fixed-length record Close #1 'Folders======================== 'basic functions ChDir Change directory MkDir Make directory RmDir Remove directory ChDrive Change drive CurDir Return current directory ----E ----H ----E ----T 14 System functions Visual Basic _tutorials 2005-02-21 09:17:24 ----O 0 0 0 ----E ----D ----E ----C 'This tutorial covers the Windows Registry and Environment variables 'Registry -VB can access registry information at: 'HKEY_CURRENT_USER\Software\VB and VBA Program Settings\appname\section\key\value 'A registry entry includes a reference to the program, a section, a key, and a value. Windows supports values of String, Binary, or DWORD type, but VB only supports String key values. VB Registry functions are: GetSetting 'gets a value from a section\key SaveSetting 'saves a value in the registry for a section\key DeleteSetting 'deletes a section or key GetAllSettings 'returns all key/values pairs from an application\setting of the Registry 'The Registry is a database of most Windows settings, as well as those for your installed applications. 'In Windows 95, 98, and Me, the Registry is contained in two hidden files in your 'Windows directory, called USER.DAT and SYSTEM.DAT. 'In Windows 2000 and Windows XP, the Registry is stored in several Hives (special files), located 'in the \windows\system32\config and \Documents and Settings\{username} folders. 'Windows 2000 and WIndows XP have five main branches: '- HKEY_CLASSES_ROOT - contains all of file types as well as OLE information for OLE-aware applications. '- HKEY_CURRENT_USER - points to the part of HKEY_USERS appropriate for the current user. '- HKEY_LOCAL_MACHINE - information about all of the hardware and software installed on your '- HKEY_USERS - preferences (such as colors and control panel settings) for each of the users of the computer. '- HKEY_CURRENT_CONFIG - the part of HKEY_LOCAL_MACHINE appropriate for the current hardware configuration. 'Registry Editor 'Windows includes a program called the Registry Editor (regedit.exe) which allows 'you to view and edit the contents of the Registry. 'Registry Patch 'A Registry patch is a simple text file with the .REG extension that contains one or more keys 'or values. If you double-click on a .REG file, the patch is applied to the registry. You can 'create a Registry patch by opening the Registry Editor, selecting a branch, and choosing 'Export from the File menu. ============================================================================ 'Environment variables MyString = Environ("PATH") 'returns the Windows Path spec 'Environment variables are strings that contain information such as 'drive, path, or file name. They control the behavior of various programs. 'For example, the TEMP environment variable specifies the location in 'which programs place temporary files. The PATH environment variable 'determines the path(s) where Windows will look for executable files. ----E ----H ----E ----T 15 Graphics Visual Basic _tutorials 2005-02-21 09:17:28 ----O 0 0 0 ----E ----D ----E ----C 'VB has limited graphics capabilities. Most serious graphics work is done using Windows API 'Coordinate system 'Graphical controls (cannot appear on top of other controls, cannot receive focus, cannot 'serve as containers and do no have an hWnd property): 'Image 'Line 'Shape 'Pictures can be displayed on: 'form 'picturebox 'image control 'Graphics methods .Cls 'clear a drawing area .PSet 'sets color of a pixel at a specified point .Point 'returns color value at a specified point .Line 'draws line between two coordinates (also draws box) .Circle 'draw circle of radius about a specified point (can also draw arcs or ellipses) .PaintPicture 'draws a picture on a form, picturebox, or printer 'These properties affect the way graphics methods appear: .FillStyle .FillColor .DrawWidth 'width of lines .BorderWidth 'width of outline on line and shape controls .DrawStyle 'set solid or broken pattern for lines .DrawMode 'defines what happend when one pattern is drawn on top of another 'Colors 'color is a Long integer from 0 to 16,777,215 (&HFFFFFF&) 'color is represented by red, green and blue content - each with a value of 0 to 255 'RGB function is used to set colors using RGB content iColor = RGB (R, G, B) 'R,G,B have values 0 to 255. (0,0,0) is black. (255,255,255) is white. iColor = QBColor (i) 'i = 0 to 15, corresponding to VB color constants 'represent color by this syntax (Note: this is reversed from standard Internet color syntax): iColor = &HBBGGRR& 'where BB is blue, GG is green, and RR is red content 'Non-displayed pictures 'VB offers a Picture object for loading pictures which do not need to be displayed 'The Picture object is convenient for creating animation sequences by using an array of Picture objects Dim MyPicture as Picture Set MyPicture = LoadPicture("mypicture.bmp") ----E ----H ----E ----T 16 Sound Visual Basic _tutorials 2005-02-21 09:17:35 ----O 0 0 0 ----E ----D ----E ----C 'VB has only 1 intrinsic support of sound - the Beep function Beep 'emits a short mid-frequency sound 'The frequency and duration of the beep depend on your hardware 'and system software, and vary among computers. 'To employ sound in a VB application the Windows API are used ----E ----H ----E ----T 17 Date-Time Visual Basic _tutorials 2005-02-21 09:17:38 ----O 0 0 0 ----E ----D ----E ----C 'VB supports a Date data type Dim D1 as Date, D2 as Date NumberDays = D2 - D1 'subtracting dates gives days (Single data type) 'Functions iResults = Second(DateVar) 'returns 1-59 iResults = Minute(DateVar) 'returns 1-59 iResults = Hour(DateVar) 'returns 1-23 iResults = Day(DateVar) 'returns 1-31 iResults = Month(DateVar) 'returns 1-12 iResults = Weekday(DateVar) 'returns 1-7 iResults = Year(DateVar) 'returns 4 digit year 'Set time/date Time = TimeString Date = DateString 'Get time/date DateVar = Date TimeVar = Time 'Time Operations DateAdd DateDiff DatePart 'Time Functions DateSerial DateValue TimeSerial TimeValue ----E ----H ----E ----T 18 Math Visual Basic _tutorials 2005-02-21 09:17:41 ----O 0 0 0 ----E ----D ----E ----C 'VB normally operates in decimal notation, but hexadecimal (base 16) 'and octal (base 8) can also be use 'decimal MyVar = 25.2 'hexidecimal MyVar = &H14A 'octal MyVar = &O37 'VB support the following mathematical functions 'Base conversions Hex 'returns Hex string representation of a number Oct 'returns Octal string representation of a number Val 'returns content of string converted to a number 'Controlling number of decimals in a number Round Int 'returns integer portion of a number. if negative, returns first negative integet <+ to the number Fix 'returns integer portion of a number. if negative, returns first nteger greater than or equal to number 'Mathematical formula Sin 'sine Cos 'cosine Tan 'tangent Sqr 'square root Abs 'absolute value Atn 'arctangent Log 'logarithm to the base 10 'related random variables Rnd 'random number between 0 and 1 Randomize 'seeds the Rnd function so that it doesn't return the same value each time a program runs Sgn 'sign of a number 1 for > 0, 0 for 0, -1 for < 0 Partition 'returns a string indicating where a number occurs within a calculated series of ranges 'These functions are available to convert one data type to another ----E ----H ----E ----T 19 Printing Visual Basic _tutorials 2005-02-21 09:17:45 ----O 0 0 0 ----E ----D ----E ----C 'VB allows printing to 3 objects within a program '1. Printer '2. Picture controls '3. Forms Printer.print "hello" picture1.print "hello" form1.print "hello" 'printer/picture/forms support key properties which affect where the printing 'takes place and how it look .CurrentX 'starting X position .CurrentY 'starting Y position .ScaleMode 'values are twips, points, pixels, inches, cm, mm, character .ScaleLeft 'coordinate at left of object .ScaleTop 'coordinate at top of object .ScaleWidth 'width of object .ScaleHeight 'height of object 'Printing starts at x,y coordinates 0,0, or whereever set with .CurrentX and .CurrentY properties Printer.CurrentX = 1000 Printer.CurrentY = 3000 'Exact set of properties available depends on the printer driver supplied by the printer manufacturer 'To end printing on a page and start a new page use (does not apply to forms/pictures) Printer.NewPage 'To end printing on a document and eject the page use (does not apply to forms/pictures) 'VB automatically calls this when a program ends, if there is content in the print buffer Printer.EndDoc 'VB supples a special method to print the entire content of a form form1.printform 'When within the IDE, printing can also be in these two locations, but with no positioning control 'Debug window 'Immediate window ----E ----H ----E ----T 20 Error handling Visual Basic _tutorials 2005-02-21 09:17:49 ----O 0 0 0 ----E ----D ----E ----C 'Uncaught errors will halt execuation of VB code (crash) 'To catch (handle) and error use on of these code techniques 'When an error occurs, VB sets the err object, which has these properties 'these are reset after Exit Sub, Exit Function, Exit Property or Resume Next statements .Clear 'clears the err object .Description 'text description of the error .HelpContext 'context ID for a topic in a Help file. Read/write. .HelpFile 'full path name of Help file .LastDllError 'return value of last DLL call where an error was returned .Number 'number assigned to this error (default property) .Raise 'use in run-time to generate an error for testing error-handling code .Source 'name of object that generated the error 'Enable error trapping this way: On Error GoTo Label ... normal code goes here Label: 'this is where execution branches to when an error occurs ....error-handling code goes here 'To get out of an error-handling routine, use one of these Resume[0] 'repeats the error-causing statement (use when the cause of error has been corrected) Resume Next 'resumes at the statement immediately following the one that caused the error Resume line 'resumes at the specified label (must be in same procedure as the error handler) 'Generally, use Resume[0] when the error gets corrected and Resume Next when it does not 'To disable error trapping use this line of code: On Error Goto 0 'The VB IDE has special tools for debugging/controlling errors 'Breakpoints lines of code there the IDE pauses execution 'Step Into execute next line of code, including when the next line is in a procedure 'StepOver execute next line of code, without stepping into a procedure 'StepOut executes the current procedure and stops at the next line in the calling procedure 'Locals Windows displays the current value of local variables 'Immediate Window run code while application is in break mode 'Watch Window displays value of selected expressions 'Quick Watch list current value of expression while application is in break mode 'Call Stack in break mode, lists all procedures that have been called but not yet run to completion ----E ----H ----E ----T 21 Controls Visual Basic _tutorials 2005-02-21 12:12:12 ----O 0 0 0 ----E ----D ----E ----C ..As part of its graphical interface, VB allows the programmer to build simple interface objects, such as textboxes, buttons and checklists by simply drawing them with a mouse. The objects are called controls. VB comes with 20 built-in (intrinsic) controls. These 20 are part of the VB run-time files. 01 ADO Data Control acts as interface between database and other databound controls 02 Checkbox status is checked or not checked 03 ComboBox combination of a textbox and a listbox 04 Command Button press a button to execute a block of code 05 DirListBox DirList/DriveList/FileList work together to naviate folder structure of Windows 06 DriveListBox DirList/DriveList/FileList work together to naviate folder structure of Windows 07 FileListBox DirList/DriveList/FileList work together to naviate folder structure of Windows 08 Frame Container for holding other controls 09 Horizontal Scroll Bar slider for adjusting values 10 Image displays a picture 11 Label displays text, edit in code only 12 Line simple graphics control to display a line of various formats 13 ListBox vertical list of text strings, each accessible by code 14 OLE Container can use to add objects from other applications, such as an Excel worksheet 15 Option Button only 1 of a group may be selected at a time 16 Picturebox displays a picture, text/graphics can be drawn on it, 17 Shape simple graphics control to display basic shapes (square, circle) 18 Textbox basic text entry, can be multiline, text can be highlighted 19 Timer creates an event over a user-defined interval 20 Vertical Scroll Bar slider for adjusting values ----E ----H ----E ----T 22 Objects Visual Basic _tutorials 2005-02-21 11:55:50 ----O 0 0 0 ----E ----D ----E ----C 'Objects are a combination of code and data which you can treat as a single item. 'The controls VB allows you to draw on a form are objects, are as the forms themselves. 'Properties, Methods, and Events 'All objects share a common way of accessing the data and code that we've said make up an object. 'The data inside an object is known as the properties of the object. In familiar terms, it corresponds 'to the values of variables which are stored inside the object. For example, all objects have names. 'The name is one of the properties of the object and the way that you access a property in code is as follows: MyString = ObjectName.Name 'All properties of objects work exactly the same way, using what is called the "dot" notation. Here are some more examples: h = Form1.height w = listbox1.fontname r = textbox.backcolor g = timer1.interval 'In each of these examples, a variable on the left is assigned the value of the property on the right. 'The format for identifying the property name is also done the same in every case - "objectname.propertyname". 'Typically, whoever creates the object "exposes" properties which you can access. In the VB IDE 'environment you can click on a control and the properties box (press F4) will display all of the property 'names along with possible values for those properties. Object properties are just like variable in that they 'can have a type. They can be integer, string, dates, or any other VB data type. So remember when 'assigning property values to variables that the VB rules for type conversion must be taken into consideration. 'When in the IDE code windows, VB also provides a big help in remembering the properties of an object. 'Once you've typed in the object name and the ".", VB will display a dropdown listbox which give all of the 'available properties. This features is called Intellisense. 'Two other nuances about properties will be of interest. First of all, not all properties of an object 'are "exposed" for use in your VB program. When we get around to creating our own objects in 'code, you'll find that you can choose whether to expose a property for use in code, or whether 'to keep it hidden within the object (so as not to allow its value to get changed). 'COM & Exposed Objects 'One of the key features about objects is that they can be made available outside of an application for 'use by other programmers. Making an object available for use is known as "exposing" the object. 'Many of the major applications such as Word or Excel expose objects for your use. Microsoft has 'established a standard known as COM (Common Object Model) which guides programmers through 'the techniques of exposing objects from within their applications. 'Exposed objects cannot, however, be distributed with your application. If you plan to create an 'application which uses exposed objects from a second application, then your user must have 'that second application installed on his PC. This is not a trivial problem. Unless you have some 'control over the user's environment you'll find it best to distribute stand-alone applications - ones 'which do not assume that any particular software is resident on your user's PCs. 'All controls, whether in the form of ActiveX Controls (.OCX files) or in the form of exposed objects, 'must be registered with Windows (as part of the Registry) before your VB program can use the 'object. In the VB IDE you can call up the Components Dialog Box which will list all of the objects '(ActiveX files or exposed objects) thtat are available for your use. If you select one of the objects 'for use, the object will appear on your VB IDE toolbox and can then be used just like any of the 'intrinsic controls that you have already used. 'There is a utility called regsvr32.exe that comes with Windows which you will find very useful. 'Regsvr32 allows you to manually register an OCX in the registry. The need to do this manually 'can arise for a variety of reasons, but mostly because an installation program failed to automatically 'make the registration. The code to register an OCX file is: regsvr32 filename.ocx 'You can do this from a DOS command line or through the Start/Run menu option. 'Classes 'We're just about to get into the How of creating objects, but one more topic needs discussion 'first. Before an object can be created, an object template must first be created. Once that 'template is created a copy can be created. It's the copy with which you will work in your VB programs. 'In VB terminology, the template is called a class and the copies of the template are called 'instances. In the registration process that we just discussed, it is the template, or class, of an 'object that gets registered with Windows. 'Object Browser 'VB provides a tool with which you can browse all registered objects, including the properties 'and methods which they expose. The Object Browser window can be displayed by pressing 'F2 within the VB IDE. One advantage of the Object Browser over the properites window is 'that the browser can show both properties and methods of the registered classes. Additionally, 'the browser shows all registered objects, including the objects exposed by applications that 'you have installed on your PC. It's the poor man's documentation of all usable classes on your PC! 'Creating Objects - References, Class Modules, & Collections 'You can create objects at both design time and run time. Controls, forms, and class modules 'are examples of objects which you can create at design time (within the VB IDE). You can also 'create controls and form objects at run time, as well as creating variable objects and collections 'at run time. We'll cover these topics next in the tutorial. 'References 'It is possible use the DIM function to create a variable whose type is that of any registered 'class. To do so, use this code: Dim X as ListBox 'Variables which have been defined as an object type are useful because they can be made 'to refer to an existing object. For example, this code, when used with the line of code just given, 'associates X with the ListBox1 control. Set X = ListBox1 'Notice the use of the Set statement? To establish a variable reference to an object, you 'cannot simply use the equal sign. You must use the SET statement. 'There are several reasons why you should be interested in creating a second reference to a control. 'First of all, once the variable is set to reference the control, all of the control's properties 'and methods and be accessed as follows: X.name is the same as ListBox1.name 'If nothing else, using variables rather than the full name of the control can save you some 'typing as you write your code. ----E ----H ----E ----T 23 Database programming Visual Basic _tutorials 2005-02-22 16:24:46 ----O 0 0 0 ----E ----D ----E ----C .. With over half of all VB programs involved in database management of some kind, you have to feel obligated to understand VB's capabilities in that area. Databases can come in various formats - Access, text files, Excel files, custom binary formats. Usually, however, when one speaks of databases the reference is to information stored in the Access data format - files that end in .mdb. With VB you can create database objects using code or you can utilize one of several databbound controls which can greatly simplify your access to the contents of a database. The penalty you pay for using databases in your program is a tremendous growth in the program size - a minimum of 5MBytes for just putting a single control on your form. Also, database operations in VB can be noticeably slow. Finally, unlike a simple text database, Access database files cannot be edited directly. These penalties have to be traded off against the simplicity with which VB allows you to access/edit database content. Controls Database access in VB begins with the data control. Set the file and table properties and all you have to do is to bind fields to other controls for display or edit. Of VB's intrinsic controls, the following can be bound to the datacontrol, automatically showing one of more fields in a database table. - textbox - label As far as basic terminology goes, databases contain tables, which are collections of data arranged in rows and columns. Rows are called records and columns are called fields. Databases can also contain queries, table relationships, validation criteria and more. A Recordset is simple a group of records from a database. Usually, a recordset is thought of as a subset of all records in a tables, although as we will see, records can also be made up of data from more than one table. Records in a recordset are in no particular order unless a user takes an action to put them in an order. Also, a recordset is a temporary copy of information from the databset. Once created, or edited, it must be saved into the database to be permanent. Actually, there are 5 types of recordsets which VB can create from a database, having to do with where the data can come from, how you can navigate through the records, and whether you can edit the data in the recordset. Learning which recordset to use in a particular application requires an understanding of the capabilities and limitations of each. - Table-type Recordset Basically a complete table from a database. You can use to add, change, or delete records. - Dynaset-type Recordset The result of an SQL query that can have updatable records. You can use to add, change, or delete records. It can contain fields from one or more tables in a database. Provides worse performance than a Table-type recordset. - Snapshot-type Recordset A read-only set of records that you can use to find data or generate reports. Can contain fields from one or more tables in a database but can't be updated. Uses a minimum of resources and provides fast performance. - Forward-only-type Recordset Identical to a snapshot except that no cursor is provided. You can only scroll forward through records. This improves performance in situations where you only need to make a single pass through a recordset. - Dynamic-type Recordset A query result set from one or more base tables in which you can add, change, or delete records from a row-returning query. Further, records other users add, delete, or edit in the base tables also appear in your Recordset. While they all have their place, it's my experience that the first three are the most useful. ADO (ActiveX Data Objects) is the current technology which Microsoft offers to access databases. It was preceded by DAO and RDO. VB Data Controls The concept of a data control is pretty simple. You set the .DataBaseName property to tell the data control which database file to read. Then you set a .RecordSource property to tell it which table within the file to make available as a recordset to other controls. As I've mentioned earlier, you can also create recordsets which are combinations of one or more tables by setting the .RecordSource property to an SQL statement. Then, for data-aware controls such as a textbox, set the .DataSource property to the data control and the .DataField property to the specific field within the table/recordset that you want bound to the control. At that point the bound controls will display the information from the chosen field of the recordset. Edits made to the data can be saved by either using the data control to move to a new record or by executing the .Refresh method of the data control. There are two data controls provided by VB - Data control (intrinsic version) This is the original, intrinsic version of the control. It supports the JET database engine and can satisfy most beginners' needs. - ADO Data control (ActiveX control) This is the latest version of the data control, implemented as an ActiveX control. Data Bound Controls There are 7 intrinsic controls and 16 ActiveX controls which recognize databases. ComboBox Here are the three versions that are available with VB, and some comments on how to decide which one to use. * ComboBox This is the original, intrinsic, version of the control. Use it whenever possible to keep down the size of your application. * DataComboBox This is Microsoft's most recent rendition of a combo control. * DBCombo Left over from VB5, you can forego using this one in favor of the newer DataCombo control. List Here are the three versions that are available with VB, and some comments on how to decide which one to use. * ListBox This is the original, intrinsic, version of the control. * DataList This is Microsoft's most recent rendition of a list control. * DBList Left over from VB5, you can forego using this one in favor of the newer DataList control. Grid There are actually four versions of a grid control that come with VB, but only three of them can be databound. Here are the three versions and some comments on how to decide which one to use. * DBGrid The olders version that came with VB5. You'll have to find it on the VB CDROM because it doesn't get automatically installed. * FlexGrid Also a VB5 version of the grid control. It does not support editing of the bound data. * Heirarchical FlexGrid Newest version of the VB5 FlexGrid and still does not support editing of the bound data. Other Data-Aware Controls These intrinsic controls can also be bound to fields in a recordset: - checkbox - combobox - image control - label - listbox - picturebox - textbox These ActiveX controls are also data-aware 00 ADO Data control 01 DataComboBox 02 DataGrid 03 DataList 04 DataRepeater 05 DateTimePicker 06 DBCombo 07 DBGrid 08 DBList 09 ImageCombo 10 MaskedEdit 11 MonthView 12 MSChart 13 MSHFlexGrid 14 MSFlexGrid 16 RichTextBox ----E ----H ----E ----T 24 SQL Visual Basic _tutorials 2005-02-21 11:55:01 ----O 0 0 0 ----E ----D ----E ----C ..SQL - Structured Query Language SQL is an industry standard language for querying a database - with the purpose to either retreive data or to modify the data in the database. SQL is intended to provide a plain-English method of accessing a database and to avoid the need for custom programming. An SQL query is a text string which tells VB what to include in a recordset or what actions to take against the data in a recordset. Using SQL really does simplify the code you have to write in an application that utilizes databases. You can even write SQL queries which will modify many records in a single operation. Once I understood the basics, the use of SQL hit me like a revelation. It's easily one of the top 5 features of VB's database handling capabilities! Sample SQL Queries "Select * From Title Where [Year Published] < 1889" "Delete From Titles Where [Year Published] < #1/1/1889#" "Select Name, Picture From Authors Where Date_of_Birth = #2/1/1947#" "Select * From Employees" "Select [First Name], [Last Name] From Employees" "Select Employees, Department, SupvName From Supervisors, Employees Where Employees.Department = Supervisorts.Department" "Select Distinct [Last Name] From Employees" "Select [Last Name], Salary From Employees Where Salary > 2100" "Select * From Orders Where [Shipped Date] = #5/12/93#" "Select [Product Name], Sum ([Units in Stock]) From Products Group By [Product Name]" "Select * From Employees Order By [Last Name], Asc" "Select [Last Name], [First Name] From Employees Order by 2 Asc" "Select [Last Name], Salary From Employees Order By Salary, Desc, [Last Name] Three things to note about the examples: - "*" is used to denote all fields - Dates are enclosed by pound signs, like this: "#2/1/1947#" - Fields with multi-part names which include spaces are enclosed in brackets: [ ] To use SQL queries, set the RecordSource property of a data control to an SQL statement such as those above and refresh the control like this: Data3.RecordSource = "SELECT * FROM Agency ORDER BY [City]" Data3.Refresh Just make sure that any references to fields match those contained in the actual database. Doing so will create a recordset whose content will match the constraints described by the SQL statement. First of all, there are 5 parts to an SQL statement which you should recognize: Command Clauses Predicates Operators Aggregate Functions Create From Distinct AND Avg Drop Where Top OR Count Alter Group By NOT Sum Select Having Between Max Insert Order By Like Min Update In Delete With a little inspection you can pretty much guess what each of these pieces of an SQL statement can do. However, here are a couple which you'll not want to miss and which I use pretty regularly. Don't miss the last one in my list, which is a very easy way to sort a recordset! Select This is the most basic command which tells VB which fields to show in the recordset. Delete Simple, but very powerful means of deleting many records at one time. From Defines the Table from which the fields will be extracted. Where Precedes the conditions by which records are selected from the database Order By Sorts the records by any combination of fields you chose. ----E ----H ----E ----T 25 Limitations Visual Basic _tutorials 2005-02-21 11:47:27 ----O 0 0 0 ----E ----D ----E ----C ..VB has some specific limitations to keep in mind as code is written Variable names 255 characters Control names 40 characters Controls per form 254 names (control array counts as one name) Control array index 32,767 Nested controls 25 levels Listbox elements 32K items, 1024 bytes max per item Textbox 64K characters Code per form 65,534 lines (applies to class and standard modules as well) Code per procedure 64K lines DLL declarations per module 1500 UDT variable size 64K ----E ----H ----E ----T 26 Summary of functions Visual Basic _tutorials 2005-02-21 11:26:11 ----O 0 0 0 ----E ----D ----E ----C 'Functions available within VB can be broadly broken into the following categories: 'Strings Files Folders Declarations 'Date/Time Registry Misc Arrays 'Math/Logic Error Handling Flow Control 'Strings Left Mid String Right Chr InstrRev Trim Len Asc LTrim LSet Space RTrim RSet Replace UCase Format StrComp LCase Instr StrReverse FormatCurrency StrConv FormatDateTime FormatNumber FormatPerCent 'Files / Folders Dir FileDateTime FreeFile Get Line Input ChDir FileLen Open Put Write MkDir FileCopy Close Seek Print ChDrive Lock Reset Input Spc CurDir UnLock Lof Loc Tab Name GetAttr Eof Kill SetAttr Width RmDir FileAttr 'Declarations Sub Call Set Function CallByName Let Dim PropertyGet Event ReDim PropertySet ArrayName Static PropertyLet Implements Public Option Explicit Friend Private Option Private Enum Const Option Compare TypeName Declare Type...End Type VarType Is GetObject DefType. CreateObject GetAutoServerSettings 'Date/Time Date MonthName Time WeekDayName Now Day Timer Hour DateAdd Minute DateDiff Second DateSerial TimeSerial DateValue TimeValue Year WeekDay Month 'Registry GetSetting SaveSetting DeleteSetting GetAllSettings 'Miscellaneous MsgBox Beep Load DoEvents InputBox UnLoad Shell AddressOf SavePicture Command RaiseEvent LoadPicture Environ Load LoadResData RGB Me LoadResString QBColor SendKeys AppActivate 'Arrays Option Base Erase Dim ReDim UBound LBound Filter Array 'Math/Logic ------------------------------------------------------------------ Hex Rnd Sqr Mod Oct Sgn Abs And Val Sin Atn Or Round Cos Log Xor Int Tan Not Fix Randomize Eqv Partition Like Round Imp CInt... Is Format FormatNumber FormatPerCent 'Error Handling On Error Resume Resume Next Resume Line 'Flow Control While (cond) ... Wend Do While|Until (cond) ... Loop While|Until (cond) For Each X in Collection|Array ... Next X For i = 1 to j Step k ... Next i If (expression) Then ... End if Select Case (expression) Case (cond) Case (cond) End Select ----E ----H ----E ----T 27 Windows API access Visual Basic _tutorials 2005-02-21 13:15:01 ----O 0 0 0 ----E ----D ----E ----C 'API - Application Programming Interface 'When Microsoft wrote Windows they put a huge amount of code into procedure libraries 'which programmers can access. No matter which language you're using (VB, C++, ...) you 'can use these files (called the Windows Application Programming Interface, or API) to access the pre-written code to expand the power of your application. 'Windows has hundreds of files you can access, but the three most often used files are: '- user32.dll controls the visible objects that you see on the screen '- gdi32 home of most graphics oriented API '- kernel32.dll provides access to low level operating system features 'Using procedures from other files is almost exactly the same as using procedures from within 'your own program. The one big difference is that you must tell your application which file the 'procedure is contained in. You must do this for each external procedure you plan to use. 'Telling VB about the procedure you want to use is known as "declaring" the procedure and 'the code to declare a procedure is as follows: Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags as Long, ByVal dwReserved as Long) as Long 'Let's take apart the declaration statement: - Declare 'This is reserved word that VB uses to begin a declaration. There is no alternative - you have to use it. - Function 'Also a reserved word, but in this case it distinguishes between a SUB procedured and a FUNCTION 'procedure. The API use Function procedures so that they can return a value to indicate the results 'of the action. Although you can discard the returned value, it's also possible to check the return value 'to determine that the action was successfully completed. completed. alternative - you have to use it. -ExitWindowsEx 'Inside each DLL is a list of the procedures that it contains. Normally, in a VB declaration statement you 'simply type in the name of the procedure just as it is named in the DLL. Sometimes, the DLL true name 'of the procedure may be a name that is illegal in VB. For those cases, VB allows you to put in the text 'string "Alias NewProcedurename" right behind the filename. In this example, VB would make a call to 'the procedure by using the name "NewProcedureName". - Lib 'user32' 'Here's where you tell VB which file the procedure is in. Normally you would put "user32.dll", showing the 'extension of the procedure library. For the special case of the three Windows system DLLs listed above, 'the API will recognize the files when simply named "user32", "kernel32", and "gdi32" - without the DLL 'extensions shown. In most other cases you must give the complete file name. Unless the file is in the 'system PATH, you must also give the complete path to the file. -(ByVal uFlags as Long ...) 'Exactly like VB procedures, Windows API functions can have a list of arguments. However, while your 'VB procedures often use arguments passed by reference (i.e., their values can be changed), most 'Windows API require that the arguments be passed by value (i.e, a copy of the argument is passed 'to the DLL and the originial variable cannot be changed). 'Also, you'll note that a constant or variable is normally used as the argument for an API call. It's 'technically acceptable to simply use a number for an argument but it is common practice among 'experienced programmers to create constants (or variables) whose name is easy to remember and 'then to use those in the argument list. When you're reading or debugging your code later, the use 'of these easy to read constant/variable names makes it much easier to figure out what went wrong! - as Long 'This is exactly like the code you use to create your own functions. Windows API are functions which 'return values and you must define what type of variable is returned. 'Concerns 'Because the API code executes outside the VB program itself, your own program is susceptable to error ' in the external procedure. If the external procedure crashes, then your own program will crash as well. It 'is not un-common for an API problem to freeze your system and force a reboot - casuing loss of data and/or code. 'Here are several issues/comments about using API which you will want to be aware of: 'Declare '- DECLARE in standard module are PUBLIC by default and be used anywhere in your app '- DECLARE in any other module are PRIVATE to that module and MUST BE marked PRIVATE '- Procedure names for API are CASE-SENSITIVE 'ALIAS '- Is the "real" name of the procedure as found in the DLL '- If the API uses string, you MUST use ALIAS with "A" to specify the correct character set (A=ANSI W=UNICODE) '- WinNT supports W, but Win95/Win98 do not '- Some DLLs have illegal VB names, so you must use ALIAS to rename the procedure '- Can also be the ordinal number of the procedure 'Variable Type '- Very few DLLs recognize VARIANT '- ByRef is VB default '- Most DLLs expect ByVal '- In C documentation, C passes all arguments except arrays by value '- AS ANY can be used but it turns off all type checking 'Strings '- API generally require fixed length strings '- Pass string ByVal means passing pointer to first data byte in the string '- Pass string ByRef means passing memory address to another memory addresss which refers to first data byte in the string '- Most DLLs expect LPSTR (ASCIIZ) strings (end in a null character), which point to the first data byte '- VB Strings should be passed ByVal (in general) '- VB uses BSTR strings (header + data bytes) - BSTR is passed as a pointer to the header '- DLL can modify data in a string variable that it receives as an argument - WARNING: if returned value is longer than passed value, system error occurs! '- Generally, API do not expect string buffers longer than 255 characters '- C & VB both treat a string array as an array of pointers to string data '- Most API require you to pass the length of the string and to fill the string wih spaces 'Arrays '- Pass entire array by passing the first element of the array ByRef '- Pass individual elements of array just like any other variable '- If pass pass binary data to DLL, use array of Byte characters 'Passing a null value '- To pass a null value - zero-length string ("") will not work '- To pass a null value - use vbNullString '- To pass a null value - change Type to Long and then use 0& 'Window Handle '- A handle is simply a number assigned by Windows to each window '- In VB, the handle is the same as the property hWnd '- Handles are always Long variable types 'Callbacks '- Some API can run one of you own VB functions. Your VB function is called a "Callback" '- Callback functions must be in a module. They cannot be in a form. '- Use AddressOf to pass a user-defined function that the DLL procedure can use '- Must have specific set of arguments, AS DEFINED by the API procedure '- Passed procedure must be As Any or As Long 'Subclassing '- All windows work by processing messages from the Windows operating system '- You can change how a window responds to a message by intercepting the message '- To intercept a message, use the API SetWindowsLong 'Miscellaneous '- Control properties MUST be passed by value (use intermediate value to pass ByRef) '- Handles - always declare as ByVal Long '- Variant - to pass Variant to argument that is not a Variant type, pass the Variant data ByVal '- UDT - cannot be passed except as ByRef ----E ----H ----E ----T 28 ASCII Table Visual Basic _tutorials 2005-02-21 11:26:26 ----O 0 0 0 ----E ----D ----E ----C .. 0-9 48-57 A-Z 65-98 a-z 97-122 Tab 9 Tab LF 10 Line feed CR 13 carriage Return Space 32 Space ! 33 exclamation " 34 Double quote # 35 pound sign $ 36 dollar sign % 37 percent sign & 38 ambersand ' 39 Single quote ( 40 Left parenthesis ) 41 Right parenthesiis * 42 asterisk + 43 plus sign , 44 comma - 45 minus sign . 46 period / 47 forward slash : 58 colon ; 59 semi-colon < 60 less than = 61 equal sign > 62 greater than ? 63 question @ 64 at sign { 123 Left curly bracket | 124 pipe } 125 Right curly bracket ~ 126 tilde Codes 0-127 Code Char Code Char Code Char Code Char 0 32 64 @ 96 ` 1 33 ! 65 A 97 a 2 34 " 66 B 98 b 3 35 # 67 C 99 c 4 36 $ 68 D 100 d 5 37 % 69 E 101 e 6 38 & 70 F 102 f 7 39 ' 71 G 103 g 8 40 ( 72 H 104 h 9 41 ) 73 I 105 i 10 42 * 74 J 106 j 11 43 + 75 K 107 k 12 44 , 76 L 108 l 13 45 - 77 M 109 m 14 46 . 78 N 110 n 15 47 / 79 O 111 o 16 48 0 80 P 112 p 17 49 1 81 Q 113 q 18 50 2 82 R 114 r 19 51 3 83 S 115 s 20 52 4 84 T 116 t 21 53 5 85 U 117 u 22 54 6 86 V 118 v 23 55 7 87 W 119 w 24 56 8 88 X 120 x 25 57 9 89 Y 121 y 26 <> 58 : 90 Z 122 z 27 59 ; 91 [ 123 { 28 60 < 92 \ 124 | 29 61 = 93 ] 125 } 30 62 > 94 ^ 126 ~ 31 63 ? 95 _ 127 ----E ----H ----E ----T 29 Collections Visual Basic _tutorials 2005-02-21 11:26:35 ----O 0 0 0 ----E ----D ----E ----C 'Collections are objects which can contain many other objects, not necessarily 'of the same type. Limitation - collections cannot contain UDTs. Dim MyCollection as New Collection 'Collections have these properties/methods: ..Add 'add an item to the collection .Count 'number of objects in the collection .Item 'reference to the object in the collection .Remove 'removes the item from the collection 'members of a collection have an index and a key Key 'unique string value Index 'Long integer between 1 and number of items in the collection 'refer to an item in a Collection in these ways: MyCollection(Key) MyCollection(Index) 'or MyCollection.Item(Key) MyCollection.Item(Index) 'iterate over a collection in two ways: For i = 1 to MyCollection.Count 'do something with MyCollection(i) Next i Dim X as Object For Each X in MyCollection ... do something with X Next 'set a reference to an object in a collection this way Set MyVar = MyCollection.Item(Index) 'to remove an item from a collection MyCollection.Remove "Name" MyCollection.Remove 2 'to clear a collection Set MyCollection = Nothing ----E ----H ----E ----T 30 Subclassing Visual Basic _tutorials 2005-02-21 13:57:35 ----O 0 0 0 ----E ----D ----E ----C 'The Windows Operating System (OS) manages the various windows of your applications. 'Each window is given a unique id number (windows handle, also known as hWnd). The 'OS continually monitors these windows for signs of activity or events - such as a mouse 'click or button press. When an event occurs the OS determines which window(s) it affects 'and sends a message to those windows. The windows respond according to the code 'the programmer has included in the project that contains those windows. 'VB either handles the message for you, or it exposes the message to you as an Event 'procedure, which is where you put your code to respond to the event. 'Each window has a message handler - code that will respond to the OS message. 'The message handler is called a WindowProc - short for window procedure. 'When a window is subclassed, you write a new window procedure that is inserted 'between the OS and the original window procedure. 'Your new procedure is responsible for deciding which messages to handle or which 'messages you want to pass on to the default WindowProc. 'Example of a custom WindowProc - put this in a .BAS module! Public Declare Function CallWindowProc& Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc&, ByVal hWnd&, ByVal Msg&, ByVal wParam&, ByVal lParam&) Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd&, ByVal nIndex&, ByVal dwNewLong&) As Long Const GWL_WNDPROC = -4 Public lpPrevWindowProc as Long Public Function WindowProc(ByVal hWnd As Long, ByVal iMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long 'this is the WindowProc that will be used to reply to Windows messages - takes over for the original WindowProc If iMsg = TargetMessage 'do something of our own WindowProc = 0& Exit Function ' exit the function - preventing VB from getting the message - delete this to let both WindowProc run End If 'pass all other messages on to VB and then return the value to Windows WindowProc = CallWindowProc(lpPrevWindowProce, hWnd, iMsg, wParam, lParam) 'passes parameters unchanged to original Windows message handler End Function 'in load event of form, take over control of messages - save pointer to the original WindowProc lpPrevWindowProc = SetWindowLong(hWnd, GWL_WNDPROC, AddressOf WindowProc) 'this is a CallBack 'in unload event of form - return control to the original WindowProc Call SetWindowLong(hWnd, GWL_WNDPROC, lpPrevWindowProc) ----E ----H ----E ----T 31 Distribution of applications Visual Basic _tutorials 2005-02-21 11:34:22 ----O 0 0 0 ----E ----D ----E ----C ..Normally a programmer creates a single setup / distribution file which the user runs to install the application. The setup file usually performs the following: - creates required folder structure - installs application EXE - installs applicaton-specific files (data, help, ...) - create Registry entrites required by the application - installs the VB runtime files - installs any OCXs/DLLs that are not a part of the runtime or the system OS In addition to the EXE file that you create during compilation, VB requires that some specific files be present on the PC before a user can use the application. VB Runtime Files The intrinsic controls, functions, and other features of VB are distributed across several files - called the VB runtime files. These features are NOT included in the compiled EXE. The VB run-time files must be on a PC before it can run VB programs. If a user has previously installed the VB run-time files, the files do not have to be re-installed. However, the VB programmer usually has to assume that the files are not available, and include them in his setup file. The runtime files are: msvbvm60.dll stdole2.tlb oleaut32.dll olepro32.dll comcat.dll asycflt.dll ctl3d32.dll OCXs Controls placed in an application, such as the RichTextBox or the Treeview, exist in separate files. They are not part of the VB run-time files and must be included in the setup file. Installation Tools VB comes with it's own Setup Wizard for creating the setup file, but most folks find the tool to be of limited value. There are other free tools on the market which do a better job. I highly recommend Inno Setup at http://www.jrsoftware.org/isinfo.php I have also use Install Creator and found it to be excellent http://www.clickteam.com ----E ----H ----E ----T 32 Top 100 Visual Basic _tutorials 2005-02-27 18:43:12 ----O 0 0 0 ----E ----D ----E ----C ..Most used VB code ..Search on 'Top100' to view the full snippets Applications Associate an extension with the app Create a shortcut to your app in any folder Create desktop shortcut Dialog - color - using API Dialog - file - using API Dialog - folder - using APi Dialog - font - using API Open Help file Put app icon in system tray Put app in Explorer context menu Put app in SendTo menu Start new application and wait for it to finish Startup with Windows (use wshom) Test if application is running within IDE Arrays Cycle through an array Randomly shuffle an array Remove element from array by content Remove element from array by position Search an array Clipboard Copy image to clipboard Copy text to clipboard Controls All - automatically highlight content on focus All - capture any key All - force lower case as keys are entered ComboBox - create MRU for dropdown list Imagelist - add images at run time Richtextbox - find and replace Richtextbox - first visible line/position of 1st char on the line Richtextbox - merge contents of two richtextboxes Richtextbox - prevent flicker of richtextbox during reposition Richtextbox - word wrap Toolbar - responding to button selection TreeView - traverse the tree Date-Time Time - elapsed time between 2 dates Timer - milliseconds between 2 events Files Binary Read/write data to a specific location within the file Read/write entire file at once View in hex format Files Text Read text file all at one time Read text file one line at a time View text file content Files Create full pathname Extract file name from full path File exists File properties (size/date/attributes) Folders Delete a folder and its subfolders Folder exists Get list of drive letters Get type of drive Open DOS window at folder Open Window at folder Open Windows Explorer at folder Forms Center a form Keep form on top Set min/max size of form Splitter, horizontal (form-based) Splitter, horizontal (splitter bar) Free Controls and Tools Free programming tools Graphics Convert between Long, RGB, VB, and Web colors Get JPG/GIF/BMP/PNG image size Get screen resolution Gradient - apply to a picturebox, 2 colors, 4 directions Gradient - apply to form, 2 colors, 4 directions Gradient - full spectrum Overlay an image Read/write/display/convert GIF/JPG/BMP Resize an image, keeping aspect ratio Screen capture Set wallpaper Internet Check for Internet connection Create URL shortcut Create web page (HTML) from code Download file from the web using API Download web page (capture as string) Get remote file information - size, date Open a web page in default browser Send email using default app Upload file (Freeware EZ-FTP) Upload file (Internet Transfer Control) Math Random integer within range Round to 2 decimals Round to n decimals Multimedia Play CD (MM control) Play sound (API only) Play sound (MM control) Play video (MM control) Record sound (MM control) Navigation List files and folders - API (pattern) List files and folders - Dir$ (pattern) List files and folders - FSO List files and folders - SysFileControls Printing Color printing Print images, positioned and scaled Print preview Registry Clear application settings from registry Edit registry key Use registry to save program settings Security Checksum Encrypt a file (uses password) Encrypt a string (uses password) Sort QuickSort Strings Convert Byte array to string Find text before/between/after two target strings Find/replace Split string into array System Get computer name Get name of special folders Get user name Get Windows and System directories Get Windows version Reboot, restart or logoff system Reboot, restart or logoff system (XP only) ----E ----H ----E ----T Associate an extension with the app Visual Basic applications Top100 2005-02-18 11:01:12 ----O 0 0 0 ----E ----D ----E ----C Option Explicit Private Const HKEY_CLASSES_ROOT = &H80000000 Private Declare Function RegCreateKey Lib _ "advapi32.dll" Alias "RegCreateKeyA" _ (ByVal hKey As Long, ByVal lpSubKey As _ String, phkResult As Long) As Long Private Declare Function RegCloseKey Lib _ "advapi32.dll" (ByVal hKey As Long) As Long Private Declare Function RegSetValueEx Lib _ "advapi32.dll" Alias "RegSetValueExA" _ (ByVal hKey As Long, ByVal _ lpValueName As String, ByVal _ Reserved As Long, ByVal dwType _ As Long, lpData As Any, ByVal _ cbData As Long) As Long Private Const REG_SZ = 1 Public Function CreateFileAssociation(AppName As String, _ ByVal AppExtension As String, AppCommand As String) As Boolean 'Parameters: 'AppName = name of application 'AppExtension: = file extension 'AppCommand = command line for application 'Example: 'CreateFileAssociation "Notepad", ".txt", "notepad.exe" Dim bAns As Boolean Dim sKeyName As String Dim sExtName As String AppExtension = Trim(AppExtension) If Left(AppExtension, 1) <> "." Then Exit Function sExtName = Mid(AppExtension, 2) & " File" bAns = WriteStringToRegistry(HKEY_CLASSES_ROOT, _ AppExtension, "", sExtName) If bAns Then bAns = WriteStringToRegistry(HKEY_CLASSES_ROOT, _ sExtName & "\shell\open\command", "", AppCommand) CreateFileAssociation = bAns End Function Private Function WriteStringToRegistry(hKey As _ Long, strPath As String, strValue As String, _ strdata As String) As Boolean Dim bAns As Boolean On Error GoTo ErrorHandler Dim keyhand As Long Dim r As Long r = RegCreateKey(hKey, strPath, keyhand) If r = 0 Then r = RegSetValueEx(keyhand, strValue, 0, _ REG_SZ, ByVal strdata, Len(strdata)) r = RegCloseKey(keyhand) End If WriteStringToRegistry = (r = 0) Exit Function ErrorHandler: WriteStringToRegistry = False Exit Function End Function ----E ----H ----E ----T Check regional settings Visual Basic applications 2005-02-16 15:30:20 ----O 0 0 0 ----E ----D ----E ----C function CheckRegionalSettings() As Boolean Dim i As Integer Dim temp1 As String 'check for Regional Setting ChDir App.Path Open "temp.txt" For Output As #1 Dim s As Single s = 12.23 Print #1, s Close #1 Open "temp.txt" For Input As #1 Line Input #1, temp1 Close #1 i = InStr(temp1, ",") If i <> 0 Then CheckRegionalSettings = True Else CheckRegionalSettings = False End If end function ----E ----H ----E ----T Close a second app with SENDKEYS Visual Basic applications 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C 'use SENDKEYS to Alt-F4 to end an application 'SecondAppTitle refers to what the application has in its Title bar AppActivate SecondAppTitle SendKeys "%(F4)", True ----E ----H ----E ----T Create a shortcut to your app in any folder Visual Basic applications Top100 2005-02-18 11:01:52 ----O 0 0 0 ----E ----D ----E ----C 'need reference In your program to Windows Script Host Object Model wshom.ocx ' Dim WS As WshShell Dim oShellLink As WshShortcut Set WS = New WshShell Set oShellLink = WS.CreateShortcut("C:\myapplication.lnk") 'all shortcuts end In .LNK oShellLink.IconLocation = "C:\myapplication.ico" 'use for icon not In EXE file oShellLink.Description = "My Installation" oShellLink.WorkingDirectory = "c:\temp" 'your choice oShellLink.TargetPath = "C:\" 'most likely this: App.Path & "\" & App.EXEName oShellLink.Save Set WS = Nothing Set oShellLink = Nothing ----E ----H ----E ----T Create desktop shortcut Visual Basic applications Top100 2005-02-06 19:32:17 ----O 0 0 0 ----E ----D ----E ----C 'reference to Windows Script Host Object Model is required 'this version goes to a folder of your choice Dim wShell As New IWshShell_Class Dim wShortcut As IWshShortcut_Class Set wShortcut = wShell.CreateShortcut("d:\test.lnk") wShortcut.TargetPath = "d:\test.txt" wShortcut.Save 'and this version goes to the desktop Dim wShell As New IWshShell_Class Dim wShortcut As IWshShortcut_Class Dim sDesktop as string ' path of desktop Dim sTargetPath as string ' path to file for which a link is to be created sDesktop = wShell.SpecialFolders.Item("Desktop") sTargetPath = wShell.ExpandEnvironmentStrings("%windir%") Set wShortcut = wShell.CreateShortcut(sDesktop & "filename.lnk") wShortcut.TargetPath = sTargetPath & "\filename.exe" wShortcut.Arguments = "" wShortCut.WorkingDirectory = sDesktop wShortCut.Save ----E ----H ----E ----T Dialog - color - using API Visual Basic applications Top100 2005-02-02 23:26:02 ----O 0 0 0 ----E ----D ----E ----C 'API dialogs for file selections and color selections Private Type CHOOSECOLOR lStructSize As Long hwndOwner As Long hInstance As Long rgbResult As Long lpCustColors As String Flags As Long lCustData As Long lpfnHook As Long lpTemplateName As String End Type Private Declare Function ChooseColorAPI Lib "comdlg32.dll" Alias _ "ChooseColorA" (pChoosecolor As CHOOSECOLOR) As Long Sub SelectColor() Dim CustomColors() As Byte Dim cc As CHOOSECOLOR Dim Custcolor(16) As Long Dim iReturn As Long cc.lStructSize = Len(cc) cc.hwndOwner = frmMain.hwnd cc.hInstance = 0 cc.lpCustColors = StrConv(CustomColors, vbUnicode) cc.Flags = 0 iReturn = ChooseColorAPI(cc) If iReturn <> 0 Then lblBackgroundColor.BackColor = cc.rgbResult End If End Sub ----E ----H ----E ----T Dialog - file - using API Visual Basic applications Top100 2005-02-03 11:33:47 ----O 0 0 0 ----E ----D ----E ----C Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long Private Type OPENFILENAME lStructSize As Long hwndOwner As Long hInstance As Long lpstrFilter As String lpstrCustomFilter As String nMaxCustFilter As Long nFilterIndex As Long lpstrFile As String nMaxFile As Long lpstrFileTitle As String nMaxFileTitle As Long lpstrInitialDir As String lpstrTitle As String Flags As Long nFileOffset As Integer nFileExtension As Integer lpstrDefExt As String lCustData As Long lpfnHook As Long lpTemplateName As String End Type Sub SelectFile() Dim OpenFile As OPENFILENAME Dim lReturn As Long Dim sFilter As String Dim BackImage As String OpenFile.lStructSize = Len(OpenFile) OpenFile.hwndOwner = frmMain.hwnd OpenFile.hInstance = App.hInstance sFilter = "Image Files (*.jpg)" & Chr(0) & "*.jpg" & Chr(0) OpenFile.lpstrFilter = sFilter OpenFile.nFilterIndex = 1 OpenFile.lpstrFile = String(257, 0) OpenFile.nMaxFile = Len(OpenFile.lpstrFile) - 1 OpenFile.lpstrFileTitle = OpenFile.lpstrFile OpenFile.nMaxFileTitle = OpenFile.nMaxFile OpenFile.lpstrInitialDir = App.path '"C:\" OpenFile.lpstrTitle = "Select Background (Tile) Image File" OpenFile.Flags = 0 lReturn = GetOpenFileName(OpenFile) If lReturn = 0 Then 'no action Else txtTemp.Text = OpenFile.lpstrFile txtTemp.Text = Mid$(txtTemp.Text, InStrRev(txtTemp.Text, "\") + 1) End If End Sub ----E ----H ----E ----T Dialog - folder - using APi Visual Basic applications Top100 2005-02-03 11:29:43 ----O 0 0 0 ----E ----D ----E ----C Private Type BROWSEINFO hOwner As Long pidlRoot As Long pszDisplayName As String lpszTitle As String ulFlags As Long lpfn As Long lParam As Long iImage As Long End Type Private Const BIF_RETURNONLYFSDIRS = &H1 Private Const BIF_DONTGOBELOWDOMAIN = &H2 Private Const BIF_STATUSTEXT = &H4 Private Const BIF_RETURNFSANCESTORS = &H8 Private Const BIF_BROWSEFORCOMPUTER = &H1000 Private Const BIF_BROWSEFORPRINTER = &H2000 Private Const MAX_PATH = 260 Private Declare Function SHGetPathFromIDList Lib "shell32" _ Alias "SHGetPathFromIDListA" _ (ByVal pidl As Long, _ ByVal pszPath As String) As Long Private Declare Function SHBrowseForFolder Lib "shell32" _ Alias "SHBrowseForFolderA" _ (lpBrowseInfo As BROWSEINFO) As Long Private Declare Sub CoTaskMemFree Lib "ole32" _ (ByVal pv As Long) Private Sub SelectFolder() Dim bi As BROWSEINFO Dim pidl As Long Dim path As String Dim pos As Long With bi .hOwner = Me.hwnd .pidlRoot = 0& .lpszTitle = "Select image folder" .ulFlags = BIF_RETURNONLYFSDIRS End With pidl = SHBrowseForFolder(bi) path = Space$(MAX_PATH) If SHGetPathFromIDList(ByVal pidl, ByVal path) Then pos = InStr(path, Chr$(0)) txtFolder.Text = LCase$(Left(path, pos - 1)) End If Call CoTaskMemFree(pidl) End Sub ----E ----H ----E ----T Dialog - font - using API Visual Basic applications Top100 2005-02-06 21:42:49 ----O 0 0 0 ----E ----D ----E ----C Private Const LF_FACESIZE = 32 Private Type LOGFONT lfHeight As Long lfWidth As Long lfEscapement As Long lfOrientation As Long lfWeight As Long lfItalic As Byte lfUnderline As Byte lfStrikeOut As Byte lfCharSet As Byte lfOutPrecision As Byte lfClipPrecision As Byte lfQuality As Byte lfPitchAndFamily As Byte lfFaceName(LF_FACESIZE) As Byte End Type Private Type ChooseFont lStructSize As Long hwndOwner As Long ' caller's window handle hdc As Long ' printer DC/IC or NULL lpLogFont As Long ' LOGFONT ' ptr. to a LOGFONT struct iPointSize As Long ' 10 * size in points of selected font flags As Long ' enum. type flags rgbColors As Long ' returned text color lCustData As Long ' data passed to hook fn. lpfnHook As Long ' ptr. to hook function lpTemplateName As String ' custom template name hInstance As Long ' instance handle of.EXE that ' contains cust. dlg. template lpszStyle As String ' return the style field here ' must be LF_FACESIZE or bigger nFontType As Integer ' same value reported to the EnumFonts ' call back with the extra FONTTYPE_ ' bits added MISSING_ALIGNMENT As Integer nSizeMin As Long ' minimum pt size allowed & nSizeMax As Long ' max pt size allowed if ' CF_LIMITSIZE is used End Type Private Declare Function ChooseFont Lib "comdlg32.dll" Alias "ChooseFontA" (pChoosefont As ChooseFont) As Long Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long) Private Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, ByVal dwBytes As Long) As Long Private Declare Function GlobalFree Lib "kernel32" (ByVal hMem As Long) As Long Private Const GMEM_FIXED = &H0 Private Const GMEM_ZEROINIT = &H40 Private Const GPTR = (GMEM_FIXED Or GMEM_ZEROINIT) Private Const CF_SCREENFONTS = &H1 Private Const CF_PRINTERFONTS = &H2 Private Const CF_BOTH = (CF_SCREENFONTS Or CF_PRINTERFONTS) Private Const CF_SHOWHELP = &H4& Private Const CF_ENABLEHOOK = &H8& Private Const CF_ENABLETEMPLATE = &H10& Private Const CF_ENABLETEMPLATEHANDLE = &H20& Private Const CF_INITTOLOGFONTSTRUCT = &H40& Private Const CF_USESTYLE = &H80& Private Const CF_EFFECTS = &H100& Private Const CF_APPLY = &H200& Private Const CF_ANSIONLY = &H400& Private Const CF_SCRIPTSONLY = CF_ANSIONLY Private Const CF_NOVECTORFONTS = &H800& Private Const CF_NOOEMFONTS = CF_NOVECTORFONTS Private Const CF_NOSIMULATIONS = &H1000& Private Const CF_LIMITSIZE = &H2000& Private Const CF_FIXEDPITCHONLY = &H4000& Private Const CF_WYSIWYG = &H8000 ' must also have CF_SCREENFONTS CF_PRINTERFONTS Private Const CF_FORCEFONTEXIST = &H10000 Private Const CF_SCALABLEONLY = &H20000 Private Const CF_TTONLY = &H40000 Private Const CF_NOFACESEL = &H80000 Private Const CF_NOSTYLESEL = &H100000 Private Const CF_NOSIZESEL = &H200000 Private Const CF_SELECTSCRIPT = &H400000 Private Const CF_NOSCRIPTSEL = &H800000 Private Const CF_NOVERTFONTS = &H1000000 Sub ChooseFont () Dim CF As ChooseFont, hMem As Long, LF As LOGFONT, aFontName As String hMem = GlobalAlloc(GPTR, Len(LF)) CF.hInstance = App.hInstance CF.hwndOwner = hWnd CF.lpLogFont = hMem CF.lStructSize = Len(CF) CF.flags = CF_BOTH If ChooseFont(CF) Then CopyMemory LF, ByVal hMem, Len(LF) aFontName = Space$(LF_FACESIZE) CopyMemory ByVal aFontName, LF.lfFaceName(0), LF_FACESIZE With Picture1.Font .Name = CString(aFontName) .Bold = LF.lfWeight .Italic = LF.lfItalic .Size = CF.iPointSize / 10 .Underline = LF.lfUnderline .Charset = LF.lfCharSet .Strikethrough = LF.lfStrikeOut End With Picture1.Cls Picture1_Paint End If GlobalFree hMem End Sub Private Function CString(aStr As String) As String CString = "" Dim k As Long k = InStr(aStr, Chr$(0)) If k Then CString = Left$(aStr, k - 1) End If End Function ----E ----H ----E ----T Find default application for a file Visual Basic applications 2005-02-16 15:04:11 ----O 0 0 0 ----E ----D ----E ----C Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _ (ByVal lpFile As String, ByVal lpDirectory As String, _ ByVal lpResult As String) As Long Const MAX_PATH = 260 Dim iResult As Long Dim Buffer As String Buffer = Space$(MAX_PATH) iResult = FindExecutable("c:\test.txt", "", Buffer) ----E ----H ----E ----T Find prior instance of EXE Visual Basic applications 2005-02-02 23:27:13 ----O 0 0 0 ----E ----D ----E ----C 'VB has a built-in method to detect a prior instance of an application If App.PrevInstance Then 'there is a copy of the program already running End If ----E ----H ----E ----T Get list of available fonts Visual Basic applications 2005-02-16 14:58:40 ----O 0 0 0 ----E ----D ----E ----C Private Sub CreateFontList() ' populate a list with system fonts Dim Cnt As Long Dim s1 As String For Cnt = 1 To Screen.FontCount s1 = Screen.Fonts(Cnt) If s1 <> "" Then List1.AddItem s1 Next List1.ListIndex = 0 End Sub ----E ----H ----E ----T Limit Size of Window Visual Basic applications 2005-02-18 11:05:11 ----O 0 0 0 ----E ----D ----E ----C Option Explicit 'A demo project showing how to prevent the user from making a window smaller 'or larger than you want them to, through subclassing the WM_GETMINMAXINFO message. 'by Bryan Stafford of New Vision SoftwareŽ - newvision@mvps.org 'this demo is released into the Public domain "As Is" without 'warranty Or guaranty of Any kind. In other words, use at 'your own risk. ' See the comments at the end of this Module for a brief explaination of ' what subclassing Is. Type POINTAPI X As Long Y As Long End Type ' the message we will subclass Public Const WM_GETMINMAXINFO As Long = &H24& Type MINMAXINFO ptReserved As POINTAPI ptMaxSize As POINTAPI ptMaxPosition As POINTAPI ptMinTrackSize As POINTAPI ptMaxTrackSize As POINTAPI End Type ' this var will hold a pointer to the original message handler so we MUST ' save it so that it can be restored before we exit the app. If we don't ' restore it.... CRASH!!!! Public g_nProcOld As Long ' declarations of the API functions used Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpDest As Any, lpSource As Any, _ ByVal cBytes&) Public Declare Function CallWindowProc& Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc&, _ ByVal hwnd&, ByVal Msg&, ByVal wParam&, ByVal lParam&) Public Const GWL_WNDPROC As Long = (-4&) ' API Call To alter the class data for a window Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd&, _ ByVal nIndex&, ByVal dwNewLong&) As Long '===================================================================================== Public Function WindowProc(ByVal hwnd As Long, ByVal iMsg As Long, _ ByVal wParam As Long, ByVal lParam As Long) As Long ' this Is *our* implimentation of the message handling routine ' determine which message was recieved Select Case iMsg Case WM_GETMINMAXINFO ' dimention a variable to hold the structure passed from Windows in lParam Dim udtMINMAXINFO As MINMAXINFO Dim nWidthPixels&, nHeightPixels& nWidthPixels = Screen.Width \ Screen.TwipsPerPixelX nHeightPixels = Screen.Height \ Screen.TwipsPerPixelY ' copy the struct to our UDT variable CopyMemory udtMINMAXINFO, ByVal lParam, Len(udtMINMAXINFO) With udtMINMAXINFO ' Set the width of the form when it's maximized .ptMaxSize.X = nWidthPixels '- (nWidthPixels \ 4) ' Set the height of the form when it's maximized .ptMaxSize.Y = nHeightPixels '- (nHeightPixels \ 4) ' Set the left of the form when it's maximized .ptMaxPosition.X = 0 'nWidthPixels \ 8 ' Set the top of the form when it's maximized .ptMaxPosition.Y = 0 'nHeightPixels \ 8 ' Set the max width that the user can drag the form .ptMaxTrackSize.X = .ptMaxSize.X ' Set the max height that the user can drag the form .ptMaxTrackSize.Y = .ptMaxSize.Y ' Set the min Width that the user can drag the form .ptMinTrackSize.X = 5550 \ Screen.TwipsPerPixelX 'nWidthPixels \ 4 ' Set the min width that the user can drag the form .ptMinTrackSize.Y = 4400 \ Screen.TwipsPerPixelY 'nHeightPixels \ 4 End With ' copy our modified struct back to the Windows struct CopyMemory ByVal lParam, udtMINMAXINFO, Len(udtMINMAXINFO) ' Return zero indicating that we have acted on this message WindowProc = 0& ' Exit the function without letting VB Get it's grubby little hands on the message Exit Function End Select ' pass all messages on to VB and then return the value to Windows WindowProc = CallWindowProc(g_nProcOld, hwnd, iMsg, wParam, lParam) End Function '================================================== Private Sub Form_Unload(Cancel As Integer) ' give message processing control back To VB ' If you don't do this you WILL crash!!! If UseSubClassing Then Call SetWindowLong(hwnd, GWL_WNDPROC, g_nProcOld) End Sub ----E ----H ----E ----T MRU for menus Visual Basic applications 2005-02-06 10:52:48 ----O 0 0 0 ----E ----D ----E ----C Sub UpdateApplicationMRUList(FileName As String) 'maintain a list of the last n files opened in the program 'recreate menu list each time program is opened '--------------------------- 'put this in the combolist itemclick event combolist1.additem FileName 'if it already exists in the list, then remove it Dim i As Long, Found As Boolean, n as Long n = 5 For i = 2 To n 'check to see if FileName is already in the list If LCase$(FileName) = LCase$(mnuFileName(i).Caption) Then Found = True Next i If Found = False Then mnuFileName(5).Caption = mnuFileName(4).Caption mnuFileName(4).Caption = mnuFileName(3).Caption mnuFileName(3).Caption = mnuFileName(2).Caption mnuFileName(2).Caption = mnuFileName(1).Caption mnuFileName(1).Caption = X End If mnuSeparator36.Visible = False For i = 1 To 5 mnuFileName(i).Visible = CBool(Len(Trim$(mnuFileName(i).Caption))) If mnuFileName(i).Visible = True Then mnuSeparator36.Visible = True Next i End Sub '--------------------------- and run this at form load mnuSeparator36.Visible = False For i = 1 To 5 mnuFileName(i).Visible = CBool(Len(Trim$(mnuFileName(i).Caption))) If mnuFileName(i).Visible = True Then mnuSeparator36.Visible = True Next i '---------------------------- and use this to save/get settings between sessions mnuFileName(1).Caption = GetSetting(App.Title, "Settings", "File1", "") mnuFileName(2).Caption = GetSetting(App.Title, "Settings", "File2", "") mnuFileName(3).Caption = GetSetting(App.Title, "Settings", "File3", "") mnuFileName(4).Caption = GetSetting(App.Title, "Settings", "File4", "") mnuFileName(5).Caption = GetSetting(App.Title, "Settings", "File5", "") SaveSetting App.Title, "Settings", "File1", mnuFileName(1).Caption SaveSetting App.Title, "Settings", "File2", mnuFileName(2).Caption SaveSetting App.Title, "Settings", "File3", mnuFileName(3).Caption SaveSetting App.Title, "Settings", "File4", mnuFileName(4).Caption SaveSetting App.Title, "Settings", "File5", mnuFileName(5).Caption ----E ----H ----E ----T Open Help file Visual Basic applications Top100 2005-02-18 11:05:42 ----O 0 0 0 ----E ----D ----E ----C '1. F1 Key 'Set app.Helpfile Property and Press F1 '2. API Declare WinHelp ... 'bring up contents of Help file iResult = WinHelp(Me.hwnd, "c:\yourfile.hlp") 'jump to topic (topic id=1000 in this example) iResults = WinHelp(Me.hwnd, "c:\yourfile.hlp", HELP_CONTEXT, 1000&) 'bring up search window iResults = WinHelp(Me.hwnd, "c:\yourfile.hlp", HELP_PARTIALKEY, ByVal "") 'quit Help iResults = WinHelp(Me.hwnd, "c:\yourfile.hlp", HELP_QUIT, 0&) ----E ----H ----E ----T Popup menu Visual Basic applications 2005-02-21 22:57:20 ----O 0 0 0 ----E ----D ----E ----C 'create a menu item 'mnuHiddenMenu' and set its .visible property to False 'then create sub-menu items under it with their .visible property to True 'In the MouseUp event of any control or form, place this: If Button = vbRightButton Then PopupMenu mnuHiddenMenu ----E ----H ----E ----T Put app icon in system tray Visual Basic applications Top100 2005-02-18 11:08:17 ----O 0 0 0 ----E ----D ----E ----C Private Declare Function Shell_NotifyIcon Lib "shell32.dll" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long 'Private Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias " Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long 'These three constants specify what you want to do Private Const NIM_Add = &H0 Private Const NIM_DELETE = &H2 Private Const NIM_MODIFY = &H1 Private Const NIF_ICON = &H2 Private Const NIF_MESSAGE = &H1 Private Const NIF_TIP = &H4 Private Const WM_LBUTTONDBLCLK = &H203 Private Const WM_LBUTTONDOWN = &H201 Private Const WM_LBUTTONUP = &H202 Private Const WM_MOUSEMOVE = &H200 Private Const WM_RBUTTONDBLCLK = &H206 Private Const WM_RBUTTONDOWN = &H204 Private Const WM_RBUTTONUP = &H205 Private Type NOTIFYICONDATA cbSize As Long hwnd As Long uID As Long uFlags As Long uCallbackMessage As Long hIcon As Long szTip As String * 64 End Type Private IconData As NOTIFYICONDATA Sub ShowApp() Me.WindowState = vbNormal Shell_NotifyIcon NIM_DELETE, IconData Me.Show End Sub Private Sub Form_Load() With IconData .cbSize = Len(IconData) ' The length of the NOTIFYICONDATA Type .hIcon = Me.Icon ' A reference to the form's icon .hwnd = Me.hwnd ' hWnd of the form .szTip = "My Tooltip" & Chr(0) ' Tooltip String delimited with a Null character .uCallbackMessage = WM_MOUSEMOVE ' The icon we're placing will send messages to the MouseMove event .uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGE ' It will have message handling and a tooltip .uID = vbNull ' uID is not used by VB, so it's set to a Null value End With End Sub Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim Msg As Long Msg = X / Screen.TwipsPerPixelX ' The message Is passed to the X value If Msg = WM_LBUTTONDBLCLK Then ' The user has double-clicked your icon Call Command1_Click ' Show the window ElseIf Msg = WM_RBUTTONDOWN Then ' Right-click ' PopupMenu mnuPopup ' Popup the menu End If End Sub Private Sub Form_Resize() If Me.WindowState = 1 Then Call Shell_NotifyIcon(NIM_Add, IconData) Me.Hide End If End Sub Private Sub Form_Unload(Cancel As Integer) Shell_NotifyIcon NIM_DELETE, IconData End Sub ----E ----H ----E ----T Put app in Explorer context menu Visual Basic applications Top100 2005-01-30 17:29:31 ----O 0 0 0 ----E ----D ----E ----C ----E ----H ----E ----T Put app in SendTo menu Visual Basic applications Top100 2005-02-18 11:08:54 ----O 0 0 0 ----E ----D ----E ----C 'Get SendTo folder Private Declare Function SHGetFolderPath Lib "shfolder" Alias "SHGetFolderPathA" (ByVal hwndOwner As Long, _ ByVal nFolder As Long, ByVal hToken As Long, ByVal dwFlags As Long, ByVal pszPath As String) As Long Private Const CSIDL_SENDTO As Long = &H9 '{user}\SendTo Dim SendToFolder As String Dim iReturn As Long SendToFolder = String(MAX_PATH, 0) iReturn = SHGetFolderPath(0, CSIDL, 0, SHGFP_Type_CURRENT, SendToFolder) 'Put shortcut there 'need reference in your program to Windows Script Host Object Model wshom.ocx ' Dim WS As WshShell Dim oShellLink As WshShortcut Set WS = New WshShell Set oShellLink = WS.CreateShortcut("C:\myapplication.lnk") 'all shotcuts End In .LNK oShellLink.IconLocation = "C:\myapplication.ico" 'use for icon not In EXE file oShellLink.Description = "My Installation" oShellLink.WorkingDirectory = App.path 'your choice oShellLink.TargetPath = App.Path & "\" & App.EXEName oShellLink.Save Set WS = Nothing Set oShellLink = Nothing ----E ----H ----E ----T Show/hide mouse cursor Visual Basic applications 2005-01-27 08:42:42 ----O 0 0 0 ----E ----D ----E ----C 'Just call ShowCursor and pass a false to hide it or a true to show it again. Public Declare Function ShowCursor Lib "user32" Alias "ShowCursor" (ByVal bShow As Long) As Long ----E ----H ----E ----T Simulate a mouse click Visual Basic applications 2005-02-18 11:09:05 ----O 0 0 0 ----E ----D ----E ----C 'click mouse at specific XY (In pixels) on a form Public Declare Function SendMessage Lib "user32" _ Alias "SendMessageA" (ByVal hwnd As Long, _ ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Public Sub SendClick(lnghWND As Long, x As Long, y As Long) Private Const WM_LBUTTONDOWN = &H201 Private Const WM_LBUTTONUP = &H202 Dim iResult As Long Dim lParam As Long lParam = (y * &H10000) + x iResult = SendMessage(lnghWND, WM_LBUTTONDOWN, 0&, ByVal lnglParam) iResult = SendMessage(lnghWND, WM_LBUTTONUP, 0&, ByVal lnglParam) End Sub ----E ----H ----E ----T Start new application and wait for it to finish Visual Basic applications Top100 2005-02-18 11:09:15 ----O 0 0 0 ----E ----D ----E ----C Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Const SYNCHRONIZE = &H100000 Private Const INFINITE = -1& 'start the indicated program and wait for it to finish Private Sub ShellAndWait(ByVal program_Name As String) Dim process_id As Long Dim process_handle As Long process_id = Shell(program_Name, vbNormalFocus) process_handle = OpenProcess(SYNCHRONIZE, 0, process_id) If process_handle <> 0 Then WaitForSingleObject process_handle, INFINITE CloseHandle process_handle End If End Sub ----E ----H ----E ----T Startup with Windows (use wshom) Visual Basic applications Top100 2005-02-16 09:52:54 ----O 0 0 0 ----E ----D ----E ----C 'two options - both require reference to Windows Script Host Object Mode (wshom.ocx) 'add a registry entry in HKLM\Software\Microsoft\Windows\CurrentVersion\Run Dim oShell As IWshShell_Class Set oShell = New IWshShell_Class oShell.RegWrite "HKLM\Software\Microsoft\Windows\CurrentVersion\Run\MyVBApp", _ "c:\app\appname.exe", "REG_SZ" 'put shortcut in startup menu 'include reference in VB program to Windows Script Host Object Mode (wshom.ocx) Dim oShell As IWshShell_Class Dim oSCut As IWshShortcut_Class Dim sPath As String Set oShell = New IWshShell_Class sPath = oShell.SpecialFolders("Startup") Set oSCut = oShell.CreateShortcut(sPath & "\TestStartup.lnk") oSCut.TargetPath = cPGM oSCut.Save ----E ----H ----E ----T Stop flickering Visual Basic applications 2005-02-09 16:29:05 ----O 0 0 0 ----E ----D ----E ----C Declare Function LockWindowUpdate Lib "user32" (ByVal hwndLock As Integer) As Integer Form1_Load() 'While loading a form LockWindowUpdate frmTest.hWnd 'show it fromTest.show 'Unlock LockWindowUpdate 0 ----E ----H ----E ----T Test if application is running within IDE Visual Basic applications Top100 2005-02-02 08:18:26 ----O 0 0 0 ----E ----D ----E ----C Public Function IsIDE() As Boolean On Error GoTo ExitHandler Debug.Print 1 / 0 'doesn't compile, so doesn't execute in EXE ExitHandler: IsIDE = Err '1/0 gives error only in IDE. False = no error, True = error End Function ----E ----H ----E ----T Toggle menu checkmark Visual Basic applications 2005-02-09 16:41:41 ----O 0 0 0 ----E ----D ----E ----C MyMenu.checked = Not MyMenu.checked ----E ----H ----E ----T Convert an array to lower case Visual Basic arrays string, text, lower, case 2005-02-18 11:10:20 ----O 0 0 0 ----E ----D ----E ----C 'first join all elements, separated by a delimiter of your choice - "++++" In this example 'Then make the entire string lower case 'finally, use split to take apart the string and place it In an array Dim temp As String, MyArray As Variant temp = Join(Myarray,"++++") temp = LCase$(temp) MyArray = Split(temp,"++++") 'here Is a second approach Dim i As Long For i = 0 To UBound(MyArray) MyArray(i) = LCase$(MyArray) Next i ----E ----H ----E ----T Cycle through an array Visual Basic arrays Top100 2005-02-02 15:19:02 ----O 0 0 0 ----E ----D ----E ----C Dim i as Long For i = lbound(MyArray) to ubound(MyArray) 'do something with MyArray(i) Next i 'if you know the upper/lower limits of the array, just use them Dim MyArray(100) 'default lower limit is zero in VB For i = 0 to 100 'do something to MyArray(i) Next i ----E ----H ----E ----T Deal a deck of cards Visual Basic arrays games, cards, card deck 2005-02-16 14:55:30 ----O 0 0 0 ----E ----D ----E ----C Dim Cards(52), i As Integer, j As Integer, temp As Integer 'shuffle the deck For i = 1 To 52 'randomly pick a swap position j = Int (52) 'swap the current position And the random position temp = Cards(i) Cards(i) = Cards(j) Cards(j) = temp Next i 'cards() Now contains random selection of cards positions - 1 thru 52 ----E ----H ----E ----T Erase an array Visual Basic arrays 2005-02-18 11:10:45 ----O 0 0 0 ----E ----D ----E ----C 'works on fixed-length and dynamic arrays 'but if used on dynamic array, must ReDim before re-using Erase MyArray() ----E ----H ----E ----T Randomly shuffle an array Visual Basic arrays Top100 random shuffle 2005-02-18 11:10:56 ----O 0 0 0 ----E ----D ----E ----C 'assumes MyArray already exists and is filled with data 'if you know the upper/lower limits of the array, just use them 'set temp variable to same type as MyArray Dim i As Long, j As Long, temp As Variant Randomize For i = LBound(MyArray) To UBound(MyArray) 'randomly pick an element of the array to swap with element i j = Int((UBound(MyArray)) * Rnd + 1) temp = MyArray(i) MyArray(i) = MyArray(j) MyArray(j) = temp Next i ----E ----H ----E ----T Remove element from array by content Visual Basic arrays Top100 remove delete 2005-02-02 15:14:27 ----O 0 0 0 ----E ----D ----E ----C 'removes only the first instance of the array that matches the value 'if you know the upper/lower limits of the array, just use them 'TestValue and MyArray should have the same Type Dim i as Long, j as Long For i = LBound(MyArray) to UBound(MyArray) -1 If MyArray(i) = TestValue Then For j = i to UBound(MyArray)-1 MyArray(j) = MyArray(j+1) Next j Exit For End if Next i ----E ----H ----E ----T Remove element from array by position Visual Basic arrays Top100 2005-02-18 11:11:28 ----O 0 0 0 ----E ----D ----E ----C '1. order is not preserved In this approach, but very simple MyArray(ItemToBeDeleted) = MyArray(UBound(MyArray)) ReDim Preserve MyArray(UBound(MyArray)-1) '2. order Is maintained Dim i As Long, N As Long 'assumes N is the position In MyArray to remove For i = N To UBound(MyArray)-1 MyArray(i) = MyArray(i+1) Next i ReDim Preserve MyArray(UBound(MyArray)-1) ----E ----H ----E ----T Search an array Visual Basic arrays Top100 2005-02-02 15:19:42 ----O 0 0 0 ----E ----D ----E ----C 'search for first occurrence of TestValue in MyArray 'if you know the upper/lower limits of the array, just use them 'TestValue and MyArray should have the same type Dim TestValue as string TestValue = "searchstring" For i = lbound(MyArray) to ubound(MyArray) If MyArray(i) = TestValue then 'value found, do something Exit For 'stop searching End if next i 'search all elements of MyArray for TestValue 'if you know the upper/lower limits of the array, just use them 'TestValue and MyArray should have the same type Dim TestValue as string TestValue = "searchstring" For i = lbound(MyArray) to ubound(MyArray) If MyArray(i) = TestValue then 'value found, do something, then continue searching End if next i ----E ----H ----E ----T Write an entire array into a file #1 Visual Basic arrays write, array, text file 2005-01-24 21:58:22 ----O 0 0 0 ----E ----D ----E ----C 'assumes MyArray exists Open "filename.txt" for Binary as #1 Put #1, MyArray Close #1 ----E ----H ----E ----T Write an entire array into a file #2 Visual Basic arrays 2005-01-24 21:58:22 ----O 0 0 0 ----E ----D ----E ----C 'assumes MyArray exists Open "myfile.txt" For Output as #1 For i = 0 to UBound(MyArray) Print #1, MyArray(i) Next i Close #1 ----E ----H ----E ----T Copy image to clipboard Visual Basic clipboard Top100 2005-02-02 15:24:30 ----O 0 0 0 ----E ----D ----E ----C 'use picture property of form, picturebox, or image control ClipBoard.Clear ClipBoard.Setdata picture1.picture 'here's a second approach, using a picture from a .BMP file 'use picture with these extensions BMP, ICO, CUR, RLE, WMF, EMF, GIF, JPG ClipBoard.Clear ClipBoard.Setdata LoadPicture("filename.bmp") ----E ----H ----E ----T Copy selection to clipboard Visual Basic clipboard 2005-02-16 15:30:01 ----O 0 0 0 ----E ----D ----E ----C sub CopyToClipboard() Clipboard.Clear If txtVisible.SelLength = 0 Then Clipboard.SetText txtVisible.Text Else Clipboard.SetText txtVisible.SelText End If end sub ----E ----H ----E ----T Copy text to clipboard Visual Basic Clipboard Top100 2005-02-02 15:24:44 ----O 0 0 0 ----E ----D ----E ----C 'be sure to clear the clipboard first Clipboard.Clear Clipboard.SetText MyString ----E ----H ----E ----T All - automatically highlight content on focus Visual Basic controls Top100 2005-02-18 11:11:59 ----O 0 0 0 ----E ----D ----E ----C Sub SelectAll() 'Put this in the GotFocus event of a textbox Me.ActiveControl.SelStart = 0 Me.ActiveControl.SelLength = Len(Me.ActiveControl.Text) End Sub ----E ----H ----E ----T All - capture any key Visual Basic controls Top100 ascii keycode 2005-02-03 13:03:27 ----O 0 0 0 ----E ----D ----E ----C 'in the KeyPress event of any control If KeyAscii = vbKeyReturn Then 'KeyAscii does not recognize all keys, only those with Ascii equivalents 'this example finds the Enter Key (Ascii code 13) 'other key/ascii codes that KeyPress recognizes include: 'vbKeySpace (32) vbKeyBack (8) vbKeyTab (9) 'use KeyUp / KeyDown events to recognize other keys which do not 'have Ascii equivalents arrows, function keys, MSGBox "Enter was pressed!" 'after doing something, set KeyAscii to zero to prevent VB from doing anything else KeyAscii = 0 End If 'this is the same as using character code constants If KeyAscii = 13 then MSGBox "Enter was pressed" End If 'KeyCode represents the physical key that is pressed/released (all keys except TAB) 'in the KeyUp events If KeyCode = vbKeyReturn Then MSGBox "Enter key was released" End If 'in the KeyDown events If KeyCode = vbKeyReturn Then MSGBox "Enter key was pressed" End If 'other useful KeyCode constants include: 'vbKeyLButton vbKeyRButton 'vbKeyReturn 'vbKeyShift 'vbKeyControl 'vbKeyEscape 'vbKeySpace 'vbKeyUp vbKeyDown vbKeyLeft vbKeyRight 'vbKeyPageUp vbKeyPageDown vbKeyEnd vbKeyHome 'vbKeyF1 - vbKey16 ----E ----H ----E ----T All - force lower case as keys are entered Visual Basic controls Top100 2005-02-03 12:52:26 ----O 0 0 0 ----E ----D ----E ----C 'in the KeyPress event of the control 'force lower case KeyAscii = Asc(LCase(Chr(KeyAscii))) 'force upper case KeyAscii = Asc(UCase(Chr(KeyAscii))) ----E ----H ----E ----T All - use Enter key to move to next control in TAB sequence Visual Basic controls 2005-02-16 13:45:43 ----O 0 0 0 ----E ----D ----E ----C 'in the key-press event If KeyAscii = 13 Then SendKeys "{Tab}" KeyAscii = 0 End If ----E ----H ----E ----T Checkbox - set with Boolean value Visual Basic controls 2005-02-09 14:29:04 ----O 0 0 0 ----E ----D ----E ----C 'vbChecked = 1 'vbUnChecked = 0 'Abs(True) = 1 'Abs(False) = 0 checkbox1.checked = vbChecked checkbox1.checked = Abs(True) checkbox1.checked = vbUnChecked checkbox1.checked = Abs(False) ----E ----H ----E ----T ComboBox - change width of drop down part Visual Basic controls 2005-02-16 15:07:23 ----O 0 0 0 ----E ----D ----E ----C Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Public Sub SetComboWidth(X As ComboBox, iWidth As Long) SendMessage X.hwnd, &H160, iWidth, 0& End Sub ----E ----H ----E ----T ComboBox - create MRU for dropdown list Visual Basic controls Top100 2005-02-06 21:44:32 ----O 0 0 0 ----E ----D ----E ----C 'this code tracks the last 10 manual entries into a combolist 'put this in the Keypress event of the combolist If KeyAscii = 13 then 'this takes effect only when Enter is pressed 'check to see if the entry already exists in the list 'use of LCase make the code case-insensitive Dim i As Long, Found As Boolean For i = 0 To cmbList.ListCount - 1 If LCase$(cmbList.Text) = LCase$(cmbList.List(i)) Then Found = True Exit For End If Next i 'if the text entry is a new item, add it to the top of the list If Found = False Then cmbList.AddItem cmbList.Text, 0 'limit the list to 10 items (drop off bottom item on the list) If cmbList.ListCount > 10 Then cmbList.RemoveItem (10) 'save the list to a text file if a new item is entered If Found = True Then Open "searchlist.txt" for Output As #1 For i = 0 to cmbList.Listcount -1 Print #1, cmbList.list(i) Next i Close #1 End If End If ----E ----H ----E ----T ComboBox - remove multiple selected items Visual Basic controls 2005-02-18 11:12:31 ----O 0 0 0 ----E ----D ----E ----C 'To delete multiple selected items, loop backwards To avoid problems Dim iCount As Long For iCount = List1.ListCount - 1 To 0 Step -1 If List1.Selected(iCount) = True Then List1.RemoveItem iCount Next iCount ----E ----H ----E ----T Common dialog - multiple files from common dialog Visual Basic controls 2005-01-27 15:26:27 ----O 0 0 0 ----E ----D ----E ----C Private Sub cmdOpen_Click() Dim sFileNames() As String Dim iCount As Integer cd.Filter = "All Files|*.*" cd.Flags = cdlOFNAllowMultiselect cd.ShowOpen If cd.FileName <> "" Then sFileNames = Split(cd.FileName, Chr(32)) For iCount = LBound(sFileNames) To UBound(sFileNames) MsgBox sFileNames(iCount), vbInformation Next End If End Sub ----E ----H ----E ----T Common dialog - SaveAs code Visual Basic controls 2005-02-06 17:22:04 ----O 0 0 0 ----E ----D ----E ----C On Error GoTo ExitmnuInOpen 'open dialog box to get new FileName CommonDialog1.Flags = cdlOFNHideReadOnly CommonDialog1.InitDir = App.Path CommonDialog1.FileName = "*.txt" CommonDialog1.DefaultExt = "txt" CommonDialog1.Filter = "Text Files (*.txt)|*.txt" CommonDialog1.DialogTitle = "Save As" CommonDialog1.ShowOpen If CommonDialog1.FileName <> "*.txt" Then FileName = CommonDialog1.FileName If FileExists(FileName) Then Kill FileName Open FileName For Binary As #1 Put #1, , txtVisible.Text Close #1 ' StatusBar1.SimpleText = FileName StatusBar1.Panels(1).Text = FileName txtHidden.Text = txtVisible.Text End If ExitmnuInOpen: ----E ----H ----E ----T File System Controls - how to synchronize Visual Basic controls 2005-02-16 15:30:45 ----O 0 0 0 ----E ----D ----E ----C 'use the 3 intrinsic list boxes: DriveListBox, DirListBox, FileListBox '============= 'DriveListBox code - Change Event Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub '============= 'DirListBox code - Change Event Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub ----E ----H ----E ----T Imagelist - add images at run time Visual Basic controls Top100 2005-02-03 15:20:09 ----O 0 0 0 ----E ----D ----E ----C Dim KeyText as String KeyText = "IconName" 'use this name in code to reference the icon ImageList1.ListImages.Add , KeyText, LoadPicture("myicon.ico") ----E ----H ----E ----T Listbox - use API for fast search Visual Basic controls 2005-02-16 15:09:23 ----O 0 0 0 ----E ----D ----E ----C Private Declare Function SendMessageString Lib "user32" _ Alias "SendMessageA" _ (ByVal hwnd As Long, _ ByVal wMsg As Long, _ ByVal wParam As Long, _ ByVal lParam As String) As Long Private Const LB_FINDSTRING = &H18F Private Const LB_FINDSTRINGEXACT = &H1A2 Dim iIndex As Long Dim FindString As String FindString = "FindThis" iIndex = SendMessageString(List1.hwnd, LB_FINDSTRINGEXACT, -1, FindString) If iIndex > -1 Then List1.ListIndex = iIndex ----E ----H ----E ----T Listbox - use API to select all Visual Basic controls 2005-02-09 14:46:18 ----O 0 0 0 ----E ----D ----E ----C Private Declare Function SendMessageString Lib "user32" _ Alias "SendMessageA" _ (ByVal hwnd As Long, _ ByVal wMsg As Long, _ ByVal wParam As Long, _ ByVal lParam As String) As Long Const WM_USER = &H400 Const LB_SETSEL = (WM_USER + 6) iReturn = SendMessage(lst.Wnd, LB_SETSEL, bState, -1 ----E ----H ----E ----T ListView - autosize column widths Visual Basic controls 2005-02-09 12:55:16 ----O 0 0 0 ----E ----D ----E ----C Public Declare Function SendMessage Lib "user32" _ Alias "SendMessageA" (ByVal hwnd As Long, _ ByVal wMsg As Long, _ ByVal wParam As Long, _ lParam As Any) As Long Const LVM_SETCOLUMNWIDTH = &H1000 + 30 Const LVSCW_AUTOSIZE = -1 Const LVSCW_AUTOSIZE_USEHEADER = -2 'LV is the ListView control Dim col As Long For col = 0 To LV.ColumnHeaders.Count -1 SendMessage LV.hwnd, LVM_SETCOLUMNWIDTH, col, LVSCW_AUTOSIZE_USEHEADER Next col ----E ----H ----E ----T Optionbutton - determine which is selected Visual Basic controls 2005-02-09 14:31:31 ----O 0 0 0 ----E ----D ----E ----C Selected = Option(0).value * 0 + Option(1).value * 1 + Option(2).value * 2 'Or For i = 0 To n Selected = Option(i).value * i Next i ----E ----H ----E ----T Picturebox - remove image Visual Basic controls 2005-02-16 15:44:38 ----O 0 0 0 ----E ----D ----E ----C Picture1.LoadPicture() ----E ----H ----E ----T Richtextbox - find and replace Visual Basic controls Top100 2005-02-18 11:13:02 ----O 0 0 0 ----E ----D ----E ----C 'Each time called, finds next occurence of StringToFind Static S_Start As Long, StringToFind As String S_Start = RichTextBox1.Find(StringToFind, S_Start) If S_Start = -1 Then MsgBox "Not found" Else RichTextBox1.SetFocus S_Start = S_Start + Len(StringToFind) End If ----E ----H ----E ----T Richtextbox - first visible line/position of 1st char on the line Visual Basic controls Top100 2005-02-05 23:07:41 ----O 0 0 0 ----E ----D ----E ----C Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Public Const EM_LINEINDEX = &HBB Public Const EM_GETFIRSTVISIBLELINE = &HCE iTopLine = SendMessage(RichTextBox1.hwnd, EM_GETFIRSTVISIBLELINE, 0, 0)) iPositionofFirstCharOfTopLine = SendMessage(RichTextBox1.hWnd, EM_LINEINDEX, iTopLine, 0&) ----E ----H ----E ----T Richtextbox - merge contents of two richtextboxes Visual Basic controls Top100 2005-02-16 16:02:59 ----O 0 0 0 ----E ----D ----E ----C 'put contents of richtextboxes 1 & 2 into a third richtextbox RichTextBox1.SelStart = 0 RichTextBox1.SelLength = Len(RichTextBox1.Text) RichTextBox2.SelStart = 0 RichTextBox2.SelLength = Len(RichTextBox2.Text) RichTextBox3.SelStart = 0 RichTextBox3.SelLength = Len(RichTextBox3.Text) RichTextBox3.SelRTF = RichTextBox1.SelRTF RichTextBox3.SelStart = Len(RichTextBox3.Text) RichTextBox3.SelLength = 0 RichTextBox3.SelText = vbCrLf RichTextBox3.SelStart = Len(RichTextBox3.Text) RichTextBox3.SelLength = 0 RichTextBox3.SelRTF = RichTextBox2.SelRTF RichTextBox1.SelStart = 0 RichTextBox1.SelLength = 0 RichTextBox2.SelStart = 0 RichTextBox2.SelLength = 0 ----E ----H ----E ----T Richtextbox - prevent flicker of richtextbox during reposition Visual Basic controls Top100 2005-02-03 10:31:19 ----O 0 0 0 ----E ----D ----E ----C 'this is more of a technique rather than code 'put richtextbox content in a hidden richtextbox RichTextBoxHidden = RichTextBoxVisible 'then make all changes to the hidden richtextbox 'then put hidden content into visible box RichTextBoxVisible = RichTextBoxHidden ----E ----H ----E ----T Richtextbox - word wrap Visual Basic controls Top100 2005-02-16 16:02:46 ----O 0 0 0 ----E ----D ----E ----C 'On - set rightmargin very small txtCode.RightMargin = txtCode.Width - 25 '0ff - set right margin very wide (1001 is arbitrary width) txtCode.RightMargin = 1001 * frmMain.TextWidth("a") ----E ----H ----E ----T Textbox - automatically highlight content Visual Basic controls selection, textbox, highlight 2005-02-18 11:13:28 ----O 0 0 0 ----E ----D ----E ----C 'Put this in the GotFocus event text1.selstart = 0 text1.sellength = Len(text1.sellength) 'Or use this as a subroutine that all textboxes can call Me.ActiveControl.SelStart = 0 Me.ActiveControl.SelLength = Len(Me.ActiveControl.Text) ----E ----H The two lines of code must be in the order given. If you reverse the two lines of code it won't work properly ----E ----T Textbox - select all text on focus Visual Basic controls 2005-02-18 11:13:34 ----O 0 0 0 ----E ----D ----E ----C Sub SelectAll() 'Put this in the GotFocus event of a textbox Me.ActiveControl.SelStart = 0 Me.ActiveControl.SelLength = Len(Me.ActiveControl.Text) End Sub 'this is an alternative for a specific textbox txtOut.SelStart = 0 txtOut.SelLength = Len(txtOut.Text) ----E ----H ----E ----T Textbox - undo (API) Visual Basic controls 2005-02-16 14:07:28 ----O 0 0 0 ----E ----D ----E ----C Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Const WM_USER = &H400 Const EM_UNDO = WM_USER + 23 iResult = SendMessage(myControl.hWnd, EM_UNDO, 0,0) ----E ----H ----E ----T Textbox - use Enter as TAB Visual Basic controls enter, textbox 2005-02-18 11:13:49 ----O 0 0 0 ----E ----D ----E ----C 'put this in the textbox click event If KeyAscii = vbKeyEnter then KeyAscii = vbKeyTAB ----E ----H ----E ----T Timer - extend control to large intervals Visual Basic controls 2005-02-08 18:07:34 ----O 0 0 0 ----E ----D ----E ----C Sub Timer1_Timer() 'set Interval property to 60 = 1 minute 'Timer normally is good for about 1 minute Static iMinutes iMinutes = iMinutes + 1 If iMinutes Mod 5 <> 0 Then Exit Sub '5 is the extended number of minutes 'you reached the extended time - do something MSGBox "The timer hit 5 minutes" 'reset the timer to begin counting again iMinutes = 0 End Sub ----E ----H ----E ----T Toolbar - responding to button selection Visual Basic controls Top100 2005-01-31 11:37:45 ----O 0 0 0 ----E ----D ----E ----C Private Sub Toolbar1_ButtonClick(ByVal Button As MSComctlLib.Button) Select Case Button.Key Case "selectfolder" If ToolBar.Buttons("selectfolder").Value = tbrPressed Then 'Do something End If Case "copylist" 'Do a copy thing Case "email" 'Do an email thing End Select End Sub ----E ----H ----E ----T Toolbar - responding to menu selection Visual Basic controls 2005-01-27 12:18:27 ----O 0 0 0 ----E ----D ----E ----C Private Sub Toolbar1_ButtonMenuClick(ByVal ButtonMenu As MSComctlLib.ButtonMenu) If ButtonMenu.Parent.Key = "game" Then 'Do something End If If ButtonMenu.Parent.Key = "speed" Then 'Do something else End If End Sub ----E ----H ----E ----T TreeView - set background color Visual Basic controls 2005-01-27 12:44:55 ----O 0 0 0 ----E ----D ----E ----C 'for setting treeview backcolor Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd _ As Long, ByVal nIndex As Long) As Long Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd _ As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Const GWL_STYLE = -16& Const TVM_SETBKCOLOR = 4381& Const TVS_HASLINES = 2& Dim lStyle As Long Dim TVNode As Node ' set the BackColor for every node For Each TVNode In TV.Nodes TVNode.BackColor = BackColor Next ' set the BackColor for the TreeView's window SendMessage TV.hWnd, TVM_SETBKCOLOR, 0, ByVal BackColor ' get the current style lStyle = GetWindowLong(TV.hWnd, GWL_STYLE) ' temporary hide lines SetWindowLong TV.hWnd, GWL_STYLE, lStyle And (Not TVS_HASLINES) ' redraw lines SetWindowLong TV.hWnd, GWL_STYLE, lStyle '============= Dim hwndTV As Long Dim Style As Long hwndTV = TV1.hWnd 'Change the background Call SendMessageLong(hwndTV, TVM_SETBKCOLOR, 0, clrref) 'reset the treeview style so the 'tree lines appear properly Style = GetWindowLong(TV1.hWnd, GWL_STYLE) 'if the treeview has lines, temporarily 'remove them so the back repaints to the 'selected colour, then restore If Style And TVS_HASLINES Then Call SetWindowLong(hwndTV, GWL_STYLE, Style Xor TVS_HASLINES) Call SetWindowLong(hwndTV, GWL_STYLE, Style) End If ----E ----H ----E ----T TreeView - traverse the tree Visual Basic controls Top100 2005-02-15 08:53:35 ----O 0 0 0 ----E ----D ----E ----C Public Sub TraverseTree(objNode As Node, Level) 'recursive Dim objSiblingNode As Node Set objSiblingNode = objNode Do 'optional - txtResults = txtResults & Level & " .. " & objSiblingNode.Text & Chr(13) & Chr(10) If Not objSiblingNode.Child Is Nothing Then Call TraverseTree(objSiblingNode.Child, Level + 1) Set objSiblingNode = objSiblingNode.Next Loop While Not objSiblingNode Is Nothing End Sub ----E ----H ----E ----T Time - elapsed time between 2 dates Visual Basic date-time Top100 2005-02-09 20:40:42 ----O 0 0 0 ----E ----D ----E ----C 'elapsed Time between dates (D2 - D1) 'subtracting 2 dates give a Single which Is the number of days Dim D1 As Date Dim D2 As Date DDays = D2 - D1 'calculate all other values As a Function of DDays DYears = DDays / 365 DMonths = DDays / 365 / 12 DHours = DDays * 24 DMinutes = DDays * 24 * 60 DSeconds = DDays * 24 * 60 * 60 '========================================== 'alternate approach 'get difference between to Dates, in an internval of your choice Dim D1 As Date Dim D2 As Date Dim Interval as String Interval = yyyy | q | m | y | d | w | ww | h | n | s Year | Quarter | Month | Day of year | Day | Weekday | Week | Hour | Minute | Second Dim Result Result = DateDiff("d", D1, D2) 'days between the dates Result = DateDiff("w", D1, D2) 'weekdays between the dates Result = DateDiff("h", D1, D2) 'hours between the dates 'the VB function 'DatePart' lets you extract just a part of the date 'the VB function 'DateAdd' lets you add an interval(s) to a date ----E ----H ----E ----T Timer - milliseconds between 2 events Visual Basic date-time Top100 2005-02-09 20:40:36 ----O 0 0 0 ----E ----D ----E ----C 'API For Time keeping Private Declare Function GetTickCount Lib "kernel32" () As Long 'use this throughout the program to time between two events Dim iStart As Long, iEnd As Long, Result As String iStart = GetTickCount iEnd = GetTickCount Result = FormatNumber((iEnd - iStart) / 1000, 3) & " seconds " ----E ----H ----E ----T Determine if file is binary Visual Basic files binary 2005-02-16 15:31:29 ----O 0 0 0 ----E ----D ----E ----C function IsBinary() As Boolean Dim i As Long, Char As String * 1, j As Long Open MergePathData(lstFiles.Path, lstFiles.List(lstFiles.ListIndex)) For Binary As #1 IsBinary = False If LOF(1) > 0 Then j = 10 If LOF(1) < j Then j = LOF(1) For i = 1 To j Get #1, i, Char Select Case Asc(Char) Case 9, 10, 13 'accept TAB, vbCRLF. no action Case 0 To 31, 128 To 255 IsBinary = True Exit For End Select Next i End If Close #1 end function ----E ----H ----E ----T Display only text conten of binary file Visual Basic files binary 2005-02-16 15:31:17 ----O 0 0 0 ----E ----D ----E ----C sub DisplayStrippedBinaryFile(X As String) Dim temp As String, i As Long, temp2 As String, C As String, j As Long Screen.MousePointer = vbHourglass txtFileViewer.Text = " ... loading binary file ... please wait! " DoEvents Open X For Binary As #1 temp = Input(LOF(1), #1) Close #1 For i = 1 To Len(temp) C = Mid$(temp, i, 1) Select Case C Case "A" To "Z", "a" To "z", "0" To "9", " ", "." temp2 = temp2 & C j = j + 1 If j Mod 50 = 0 Then temp2 = temp2 & vbCrLf DoEvents End If End Select Next i txtFileViewer.Text = "" & vbCrLf & temp2 Screen.MousePointer = vbDefault end sub ----E ----H ----E ----T Open file with default Windows application Visual Basic files binary open, default, file, application 2005-01-09 00:27:13 ----O 0 0 0 ----E ----D ----E ----C Public Declare Function ShellExecute Lib "SHELL32.DLL" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Public Const SW_ShowNormal = 1 'set the variable temp to the file type you want to open 'the OS will open that file with the application set to handle the extension of that file Dim iReturn As Long, temp As String temp = "myfile.doc" iReturn = ShellExecute(frmMain.hwnd, "Open", temp, vbNullString, App.Path, SW_ShowNormal) ----E ----H ----E ----T Read/write data to a specific location within the file Visual Basic files binary Top100 2005-02-16 15:31:44 ----O 0 0 0 ----E ----D ----E ----C 'read 20 bytes starting at position 100 Dim InputString as String * 20 Open FileName for Binary As #1 Get #1, 100, InputString Close #1 'or read as a byte array Dim InputString(20) as Byte Open FileName for Binary As #1 Get #1, 100, InputString Close #1 'write 10 bytes to position 50 OutputString = "0123456789" Open FileName for Binary As #1 Put #1, 50, OutputString Close #1 ----E ----H ----E ----T Read/write entire file at once Visual Basic files binary Top100 2005-02-03 15:12:03 ----O 0 0 0 ----E ----D ----E ----C 'puts the entire file into a Byte array 'for character by character action Open FileName For Binary As #1 ReDim MyByteArray(LOF(1)-1) As Byte Get #1, , MyByteArray Close #1 ----E ----H ----E ----T View in hex format Visual Basic files binary Top100 2005-02-02 15:43:59 ----O 0 0 0 ----E ----D ----E ----C Sub HexView(FileName as String) 'put contents of file into textbox1 Dim temp As String, temp2 as String Dim i As Long, j As Long Dim leader As String Dim HexText As String Dim AsciiText As String Dim Char As String 'read the file into a string Open filename for input as #1 temp2= Input (Lof(1),#1) Close #1 'create hex string If Len(temp2) > 0 Then For i = 1 To Len(temp2) Step 8 leader = String$((6 - Len(Hex(i - 1))), "0") & Hex(i - 1) & " " HexText = "" For j = 0 To 7 If i + j > Len(temp2) Then HexText = HexText & Space$((8 - j) * 3) Exit For End If Char = Format$(Hex(Asc(Mid$(temp2, i + j, 1))), "00") If Len(Char) = 1 Then Char = "0" & Char HexText = HexText & Char & " " Next j AsciiText = Mid$(temp2, i, 8) AsciiText = Replace(AsciiText, Chr(9), ".") AsciiText = Replace(AsciiText, Chr(10), ".") AsciiText = Replace(AsciiText, Chr(13), ".") temp = temp & leader & HexText & " " & AsciiText & vbCrLf Next i Else temp = vbCrLf End If temp = Mid$(temp, 1, Len(temp) - 2) text1.text = temp End Sub ----E ----H ----E ----T Open text file with default text app Visual Basic files text 2005-02-16 15:32:01 ----O 0 0 0 ----E ----D ----E ----C Dim temp As String, i As Long temp = "gbsimplecamconfig.txt" i = ShellExecute(frmMain.hwnd, "Open", temp, vbNullString, App.Path, SW_ShowNormal) ----E ----H ----E ----T Open text file with Notepad Visual Basic files text 2005-01-24 22:08:28 ----O 0 0 0 ----E ----D ----E ----C Shell "notepad " & AddressFileName, vbNormalFocus ----E ----H ----E ----T Read text file all at one time Visual Basic files text Top100 2005-02-02 15:26:48 ----O 0 0 0 ----E ----D ----E ----C 'read an entire text file into a string Dim temp as String Open filename for input as #1 temp = Input (Lof(1),#1) Close #1 ----E ----H ----E ----T Read text file into a string Visual Basic files text open, text, string 2005-02-16 15:32:16 ----O 0 0 0 ----E ----D ----E ----C Dim InString as String Open "filename.txt" For Binary As #1 InString = Input(LOF(1), #1) Close ----E ----H ----E ----T Read text file into an array #1 Visual Basic files text open, text, file, array 2005-02-16 15:32:22 ----O 0 0 0 ----E ----D ----E ----C 'first read the file into a string - includes the line feed/carriage control characters Dim InString as String, MyArray as Variant Open "filename.txt" For Binary As #1 InString = Input(LOF(1), #1) Close 'now split the string MyArray = Split(InString, vbCRLF, -1) ----E ----H ----E ----T Read text file into an array #2 Visual Basic files text 2005-02-16 15:32:28 ----O 0 0 0 ----E ----D ----E ----C 'puts content into array starting at position zero 'if you know the number of lines in advance, you won't have to use REDIM Preserve Dim temp as String, MyArray as Variant Open "filename.txt" For Input as #1 While Not EOF(1) REDIM Preserve MyArray(i) Line Input #1, MyArray(i) i = i +1 Wend Close ----E ----H ----E ----T Read text file one character at a time Visual Basic files text 2005-02-16 15:32:34 ----O 0 0 0 ----E ----D ----E ----C Dim Char as String * 1 Open "filename.txt" For Input As #1 While Not EOF(1) Char = Input$(1,#1) Wend ----E ----H ----E ----T Read text file one line at a time Visual Basic files text Top100 2005-02-16 15:33:43 ----O 0 0 0 ----E ----D ----E ----C Dim NewLine as String Open "filename.txt" For Input As #1 While Not EOF(1) Line Input #1, NewLine 'do something with NewLine Wend ----E ----H ----E ----T Remove a character from a text file Visual Basic files text character, remove 2005-01-24 22:04:01 ----O 0 0 0 ----E ----D ----E ----C 'first read text file into string Dim InString as String Open "filename.txt" For Binary As #1 InString = Input(LOF(1), #1) Close 'then replace specified character(s) with an empty string "" InString = Replace(Instring, CharToRemove, "") 'finally put string back into the file Open "filename.txt" For Output as #1 Put #1, InString Close ----E ----H ----E ----T Save array to file (fast) Visual Basic files text 2005-02-18 11:15:27 ----O 0 0 0 ----E ----D ----E ----C 'MyArray is a string array filled with text 'this code avoids having to cycle through the string array Open "myfile.txt" For Output As #1 Print #1, Join(MyArray, vbcrlf) Close #1 ----E ----H ----E ----T View text file content Visual Basic files text Top100 2005-02-02 15:27:41 ----O 0 0 0 ----E ----D ----E ----C 'read an entire text file into a multiline textbox Dim temp as String Open filename for input as #1 textbox1.text = Input (Lof(1),#1) Close #1 ----E ----H ----E ----T Wordwrap Visual Basic files text 2005-02-18 11:15:50 ----O 0 0 0 ----E ----D ----E ----C '1. one approach Sub WordWrap() 'word wrap is on when the margin Is arbitrarily very large If mnuWordWrap.Checked = True Then 'on txtIn.RightMargin = txtIn.Width - 25 Else 'off txtIn.RightMargin = 1001 * frmChat.TextWidth("a") End If End Sub '============================ '2. another approach Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, ByVal wMsg As Long, _ ByVal wParam As Long, lParam As Any) As Long Const WM_USER = &H400 Const EM_SETTARGETDEVICE = (WM_USER + 72) 'wordwrap SendMessageLong frmMain.rtfTest, EM_SETTARGETDEVICE, 0, 0 'default SendMessageLong frmMain.rtfTest, EM_SETTARGETDEVICE, 0, 1 ----E ----H ----E ----T Backup and Restore a file Visual Basic files 2005-01-24 22:10:59 ----O 0 0 0 ----E ----D ----E ----C 'backup If MsgBox("Are you sure?", vbOKCancel + vbQuestion, "Backup Data") = vbOK Then FileCopy InfoFileName, InfoFileName & ".old" End If 'restore If MsgBox("Are you sure?", vbOKCancel + vbQuestion, "Restore Data") = vbOK Then FileCopy InfoFileName & ".old", InfoFileName End If ----E ----H ----E ----T Create full pathname Visual Basic files Top100 path 2005-02-02 15:30:12 ----O 0 0 0 ----E ----D ----E ----C 'add path information and file name, including \ separator if needed Function MergePathData(thePath As String, theFileName As String) As String Select Case Right$(thePath, 1) Case "\": MergePathData = thePath & theFileName Case Else : MergePathData = thePath & "\" & theFileName End Select End Function ----E ----H ----E ----T Delete file to recycle bin Visual Basic files 2005-02-09 12:39:10 ----O 0 0 0 ----E ----D ----E ----C Private Type SHFILEOPTSTRUCT hWnd As Long wFunc As Long pFrom As String pTo As String fFlags As Integer fAnyOperationsAborted As Long hNameMappings As Long lpszProgressTitle As Long End Type Private Declare Function SHFileOperation Lib "Shell32.dll" _ Alias "SHFileOperationA" (lpFileOp As SHFILEOPTSTRUCT) As Long Private Const FO_DELETE = &H3 Private Const FOF_ALLOWUNDO = &H40 Public Sub DeleteFileToRecycleBin(Filename As String) Dim fop As SHFILEOPTSTRUCT fop.wFunc = FO_DELETE fop.pFrom = Filename fop.fFlags = FOF_ALLOWUNDO SHFileOperation fop End Sub ----E ----H ----E ----T Extract file name from full path Visual Basic files Top100 path title 2005-02-02 15:30:41 ----O 0 0 0 ----E ----D ----E ----C 'assumes FullPath is a string containing the complete path of a valid file Dim FileName as String FileName = mid$(FullPath,InstrRev(FullPath,"\")+1) ----E ----H ----E ----T File exists Visual Basic files Top100 exists 2005-02-06 18:17:53 ----O 0 0 0 ----E ----D ----E ----C Function FileExists(filename) as Boolean If Dir(filename) <> "" then FileExists = True End If '======================= 'alternate approach using FileSystemObject (add reference to project to use) Dim fso As New FileSystemObject 'file exists If fso.FileExists("C:\Files\file.txt") Then MsgBox "File Exists!" End if ----E ----H ----E ----T File properties (size/date/attributes) Visual Basic files Top100 2005-02-09 20:45:27 ----O 0 0 0 ----E ----D ----E ----C 'file length (Bytes) - use full path name unless file is in current drive/directory Dim iLength as long iLength = FileLen("c:\filename.exe") 'date/time of a file Dim temp as Variant Dim FileName as string FileName = "c:\data\test.txt" temp = FileDateTime (FileName) 'attributes of a file Function FileProperties( FileName as String, RO as Boolean, Hidden as Boolean, System as Boolean, Directory as Boolean, Archive as Boolean) Dim iResult as long iResult = GetAttr (FileName) RO = iResult AND vbReadOnly Hidden = iResult AND vbHidden System = iResult AND vbSystem Directory = iResult AND vbDirectory Archive = iResult AND vbArchive FileProperties = iResult End Function 'set the attributes of a file (file cannot be open) SetAttr "c:\test.txt", vbNormal + vbReadOnly + vbHidden + vbSystem + vbArchive ----E ----H ----E ----T FileSave Visual Basic files 2005-02-16 15:36:11 ----O 0 0 0 ----E ----D ----E ----C Sub mnuFileSave_Click() If DataChanged = False Then Exit Sub If MsgBox("Are you sure?", vbOKCancel, "Save Changes to Equations") = vbCancel Then Exit Sub 'save data to file (custom for each application) DataChanged = False end sub ----E ----H ----E ----T Get unique temporary file name Visual Basic files 2005-01-27 12:38:13 ----O 0 0 0 ----E ----D ----E ----C How to ... Get unique temporary file name Private Const MAX_FILENAME_LEN = 256 Private Const UNIQUE_NAME = &H0 Private Declare Function GetTempFileNameA Lib "kernel32" (ByVal _ lpszPath As String, ByVal lpPrefixString As String, ByVal wUnique _ As Long, ByVal lpTempFileName As St