87 Cunnings and tricks for Visual Basic.
Materials are kindly translated by Anton Minko
1. MANAGEMENT OF EVENTS
2. COMMENTING AND BLOCKS OF THE CODE
3. VALUES BY DEFAULT FOR UNESSENTIAL PARAMETERS
4. DO NOT CREATE ALIAS-НЫХ VARIABLES
5. THE CENTERING OF THE FORM ON THE SCREEN
6. DO NOT TAKE A GREAT INTEREST FAST CODE
7. NOT ALL PATTERNS ARE CREATED EQUALLY
8. ADJUSTMENT IN VB
9. HOW TO HIDE ALL WINDOWS OF THE PROJECT
10. STANDALONE LIBRARIES OF TYPES
11. OBJECT BROWSER FOR THE FINDING NOT DOCUMENTARY PROBABLY
12. THE ADDRESS OF THE VARIABLE
13. WHEN BENCHMARK’и PROGRAMS LAST DAY
14. APP.PATH CAN RETURN UNC-ПУТИ
15. ABOUT UNIVERSAL PARAMETERS OF FILES
16. TO REDUCE THE SIZE OF THE CODE, USING OPERATORS IIF AND SWITCH
17. ACCELERATE YOUR CODE USE CHOOSE
18. GOSUBS WORK SLOWLY IN PROGRAMS
19. «ARRAY» - HENCEFORTH THIS ERRONEOUS NAME FOR VARIABLES
20. START AUTOMATION MANAGER AS HIDDEN PROBLEMS
21. PROBLEMS WITH EMERGING MENUS
22. USE OF THE COLLECTION FOR SELECTION OF UNIQUE VALUES
23. CREATION « FAR OFF CONTROLLABLE » FORMS
24. RECORD of the CURRENT POSITION And the SIZE of the FORM BY MEANS OF SAVESETT
25. The EFFECTIVE UTILIZATION INTERNAL VB CONSTANTS
26. THE CORRECT TEST ON " FILE EXIST "
27. THE PROCEDURES WORKING WITH GROUPS KONTROLOV
28. IMPROVEMENT OF FIGURES
29. THE CIPHERED PASSWORDS
30. CAPITAL-LOWER CASE LETTER - ADVICE ON TRACKING THE REGISTER
31. TRACKING DOUBLE CLICK FOR BUTTONS ON
32. VOLUME OF THE CATALOGUE
33. THE USEFUL DISK INFORMATION
34. PRESSING CTRL FOR ALLOCATION SEPARATE ITEM IN LIST
35. TO CHOOSE ALL FILES ON THE MASK
36. THE NAME OF THE CURRENT COMPUTER IN WINDOWS 95/NT
37. HOW TO SHOW FONTS WHEN YOU CHOOSE THEM
38. INTERCEPTION RIGHT UNITS TREEVIEW
39. START VB BY MEANS OF MENU SENDTO
40. NEW " HOT BUTTONS " FOR VB
41. HOW TO RECEIVE USERID UNDER WINDOWS 95/NT
42. The CONCLUSION of the SAND-GLASS DURING DATA PROCESSING
43. The ESTIMATION of the TIME INTERVAL (in minutes) BETWEEN TWO DATES
44. WILL SUFFICE TO PRINT!
45. TO CHANGE VALUES OF TWO VARIABLES
46. FAST MULTINOMINALS
47. FORMATTING AND COPYING OF DISKETTES THROUGH FUNCTIONS API
48. CONSECUTIVE NUMBERS OF VERSIONS
49. ALIGNMENT BY the RIGHT EDGE
50. VAL DOES NOT WORK ON THE FORMATTED NUMBERS
51. CLEVER GENERATOR ID
52. CHANGE OF THE SIZE OF DROPPING OUT AREA ON COMBOBOXE
53. QUANTITY of FREE MEMORY By means of WIN32
54. HOW OLD ARE YOU?
55. ABOUT WHICH IT IS IMPOSSIBLE TO FORGET
56. TO CREATE HURRIEDLY the FILE BY MEANS OF FUNCTION ARRAY
57. TO FIND CHOSEN IN FILE OPTION BUTTONS
58. PACKING VALUES CHECK-BOX IN ONE VARIABLE OF TYPE INTEGER
59. CONDITIONAL COMPILATION OF THE CODE
60. TO REDUCE BLINKING DURING LOADING the FORM
61. TO HIDE the INDEX ON CURRENT RECORD in DBGride
62. USE POP-UP THE MENU IN THE WINDOW WITHOUT TITLE BAR
63. HOW TO LEARN DIVIDERS OF DATE AND TIME WITHOUT FUNCTIONS API
64. PREVENTION OF MISTAKES AT USE GETSETTING
65. DUPLICATION OF LINES OF THE CODE WITHOUT SYNTACTIC MISTAKES
66. The LABEL FOR LOADING LAST EQUIPMENT DESIGN In VB
67. HOW TO DEDUCE the SYMBOL "and" In LABEL
68. CREATION OF TIME FILES
69. MOUSE EVENTS DO NOT HAPPEN IF ENABLE IS ESTABLISHED IN FALSE
70. HOW TO DEDUCE THE POPUP MENU ON TEXT BOXES
71. TO ALIGN the FORM In view
72. CLEARING THE LINE OF UNNECESSARY SYMBOLS
73. CHECK of OBJECTS BY MEANS OF TYPENAME
74. ADDITION OF THE LINE IN TEXT BOX
75. CHECK OF ARGUMENTS IN FUNCTION VAL
76. LABELS FOR INTERNET
77. VIEWING MAINTENANCE HELP-ФАЙЛА
78. THE TASK OF BORDERS MDI OF THE FORM PRECISELY AS IN DESIGN-TIME
79. FAST SEARCH In the DATABASE
80. EASY TRACKING POSITION OF FOCUS
81. NOT CLOSED FORM
82. TO CHANGE PROPERTY TO THE WHOLE GROUP KONTROLOV
83. HOW SIMPLY TO FORMAT AND APPROXIMATE NUMBER
84. BE CAUTIOUS, HERE TO YOU NOT WITH!
85. TO USE BACKQUOTES INSTEAD OF APOSTROPHES
86. NEW VERSIONS OF THE PROGRAM ON THE NETWORK
87. TO CLOSE THE WINDOW OF THE PROGRAM AS IT DOES WINDOWS 95
<PICTURE>
1 MANAGEMENT OF EVENTS
Two problems can happen, when the confused user creeps COMBO by means of a mousy upwards and downwards, and then by pressing on Enter does the a choice. First, pressing on grey causes two events: Change and Click. Secondly, pressing on Enter moves focus to a following element of the form whereas pressing the button of the mouse does not cause similar effect (i.e. focus remains on COMBO). Therefore, if your code is placed in section of event Change on upwards/downwards (keyboard) will cause this event that you, naturally, do not want. On the contrary, if you place the code only in section of event Lost Focus and the user clicks the mouse on the choice focus will not leave from , and the user will behold the text which it has chosen the mouse, and to think, why it nothing occurs. The mentioned below decision « filters a market » events Click, generated pressing on keyboards, and compels to lose focus. In section Declarations of the form enter the following
' In VB3 it is necessary to change type of a flag on integer Dim bNoise as Boolean ' True means, that there is "noise" to which it is not necessary to react
And this code enter in section of event Form_Load:
bNoise = False
This code enter in event KeyDown Combo:
Private Sub cbTest_KeyDown (KeyCode As _ Integer, Shift As Integer) ' if the user uses arrows for driving under the list Combo/FONT> ' to ignore events Click If KeyCode = vbKeyDown Or KeyCode _ = vbKeyUp Then bNoise = True End Sub
This code is entered in event Click Combo:
Private Sub cbTest_Click () If bNoise Then ' Ignore Noise events ' (up or down arrow) bNoise = False Else ' To withdraw focus with SendKeys " {TAB} ", True End If End Sub
Now you need to write a code containing reaction to a choice of the user, and to bring it in section of event LostFocus Combo.
Back to the MAINTENANCE
<PICTURE>
2. COMMENTING AND BLOCKS OF THE CODE
VB5 Level: Beginning
VB 5.0 allows you the whole block of a code, and then also it is fast it. It is very useful at debugging when you do not need to execute a lot of operators, and at the same time you cannot remove them here and so simply for nothing. Meanwhile, the pair Comment/Uncomment is present only in тулбаре Edit which should be caused specially :-(. Quickly to cause тулбар Edit, click with the right button of the mouse on any тулбаре in VB, and choose then command Edit.
Back to the MAINTENANCE
<PICTURE>
3. VALUES BY DEFAULT FOR UNESSENTIAL PARAMETERS
VB5 Level: Beginning
If you ever программили on VB4 you probably used a powerful chesspiece under the name Unessential parameters (Optional parameters). VB5 has gone further away: now these parameters can be any type (not only Variants), and can appear in procedures Property. It is interesting, that you can set now for them value by default.
Property Get Value _ (Optional index As Long = 1) End Property
You can do now it without was earlier obligatory (and terribly brake) by test IsMissing:
Property Get Value _ (Optional index As Long) If IsMissing (index) Then index = 1... End Property
Back to the MAINTENANCE
<PICTURE>
4. DO NOT CREATE ALIAS-НЫХ VARIABLES
VB5 Level: Beginning
Never передавайтe a global variable as argument in procedure which also directly addresses to this variable from itself (what for??). If you on 100 % are assured, that follow this rule in your programs cross out option Assume No Aliasing in dialogue window Advanced Optimizations which is caused from item Compile of dialogue Project Properties (уф, I hope, it is clear). If the compiler native code knows, that these most alias-th variables are not present, it easy copies values of variables in шустрые registers ЦПУ, and copies their values back in RAM only at an output from procedure. It increases speed of execution of the compiled programs.
Back to the MAINTENANCE
<PICTURE>
5. THE CENTERING OF THE FORM ON THE SCREEN
VB5 Level: Beginning
Everyone know about small кодике, allowing you to align the form on the screen without dependence from the graphic sanction. Now you can reach the same result, only having appropriated value vbStartUpScreen (=2) new property StartUpPosition of the form (has appeared in version 5). You even can center the form concerning its parental window, having appropriated value vbStartUpOwner (=1). Assignment can be made in window Property of the corresponding form. When you align the form inside of a parental window, do not forget to add the second argument in method Show.
Form2. Show vbModal, Me
Back to the MAINTENANCE
<PICTURE>
6. DO NOT TAKE A GREAT INTEREST АВТООПТИМИЗИЦИЕЙ FAST CODE
VB5 Level: Beginning
If to look at options native code optimization at first and washs away to click on " Optimize for Fast Code ". However, strangely enough it can sound, the given action far not always guarantees expected effect. Аппликухи, optimized on high-speed execution, as a rule, are not optimized (sorry for a pun), and only receive a lot of memory at loading. It addresses for them slower loading that is especially appreciable by machines with insufficient quantity RAM, and as a result makes impression, that you аппликуха works more slowly, rather than optimized under a compact code. For the same reason, consults компилить аппликухи in P-code. In case of volumetric, UI-and базоданских аппликух, the prize from compilation in native-code at all will not move increase in the size аппликухи. In general, that precisely nobility, what compilation is necessary to you, юзайте VB Application Performance Explorer (APE) which lays on VB CD.
Back to the MAINTENANCE
<PICTURE>
7. NOT ALL PATTERNS ARE CREATED EQUALLY
VBA5 Level: Beginning
Unlike other products Office 97, patterns Word 97 contain business-application engine which is stored separately from documents, использюущих this engine. Books Excel based on patterns and presentations PowerPoint store in themselves patterns on the basis of which they are created. In practice, all documents Word consist from 2х VBA projects: the first project is created on the basis of the core (original, stored in Word) a pattern (all documents Word are based on patterns), and the second project belongs to document Word. On the other hand, books Excel and presentations PowerPoint created on patterns, contain only one VBA the project. Each file contains the own draft copy of an original pattern. The changes made in this pattern, do not mention the basic pattern stored the appendix.
Back to the MAINTENANCE
<PICTURE>
8. ADJUSTMENT ТУЛБАРОВ IN VB
VB5 Level: Beginning
Here some offers on adjustment IDE in VB5: To add bookmarks in тулбокс it is possible, having cluck with the right button of the mouse on button General (that on тулбоксе), and having chosen Add Tab. You can move and delete also bookmarks, and move icons контролов from one bookmark on another, using a usual method drag-and-drop. To pull out the button of any item of the menu on тулбар it is possible, having cluck with the right button on any тулбаре and having chosen item Customize. Pass to bookmark Commands, choose the necessary item of the menu in the right window, and drag it on тулбар. The first candidates on addition are items Project-References, Project-Properties, and Tools-Add Procedure. How to create absolutely new тулбар on вкладке Toolbars dialogue window Customize. After you have defined contents of the future тулбара, for addition of buttons on this тулбар use described by the paragraph above procedure. When at you on the screen dialogue window Customize is made active, click with the right button on any button тулбара and you can change figure of the button, create a divider, hide/show the text, etc.
Back to the MAINTENANCE
<PICTURE>
9. HOW TO HIDE ALL WINDOWS OF THE PROJECT
VB5 Level: Beginning
When you work with several пректами at once, it is possible to get confused in a heap thuja хучи windows from different projects. However, you can temporarily hide all the windows concerning the given project, having clicked under the pictogram of the project in window Project Explorer so that all the branches which are sticking out of it, have disappeared. Then the windows concerning the given project will be curtailed also all. This opportunity can be cancelled, having clicked on сответствующем квадратике on bookmark General in menu Tools-Options.
Back to the MAINTENANCE
<PICTURE>
10. STANDALONE LIBRARIES OF TYPES
VB4 16/32, VB5 (Enterprise Edition) Level: Intermediate
Koгда you create yours out-of-process OLE a server, VB builds in library of types of a server (companion type library) an EXE-file, not generating thus .TLB a file. However, if at you Enterprise Edition VB4 or VB5 having crossed out квадратик Remote Server File, you will force VB to create standalone билиотеку types. In VB5, this option is on вкладке Component dialogue window Properties menu Project.
Back to the MAINTENANCE
<PICTURE>
11. USE OBJECT BROWSER’a for a finding of not documentary opportunities
VB5 Level: Intermediate If to click with the right button of the mouse in right window Object Browser’а (there where members of classes are drawn) the contextual menu with command Show Hidden Members will jump out. If to click on this command, henceforth Object Browserбудет to show all hidden-properties and methods (together with classes) any library, and you can use it for more detailed research of libraries of objects. For example, in library VBA is hidden a class under the name _HiddenModule which includes many known functions VBA plus three not documentary: ObjPtr, StrPtr, and VarPtr. ObjPtr returns private area address of a copy of object, StrPtr returns the address first symbol in line, VarPtr returns the address of a variable or a descriptor of a line (string descriptor) if we have a case of a variable of type string.
Back to the MAINTENANCE
<PICTURE>
12. THE ADDRESS OF THE VARIABLE
VB4 16/32 Level: Advanced
In VB5 there is built in function VarPtr (see Advice « USE OBJECT BROWSER’a длЯнахождениЯ not documentary opportunities »), but this function is not present in VB4. Runtime library in VB4 includes this function, but before its use it is necessary to declare all over again:
#If Win16 Then Declare Function VarPtr Lib "VB40016.DLL" (variable As Any) As Long #Else Declare Function VarPtr Lib "VB40032.DLL" (variable As Any) As Long #End If
This function is useful by transfer of the user types (Type structure) in external procedure API, and in this type any from fields is the address of other variable or record.
Back to the MAINTENANCE
<PICTURE>
13. WHEN BENCHMARK’и (MEASUREMENTS of SPEED of WORK of the PROGRAM) LAST DAY
VB4 16/32, VB5 Level: Intermediate
Usually, programmers on VB measure speed of performance of a code by means of Timer functions. However, if your program should come to the end next day you should consider, that the value returned by function Timer, ресетится at midnight. If you will accept value to within one second, you can simplify your code by means of function Now.
Dim startTime As Date StartTime = Now ' the code to be benchmarked '... Print " elapsedSeconds = " and Format $ ((Now - startTime) * 86400, "#####")
Function Format $ for a rounding off of result up to the whole is required to you.
Back to the MAINTENANCE
<PICTURE>
14. APP.PATH CAN RETURN UNC-ПУТИ
VB5 Level: Intermediate
Unlike VB4, App. Path in VB5 can return a UNC-way, type " \\ server \programs\... ", depending on circumstances, from that as the program is started and it from VB IDE is started or compiled in an EXE-file. This feature can strongly spoil to you a life if you use App. Path for installation of the current catalogue at start of the program.
ChDrive App. Path ChDir App. Path
As ChDrive on is able to process UNC-ways, this code can cause a fatal mistake of time of performance, but можт to be protected by use On Error Resume Next. However this фикс will not protect you from all невзгод, able to occur. The best decision consists in that, чтоюы to give to the user most to enter the catalogue during execution of the program, then to write down the received way to the register or an INI-file. For more detailed инфы, see clause Q167167 in Microsoft Knowledge Base.
Back to the MAINTENANCE
<PICTURE>
15 ABOUT UNIVERSAL PARAMETERS OF FILES
VB4 16/32, VB5 Level: Advanced you can write uniform procedure for any types of a file with any type as argument, using parameter of type Variant. Inside of procedure, addressing of elements of a file occurs in the usual way:
' return the number of items Function ItemCount (anArray As Variant) As Long ItemCount = UBound (anArray) - LBound (anArray) + 1 ' the first element is ' anArray (LBound (anArray)) End Function
You can even запулить in procedure a multivariate file with any колическтвом measurements and to understand, how many at this file of measurements, it is necessary to make references to functions UBound and Lbound before occurrence of a mistake:
Function ItemCount (anArray As Variant) As Long Dim items As Long, i As Integer On Error Resume Next items = UBound (anArray) - LBound (anArray) + 1 For i = 2 to 999 items = items * (UBound (anArray, _ i) - LBound (anArray, i) + 1) If Err Then Exit For Next ItemCount = items End Function
Back to the MAINTENANCE
<PICTURE>
16. TO REDUCE THE SIZE OF THE CODE, USING OPERATORS IIF AND SWITCH
VB4 16/32, VB5 Level: Intermediate Often happens expedient to replace block If... Then... Else more compact function Iif:
' returns greater of two compared sizes maxValue = IIf (first> = second, first, second)
Switch - seldom used function, even in those numerous cases when it is more useful rather than the longest block If... ElseIf:
' it is necessary to learn, х полижительный, negative, or it is equal 0? Print Switch (x <0, "negative", x> 0, _ "positive", True, "Null")
Let's notice, that value of last check always True as three conditions are mutually excluding and superfluous.
Back to the MAINTENANCE
<PICTURE>
17. ACCELERATE YOUR CODE USE CHOOSE
VB3, VB4 16/32, VB5 Level: Beginning
You can use Choose there where it is possible to replace a file or to construct tables of results, at a stage of compilation (compile-time), instead of doing it at a stage of performance (run time). For example, if you should know values of factorials of numbers from 1 up to 10, try a following example (Choose makes a choice of a factorial from a set of available values всесто to calculate a factorial each time anew):
Function Factorial (number As Integer) _ As Long Factorial = Choose (number, 1, 2, 6, _ 24, 120, 720, 5040, 40320, _ 362880, 3628800) End Function
Back to the MAINTENANCE
<PICTURE>
18. GOSUBS WORK SLOWLY IN ОТКОМПИЛИРОВАННЫХ PROGRAMS
VB5 Level: Intermediate
As use GoSubs concerns to not structured style of programming many programmers try to avoid it. If you compile yours VB5 аппликуху in native code, you will have one more reason to avoid this operator as calls through GoSubs can occur five times more slowly, than calls of usual procedure or function.
Back to the MAINTENANCE
<PICTURE>
19. «ARRAY» - HENCEFORTH THIS ERRONEOUS NAME FOR VARIABLES
VB5 Level: Intermediate
If you, as well as I, often use a name "array" for variables, you should reconsider your code at its carry under VB5. This word is now reserved (reserved keyword) and cannot be used as a name of a variable. You can easily alter your code by means of command Replace in IDE VB5, do not forget thus черкнуть " Find whole words only ".
Back to the MAINTENANCE
<PICTURE>
20. START AUTOMATION MANAGER AS HIDDEN PROBLEMS
VB4 16/32, VB5 Enterprise Edition Level: Advanced
If you мспользуете OLE Remote Automation, you should start in advance Automation Manager on a server before there will be the first OLE remote communication. By default, this appendix visible, but you can hide it, that it not мозолило eyes on таскбаре Чикаги. For this purpose create a label for Automation Manager which would include in a command line the switch/Hidden: C: \Windows \System \AutMgr32.Exe/Hidden On the other hand, you can change value of a corresponding key in the register. For fuller инфы, see Clause Q138067 in the Microsoft Knowledge Base.
Back to the MAINTENANCE
<PICTURE>
21. PROBLEMS WITH EMERGING MENUS
VB4 16/32, VB5 Level: Advanced
If you use emerging menus (popup menus) in your programs be afraid of a bug which is available in VB4 16/32 and VB5. If you have two forms and one of them causes the second modal through the emerging menu from this the second modal you cannot cause any emerging menu, how many them on it was. That пофиксить this business, use the timer on the first form. Instead of display фторой forms from the emerging menu on event Click, make active the timer so that it has shown this second form through some milliseconds. For fuller инфы, see Clause Q167839 in the Microsoft Knowledge Base.
Back to the MAINTENANCE
<PICTURE>
22. USE OF THE COLLECTION FOR ОТФИЛЬТРОВЫВАНИЯ THE DUPLICATED VALUES
VB4 16/32, VB5 Level: Intermediate This code illustrates how to use collections (Collection) for generation of a unique set of sizes from a set containing duplicates. In this example, the file of lines is scanned and are sorted all unique with use list-box контрола:
Sub Remove_Duplicates (arr () As String) Dim i As Long Dim RawData As String Dim DataValues As New Collection
On Error Resume Next ' it is inserted for ignoring a mistake 457 - Duplicate key For i = LBound (arr) To UBound (arr) RawData = arr (i) DataValues. Add RawData, RawData ' If Run-time error 457 has happened, a repeating value is ignored Next On Error GoTo 0
' Preservation in List Box ' (property Sorted is exposed True) lstSortedData. Clear For Each DataValue In DataValues lstSortedData. AddItem DataValue Next End Sub
Back to the MAINTENANCE
<PICTURE>
23. CREATION « FAR OFF CONTROLLABLE » FORMS
VB3 Level: Intermediate
Sometimes it is required to me котролировать one form when focus is on another. For example, when I press «ОК» on the form And, I should make resize on the form of Century So, on each form which to me should « be supervised far off », I do invisible text box, we shall name it TextCommand, in event Change which there is a following code:
Sub TextCommand_Change () Dim msg as string msg = Trim $ (Me. TextCommand. Text) If Len (msg) = 0 Then Exit Sub
Select Case msg Case "COMMAND_RESIZE" Call MyFormResize Case "COMMAND_REPAINT" Call MyFormPaint... End Select Me. TextCommand = " " End Sub
You can supervise far off the form, transferring corresponding value in it TextCommand:
Sub Command1_Click () formB.TextCommand = "COMMAND_RESIZE" DoEvents End Sub
This code can be used for sending мессагов from MDI forms to descendants:
Dim f As Form Set f = Me. ActiveForm f. TextCommand = "COMMAND_RESIZE"
If you sit under VB4 or VB5, you can use also Public-properties and methods of the form.
Back to the MAINTENANCE
<PICTURE>
24. RECORD of the CURRENT POSITION And the SIZE of the FORM BY MEANS OF SAVESETTING
VB4 16/32, VB5 Level: Intermediate Functions SaveSetting and GetSetting facilitate a writing сеттингов in аппликухах. These two functions restore and remember current positions of the form:
Public Sub FormPosition_Get (F As Form) ' Reads out a position of form F from ' ini/reg a file and accordingly ' positions form Dim buf As String Dim l As Integer, t As Integer Dim h As Integer, w As Integer Dim pos As Integer
buf = GetSetting (app. EXEName, _ "FormPosition", F.Tag, " ") If buf = " " Then ' defaults for a centering фромы F.Move (Screen. Width - F.Width) \ _ 2, (Screen. Height - F.Height) \ 2 Else ' to allocate l, t, w, h and to expose the form pos = InStr (buf ",") l = CInt (Left (buf, pos - 1)) buf = Mid (buf, pos + 1) pos = InStr (buf ",") t = CInt (Left (buf, pos - 1)) buf = Mid (buf, pos + 1) pos = InStr (buf ",") w = CInt (Left (buf, pos - 1)) h = CInt (Mid (buf, pos + 1)) F.Move l, t, w, h End If End Sub
Public Sub FormPosition_Put (F As Form) ' Writes op, left, height and ' width positions of form F in reg/ini a file аппликухи Dim buf As String buf = F.left and "," and F.top and "," and _ F.Width and "," and F.Height SaveSetting app. EXEName, _ "FormPosition", F.Tag, buf End Sub
You should place these procedures in the module and to cause them from events Load and Unload forms. You should write a name of the form to its property Tag that these procedures worked correctly
Sub Form_Load () FormPosition_Get Me End Sub Sub Form_Unload () FormPosition_Put Me End Sub
Back to the MAINTENANCE
<PICTURE>
25. The EFFECTIVE UTILIZATION INTERNAL VB CONSTANTS
VB4 16/32, VB5 Level: Beginning
I had to see some advice on use of numerical values instead of corresponding VB constants. For example, you can deduce message box, using numerical constants:
rc = MsgBox (msg, 4 + 32 + 256, " Confirm Delete ")
Whether but not is easier prohonour the following?
rc = MsgBox (msg, vbYesNo + vbQuestion _ + vbDefaultButton2, _ " Confirm Delete ")
You can use following constants for check box:
VbUnchecked =0 VbChecked =1 VbGrayed =2
Also it is useful to know line constants instead of corresponding chr $ (symbols ASCII):
vbTab instead of Chr $ (9) vbCr instead of Chr $ (13) vbLf instead of Chr $ (10) vbCrLf instead of Chr $ (13) +Chr $ (10)
Back to СОДЕРЖАНИ
<PICTURE>
26 THE CORRECT TEST ON " FILE EXIST "
VB3, VB4 16/32, VB5 Level: Intermediate
Dir $ generates runtime error if to it put a nonexistent name of a disk. For example, Dir $ ("d: \win \himems.sys") dies, if драйв d: does not exist. For check of existence of a file, add обработчик mistakes:
Function FileExist (filename As String) _ As Boolean On Error Resume Next FileExist = Dir $ (filename) <> " " If Err. Number <> 0 Then FileExist _ = False On Error GoTo 0 End Function
Back to the MAINTENANCE
<PICTURE>
27. THE PROCEDURES WORKING WITH GROUPS KONTROLOV
VB4 16/32, VB5 Level: Intermediate
You can use almost forgotten opportunity VB to have procedure or the function working with unlimited number of arguments that can be useful at work with set контролов. For example, you can enable/disable group контролов one call of procedure:
EnableAll True, Text1, Text2, _ Command1, Command2
This procedure passes on all контролам, transferred as arguments:
Sub EnableAll (Enabled As Boolean, _ ParamArray objs () As Variant) Dim obj As Variant For Each obj In objs obj. Enabled = Enabled Next obj End Sub
Back to the MAINTENANCE
<PICTURE>
28 IMPROVEMENT СКРОЛЛИНГА OF FIGURES
VB3, VB4 16/32, VB5 Level: Intermediate First, make, that event Scroll скроллбара pictures updated coordinates of a picture (as if it moves) when you carry мышой on a picture. Then, declare following variables at a level of the form:
Dim StartX As Long, StartY As Long Dim Moving As Boolean
Finally, declare these three events for PicPicture: At last, declare this three events for PicPicture:
Private Sub PicPicture_MouseDown_ (Button As Integer, Shift As _ Integer, x As Single, y As Single) StartX = x StartY = y Moving = True End Sub
Private Sub PicPicture_MouseMove_ (Button As Integer, Shift As _ Integer, x As Single, y As Single) If Moving Then PicPicture. Move _ PicPicture. Left + x - StartX, PicPicture. Top + y - StartY End If End Sub
Private Sub PicPicture_MouseUp_ (Button As Integer, Shift As _ Integer, x As Single, y As Single) Moving = False End Sub
Now you can скроллить a picture мышой. Do not forget to check up border of a picture.
Back to the MAINTENANCE
<PICTURE>
29. THE CIPHERED PASSWORDS
VB3, VB4 16/32, VB5 Level: Intermediate
Following two functions easily and effectively Þ¿õÓÒÔ/will decode the text password. Functions have two arguments: number from 1 up to 10 to shift a position of symbol ASCII in the password, and actually a line of the password. Function EncryptPassword passes through each symbol of line DecryptedPassword, checks a symbol on parity/oddness, and shifts it upwards/downwards according to parameter Number. This does the ciphered line not readable. The ciphered password «укатывается» then operator XOR who even more confuses a line. I have limited parameter Number to number 10 as I should not do check on "wrong" symbols ASCII. Function DecryptPassword repeats upside-down process of enciphering, applying XOR, and then shift.
Function EncryptPassword (Number As _ Byte, DecryptedPassword As String) Dim Password As String, Counter As Byte Dim Temp As Integer
Counter = 1 Do Until Counter = _ Len (DecryptedPassword) + 1 Temp = Asc (Mid (DecryptedPassword, _ Counter, 1)) If Counter Mod 2 = 0 Then ' see if even Temp = Temp - Number Else Temp = Temp + Number End If Temp = Temp Xor (10 - Number) Password = Password and Chr $ (Temp) Counter = Counter + 1 Loop EncryptPassword = Password End Function
Function DecryptPassword (Number As _ Byte, EncryptedPassword As String) Dim Password As String, Counter As Byte Dim Temp As Integer
Counter = 1 Do Until Counter = _ Len (EncryptedPassword) + 1 Temp = Asc (Mid (EncryptedPassword, _ Counter, 1)) Xor (10 - Number) If Counter Mod 2 = 0 Then ' see if even Temp = Temp + Number Else Temp = Temp - Number End If Password = Password and Chr $ (Temp) Counter = Counter + 1 Loop DecryptPassword = Password End Function
Back to the MAINTENANCE
<PICTURE>
30. CAPITAL-LOWER CASE LETTER - ADVICE ON TRACKING THE REGISTER OF LETTERS
VB4 16/32, VB5 Level: Intermediate If you use the left arrow on клаве to pass to the beginning of a word, and then press the letter as a result you receive two header letters (the first already was, and the second was entered by you - I so understand??). Having applied a code, which uses advantages built in in VB4/VB5 functions StrConv (), you receive automatic reduction of letters the necessary register during input:
Private Sub Text1_Change () If Text1. Tag = " " Then Text1. Tag = Text1. SelStart Text1. Text = StrConv (Text1. Text, vbProperCase) Text1. SelStart = Text1. Tag Text1. Tag = " " End If End Sub
Back to the MAINTENANCE
<PICTURE>
31. TRACKING DOUBLE CLICK FOR BUTTONS ON ТУЛБАРЕ
VB4 32, VB5 Level: Intermediate VB4 supports built in in Win95 контрол Toolbar, allowing users to add buttons on Тулбар. These buttons have event ButtonClick but if you wish to catch double-click standard event ButtonDoubleClick is not present. To correct it, declare two variables of a level of the form:
Private mbSingleClicked As Boolean Private mbDoubleClicked As Boolean
In the Toolbars ButtonClick event, add this code: In event ButtonClick Тулбара add a following code:
Private Sub Toolbar1_ButtonClick_ (ByVal Button As Button) Dim t As Single t = Timer If mbSingleClicked = True Then mbDoubleClicked = True MsgBox " Double Clicked " Else mbSingleClicked = True ' to allow the user to click once again if it wants double-click Do While Timer - t <1 And mbSingleClicked = True DoEvents Loop ' if the user has made DoubleClick, to leave procedure If mbDoubleClicked = True Then mbSingleClicked = False mbDoubleClicked = False Exit Sub End If End If If mbDoubleClicked = False Then MsgBox " Single Clicked " End If
' an example of processing of these events ' If mbDoubleClicked Then '---------code ' ElseIf mbSingleClicked Then '---------code ' End If
' at an output from procedure it is necessary реинитить variables, differently we shall rest in SingleClickи If mbDoubleClicked = False Then mbSingleClicked = False mbDoubleClicked = False End If End Sub
Back to the MAINTENANCE
<PICTURE>
32. VOLUME OF THE CATALOGUE IN БАЙТАХ
VB3, VB4 16/32, VB5 Level: Intermediate
This function returns number of the bytes borrowed by files in the catalogue:
Function DirUsedBytes (ByVal dirName As _ String) As Long Dim FileName As String Dim FileSize As Currency
' to add \ if was not If Right $ (dirName, 1) <> "\" Then dirName = dirName and "\" Endif FileSize = 0 FileName = Dir $ (dirName and " *. * ")
Do While FileName <> " " FileSize = FileSize + _ FileLen (dirName and FileName) FileName = Dir $ Loop DirUsedBytes = FileSize
End Function
Example of a call of such function:
MsgBox DirUsedBytes ("C: \Windows")
Back to the MAINTENANCE
<PICTURE>
33. THE USEFUL DISK INFORMATION
VB4 32, VB5 Level: Advanced
This function returns quantity of free space on a disk, total amount of a disk, a share of free space н адиске, and использванное space. Before a call of function, appropriate to the first field of structure DISKSPACEINFO ("RootPath") a name of a disk:
Dim dsi As DISKSPACEINFO dsi. RootPath = " C: \ " GetDiskSpace dsi
Function returns all results in other fields of record (structure):
' *** Declaratiosn Section ****** Declare Function GetDiskFreeSpace Lib _ "kernel32" Alias _ "GetDiskFreeSpaceA" _ (ByVal lpRootPathName As String, _ lpSectorsPerCluster As Long, _ lpBytesPerSector As Long, _ lpNumberOfFreeClusters As Long, _ lpTotalNumberOfClusters As Long) _ As Long
Type DISKSPACEINFO RootPath As String * 3 FreeBytes As Long TotalBytes As Long FreePcnt As Single UsedPcnt As Single End Type
' ****** THE MODULE OF THE CODE ****** Function GetDiskSpace (CurDisk As _ DISKSPACEINFO) Dim X As Long Dim SxC As Long, BxS As Long Dim NOFC As Long, TNOC As Long
X& = GetDiskFreeSpace_ (CurDisk. RootPath, SxC, BxS, _ NOFC, TNOC) GetDiskSpace = X&
If X& Then CurDisk. FreeBytes = BxS * _ SxC * NOFC CurDisk. TotalBytes = BxS * _ SxC * TNOC CurDisk. FreePcnt = ((CurDisk._ TotalBytes CurDisk._ FreeBytes) / CurDisk._ TotalBytes) * 100 CurDisk. UsedPcnt = _ (CurDisk. FreeBytes / _ CurDisk. TotalBytes) * 100 Else CurDisk. FreeBytes = 0 CurDisk. TotalBytes = 0 CurDisk. FreePcnt = 0 CurDisk. UsedPcnt = 0 End If End Function
In such kind, function works with драйвами the size somewhere up to 2Гб, for greater disks it is necessary to use variables of type Single.
Back to the MAINTENANCE
<PICTURE>
34. AS СЫМИТИРОВАТЬ PRESSING OF KEY CTRL FOR ALLOCATION OF UNTIED PIECES IN LIST BOX
VB4 32, VB5 Level: Advanced
When property MultiSelect usual listboxа is established in 1 - Simple or in 2 - Extended, the user should press Ctrl at кликании inside of it listboxа to allocate untied (going неподряд) elements. My method allows the user to choose some elements, not pressing thus Ctrl. Place a mentioned below code in the module.
Declare Function GetKeyboardState Lib _ "user32" (pbKeyState As Byte) _ As Long Declare Function SetKeyboardState Lib _ "user32" (lppbKeyState As Byte) _ As Long Public Const VK_CONTROL = &H11 Public KeyState (256) As Byte
This code thrust in event MouseDown of yours listboxа (we shall name it List1) at which property MultiSelect is established in Simple or Extended:
' "presses" Ctrl GetKeyboardState KeyState (0) KeyState (VK_CONTROL) = _ KeyState (VK_CONTROL) Or &H80 SetKeyboardState KeyState (0)
This code place in procedure in which it is necessary "to wring out" Ctrl, for example, List1_LostFocus:
' "wrings out" Ctrl GetKeyboardState KeyState (0) KeyState (VK_CONTROL) = _ KeyState (VK_CONTROL) And &H7F SetKeyboardState KeyState (0)
Back to the MAINTENANCE
<PICTURE>
35. TO CHOOSE ALL FILES ON THE MASK IN ПОДДЕРЕВЕ CATALOGUES
VB3, VB4 16/32, VB5 Level: Intermediate
As this code does not use API, you can easily transfer it with 16 on a 32-bit platform and back. Procedure DirWalk позводит to you to see all поддерево, since заданнного places:
ReDim sArray (0) As String Call DirWalk ("OLE*.DLL", " C: \ ", sArray)
This procedure accepts * and? In the first argument which sets a mask of search. You can set some masks, dividing their symbol «;», for example, " OLE*.DLL; *.TLB ". The second argument - a place of start, the third argument - a file of lines. This procedure recursively passes under all catalogues and puts all the files, satisfying to a condition, in a file sArray with the instruction of a full way. This file changes the sizes depending on quantity of the files, satisfying to conditions of search. For использовния DirWalk, push two контрола, FileListBox and DirListBox, on the form. This procedure means, that it works with контролами on the current form:: FileListBox by name File1, and DirListBox by name Dir1. For increase in speed of work make these контролы invisible. Use of these контролов does not demand purchase additional тулзов as they (контролы) contain in base library контролов VB.
Sub DirWalk (ByVal sPattern As String, _ ByVal CurrDir As String, sFound () _ As String) Dim i As Integer Dim sCurrPath As String Dim sFile As String Dim ii As Integer Dim iFiles As Integer Dim iLen As Integer
If Right $ (CurrDir, 1) <> "\" Then Dir1. Path = CurrDir and "\" Else Dir1. Path = CurrDir End If For i = 0 To Dir1. ListCount If Dir1. List (i) <> " " Then DoEvents Call DirWalk (sPattern, _ Dir1. List (i), sFound ()) Else If Right $ (Dir1. Path, 1) = "\" _ Then sCurrPath = Left (Dir1. Path, _ Len (Dir1. Path) - 1) Else sCurrPath = Dir1. Path End If File1. Path = sCurrPath File1. Pattern = sPattern If File1. ListCount> 0 Then ' the necessary files are found in catalogue For ii = 0 To File1._ ListCount - 1 ReDim Preserve _ sFound (UBound (sFound) _ + 1) sFound (UBound (sFound) - _ 1) = sCurrPath and _ "\" and File1. List (ii) Next ii End If iLen = Len (Dir1. Path) Do While Mid (Dir1. Path, iLen, _ 1) <> "\" iLen = iLen - 1 Loop Dir1. Path = Mid (Dir1. Path, 1, _ iLen) End If Next i End Sub
Back to СОДЕРЖАНИ
<PICTURE>
36. THE NAME OF THE CURRENT COMPUTER IN WINDOWS 95/NT
VB4 32, VB5 Level: Advanced
Often you should know a name of a current computer under WINDOWS 95/NT from yours VB programs. Use this unpretentious function API from kernel32.dll:
Private Declare Function GetComputerNameA Lib "kernel32" _ (ByVal lpBuffer As String, nSize _ As Long) As Long
Public Function GetMachineName () As _ String Dim sBuffer As String * 255 If GetComputerNameA (sBuffer, 255&) _ <> 0 Then GetMachineName = Left $ (sBuffer, _ InStr (sBuffer, vbNullChar) _ - 1) Else GetMachineName = " (Not Known) " End If End Function
Back to the MAINTENANCE
<PICTURE>
37. HOW TO SHOW FONTS WHEN YOU CHOOSE THEM
VB3, VB4 16/32, VB5 Level: Intermediate That the user could change a name of a font, load all fonts in комбобокс:
Private Sub Form_Load () ' to define quantity of screen fonts. For I = 0 To Screen. FontCount - 1 ' to thrust all fonts in листбокс. cboFont. AddItem Screen. Fonts (I) Next I End Sub
Decorate procedure, having allowed the user at once to see result of the choice, needlessly to print "something" as the test:
Private Sub cboFont_Click () ' to make chosen FontName a font combobox cboFont. FontName = cboFont. Text End Sub
Back to the MAINTENANCE
<PICTURE>
38. INTERCEPTION RIGHT КЛИКОВ ON UNITS TREEVIEW
VB4 32, VB5 Level: Intermediate
Контрол TreeView gives to yours аппликухе finished kind Windows 95. However, in textbooks on VB it is not told how to intercept right mouse cliques on unit (node) a tree. Event Treeview_MouseDown occurs before event NodeClick. To show the contextual menu above unit, use this code and define a key (Key) for for each unit in the form of the letter and number following it.
+ Root (R01) ' the letter gives | ---Child 1 (C01) ' the indication to | - + Child 2 (C02) ' the context menu | | ---Child 2.1 (H01) | | ---Child 2.2 (H02)
Dim bRightMouseDown as Boolean
Private Sub Form_Load () bRightMouseDown = False End Sub
Private Sub treeview1_MouseDown_ (Button As Integer, Shift As _ Integer, X As Single, Y As Single) If Button And vbRightButton Then bRightMouseDown = True Else bRightMouseDown = False End If End Sub
Private Sub treeview1_MouseUp_ (Button As Integer, Shift As _ Integer, X As Single, Y As Single) bRightMouseDown = False End Sub
Private Sub treeview1_NodeClick_ (ByVal Node As Node) Select Case Left (Node. Key, 1) Case "R" If Not bRightMouseDown Then ' do the normal node click, ' so you must here the code ' for the node code click Else ' a choice of unit treeview1. Nodes (Node. Key) .Selected = True ' to show contextual menu PopupMenu mnuContext1 End If Case "C" If Not bRightMouseDown Then ' do the normal node click, ' so you must here the code ' for the node code click Else ' a choice of unit treeview1. Nodes (Node. Key) .Selected = True ' to show contextual menu PopupMenu mnuContext2 End If
' the same with other units '.... End Select End Sub
Back to the MAINTENANCE
<PICTURE>
39. START VB BY MEANS OF MENU SENDTO
VB3, VB4 16/32, VB5 Level: Intermediate Addition of a label " Shortcut to VB.exe " and " Shortcut to VB32.exe " in the menu " Send To " allows you right-clickом on any VBP the project to open it in VB4 16/32 or in VB5 - on a choice. Come into yours VB the catalogue, right-clickните on VB32.exe, and choose " Create shortcut. ". When the label will be created, move it to catalogue C: \Windows \Sendto. Now at right-clickе on the project you can choose where "to send" your project. You can add labels for WordPad, Word, Excel or any other program supposing use of an entrance file as parameter of start.
Back to the MAINTENANCE
<PICTURE>
40. NEW “ HOT BUTTONS ” FOR VB
VB4 16/32, VB5 Level: Intermediate
1) In VB5, press Ctrl-F3 when the cursor is above any word. Thus following ocurrence of this word will be automatically found in the text, passing dialogue of search. The cursor should stand at least behind the first letter of a word that this feature worked correctly.
2) In VB4/5 pressing Ctrl-Tab it is possible to move between all open windows in IDE, it often appears more quickly, than to go to menu Window.
Back to the MAINTENANCE
<PICTURE>
41. HOW TO RECEIVE USERID UNDER WINDOWS 95/NT
VB4 32, VB5 Level: Intermediate
Often you should receive userID the current user working with your program. Use for this purpose updating of one of functions API:
Option Explicit
Private Declare Function WNetGetUserA _ Lib "mpr" (ByVal lpName As String, _ ByVal lpUserName As String, _ lpnLength As Long) As Long
Function GetUser () As String Dim sUserNameBuff As String * 255 sUserNameBuff = Space (255) Call WNetGetUserA (vbNullString, _ sUserNameBuff, 255&) GetUser = Left $ (sUserNameBuff, _ InStr (sUserNameBuff, _ vbNullChar) - 1) End Function
Back to the MAINTENANCE
<PICTURE>
42 CONCLUSION of the SAND-GLASS DURING DATA PROCESSING
VB4 32, VB5 Level: Advanced
Нижеуказанная the technique simplifies switching MousePointerа, without addition спец. A code in the end of each procedure/function. When you созадете the object from any class, is generated event Initialize. Then the code of corresponding procedure is executed. It is the first code executed for given object, it is executed before assignment of any properties to object and before performance of methods of object. When the variable leaves area of visibility, all references to object are destroyed, and the code for event Terminate is carried out.
Declare Sub Sleep Lib "kernel32" _ (ByVal dwMilliseconds As Long)
' the example of the procedure using class CHourGlass Private Sub ProcessData () Dim MyHourGlass As CHourGlass Set MyHourGlass = New CHourGlass ' here is inserted a code of data processing Sleep 5000 ' It models data processing ' continuation of code End Sub
' creation of class CHourGlass: Private Sub Class_Initialize () ' To show HourGlass Screen. MousePointer = vbHourglass End Sub
Private Sub Class_Terminate () ' To restore MousePointer Screen. MousePointer = vbDefault End Sub
Back to the MAINTENANCE
<PICTURE>
43. The ESTIMATION of the TIME INTERVAL (in minutes) BETWEEN TWO DATES
VB4 16/32, VB5 Level: Beginning the number of the last minutes between two events can be necessary for you. A code:
lTotalMinutes = Minutes (Now) - _ Minutes (datStartTime)
This function returns quantity of minutes with 01/01/1900:
Public Function Minutes (d As Date) _ As Long ' the Minutes which have been last with 1900 Dim lPreviousDays As Long Dim lTotalMinutes As Long
lPreviousDays = d - #1/1/1900# lTotalMinutes = _ (lPreviousDays * 24) * 60 lTotalMinutes = lTotalMinutes + _ Hour (d) * 60 lTotalMinutes = lTotalMinutes + _ Minute (d)
Minutes = lTotalMinutes End Function
Back to the MAINTENANCE
<PICTURE>
44. WILL SUFFICE TO PRINT!
VB3, VB4 16/32, VB5 Level: Beginning
Sometimes to me the line after line would be desirable to unpack data from recordsetа. However, it is difficult enough пркратить this process before all recordset will leave in turn of the printer. Use button Cancel which establishes a flag. Except for the button sending the task for a press, create one more, under name Cancel. You also can appropriate to its property Cancel value True that the user could stop a press pressing on Esc. Add one more variable in the module:
Dim CancelNow As Integer
Put this code in the Click event of the Cancel button: Add this code in event Click of button Cancel:
Sub cCancel_Click () CancelNow =-1 DoEvents End Sub
You can even do without the button and catch only pressing on Escape. In this case, establish property KeyPreview of the form in True and insert a following code:
Sub Form_KeyPress (KeyAscii As Integer) ' if the user presses ESC If KeyAscii = (27) Then CancelNow =-1 DoEvents End If End sub
At last, insert check of a flag inside of a cycle of a press:
'... Any code... ' a press recordset from database Do While Not MyRecordSet. EOF Printer. Print MyRecordSet! SomeRecord MyRecordSet. MoveNext DoEvents ' a stop if has been pressed Cancel If CancelNow then Exit Do Loop Printer. EndDoc '... A code further...
Back to the MAINTENANCE
<PICTURE>
45. TO CHANGE VALUES OF TWO VARIABLES
VB3, VB4 16/32, VB5 Level: Intermediate
Use this algorithm to swap two integer variables: Actually, here:
a = a Xor b b = a Xor b a = a Xor b
Back to СОДЕРЖАНИ
<PICTURE>
46. FAST ОБСЧЕТ MULTINOMINALS
VB3, VB4 16/32, VB5 Level: Intermediate
Well-known formula Горнера allows to consider quickly полиномиальные expressions. To count A*x^N + B*x (N-1) + … + Y*x + Z (means a degree), write: (… ((A*x + B) *x + C) *x + … +Y) *x + Z.
Back to the MAINTENANCE
<PICTURE>
47. FORMATTING AND COPYING OF DISKETTES THROUGH FUNCTIONS API
VB4 32, VB5 Level: Advanced
In Win32 API there is a couple of the functions, allowing to format and copy diskettes from the program:
Private Declare Function SHFormatDrive _ Lib "shell32" (ByVal hwnd As Long, _ ByVal Drive As Long, _ ByVal fmtID As Long, _ ByVal options As Long) As Long Private Declare Function GetDriveType _ Lib "kernel32" _ Alias "GetDriveTypeA" _ (ByVal nDrive As String) As Long
Add two command buttons in the form, name them cmdDiskCopy and cmdFormatDrive, and thrust in their events Click following fragments of a code:
Private Sub cmdDiskCopy_Click () ' DiskCopyRunDll demands two parameters - From and To Dim DriveLetter $, DriveNumber&, _ DriveType& Dim RetVal&, RetFromMsg& DriveLetter = UCase (Drive1. Drive) DriveNumber = (Asc (DriveLetter) - _ 65) DriveType = GetDriveType_ (DriveLetter) If DriveType = 2 Then ' Floppies, _ etc RetVal = Shell_ ("rundll32.exe" and _ " diskcopy.dll, " _ and "DiskCopyRunDll" and _ DriveNumber and "," and _ DriveNumber, 1) Else ' Just in case RetFromMsg = MsgBox_ (" Only floppies can be " and _ "copied", 64, _ " DiskCopy Example ") End If End Sub
Private Sub cmdFormatDrive_Click () Dim DriveLetter $, DriveNumber&, _ DriveType& Dim RetVal&, RetFromMsg % DriveLetter = UCase (Drive1. Drive) DriveNumber = (Asc (DriveLetter) - _ 65) ' To replace the letter with figure: A=0 DriveType = GetDriveType_ (DriveLetter) If DriveType = 2 Then _ ' i.e. флоп RetVal = SHFormatDrive (Me.hwnd, _ DriveNumber, 0&, 0&) Else RetFromMsg = MsgBox_ (" This drive is NOT a " and _ " removeable drive! " And _ " Format this drive? ", _ 276, " SHFormatDrive Example ") If RetFromMsg = 6 Then ' Раскомментируйте also will see... ' RetVal = SHFormatDrive_ (Me.hwnd, _ ' DriveNumber, 0&, 0&) End If End If End Sub
Add контрол DriveListBox under name Drive1:
Private Sub Drive1_Change () Dim DriveLetter $, DriveNumber&, _ DriveType& DriveLetter = UCase (Drive1. Drive) DriveNumber = (Asc (DriveLetter) - _ 65) DriveType = GetDriveType_ (DriveLetter) If DriveType <> 2 Then _ ' Floppies, etc cmdDiskCopy. Enabled = False Else cmdDiskCopy. Enabled = True End If End Sub
Be cautious: so it is short also the screw запороть.
Back to the MAINTENANCE
<PICTURE>
48. CONSECUTIVE NUMBERS OF VERSIONS
VB4 16/32, VB5 Level: Intermediate
For tracking sequence of versions, use this procedure if you use number of the version:
Public Function GetMyVersion () As String ' converts number of the version in something like "2/1/0001" Static strMyVer As String If strMyVer = " " Then strMyVer = Trim $ (Str $ (App. Major)) and "." And _ Format $ (App. Minor, "##00") _ and "." Format $ (App. Revision, "000") End If GetMyVersion = strMyVer End Function
Back to the MAINTENANCE
<PICTURE>
49. ALIGNMENT КОНТРОЛОВ BY the RIGHT EDGE
VB3, VB4 16/32, VB5 Level: Beginning
At creation of forms with the unstable sizes, I prefer to place all контролы in right bottom and right top corners. For example, on forms where data are entered, I put buttons of navigation on records in the left bottom part of the form together with buttons Add New Record, Delete Record, and Find Record. In the bottom right corner I put buttons print preview and closings of the form. Place this procedure in the module or general declarations forms. In parameter Offset you can change a distance from a right edge of the form, that is you can level by a right edge yours контролы.
Sub ButtonRight (X As Control, _ Frm As Form, Offset as Integer) X.Left = Frm. ScaleWidth - _ X.Width - Offset End Sub
Place two command buttonа on the form. In event Form_Resize, add about such code:
Private Sub Form_Resize () ButtonRight Command1, Me, 0 ButtonRight Command2, Me, _ Command1. Width End Sub
Back to the MAINTENANCE
<PICTURE>
50. VAL () DOES NOT WORK ON THE FORMATTED NUMBERS
VB3, VB4 16/32, VB5 Level: Intermediate
More cautiously with function Val (). It incorrectly distinguishes the formatted numbers. Use instead of it CInt (), CDbl ().
FormattedString = Format (1250, _ "General") ' = " 1,250.00" Debug. Print Val (FormattedString) ' will print 1! Debug. Print cDbl (FormattedString) ' will print 1250
Back to the MAINTENANCE
<PICTURE>
51. CМЫШЛЕНЫЙ GENERATOR ID
VB3, VB4 16/32, VB5 Level: Intermediate
I have written the generator for creation unique номиров, type of number акаунта, or ID in вашеи the appendix. I use it together with фенкцией CheckForValid, for example CheckForValid will return True for number "203931." And will return False for "209331."
Function CheckForValid (Num As Long) _ As Boolean ' Check for valid number Result = Num Mod 13 If Result <> 0 Then CheckForValid = False ' if false then the number is wrong Else CheckForValid = True ' if true the number is OK End If End Function
Function Generate (Num As Long) As Long ' Generates the successor of a valid ' number If CheckForValid (Num) Then Generate = Num + 13 ' if valid Generate Else Generate =-1 ' Otherwise return-1 End If End Function
Back to the MAINTENANCE
<PICTURE>
52. CHANGE OF THE SIZE OF DROPPING OUT AREA ON COMBOBOXE
VB4 32, VB5 Level: Advanced In VB there is no property ListRows i.e. if you should represent more than 8 дефолтовых lines on the dropping out list comboboxа use this procedure for increase in the size of a window comboboxа:
Option Explicit
Type POINTAPI x As Long y As Long End Type
Type RECT Left As Long Top As Long Right As Long Bottom As Long End Type
Declare Function MoveWindow Lib _ "user32" (ByVal hwnd As Long, _ ByVal x As Long, ByVal y As Long, _ ByVal nWidth As Long, _ ByVal nHeight As Long, _ ByVal bRepaint As Long) As Long Declare Function GetWindowRect Lib _ "user32" (ByVal hwnd As Long, _ lpRect As RECT) As Long Declare Function ScreenToClient Lib _ "user32" (ByVal hwnd As Long, _ lpPoint As POINTAPI) As Long
Public Sub Size_Combo (rForm As Form, _ rCbo As ComboBox) Dim pt As POINTAPI Dim rec As RECT Dim iItemWidth As Integer Dim iItemHeight As Integer Dim iOldScaleMode As Integer
' Change Scale Mode of the form on Pixels iOldScaleMode = rForm. ScaleMode rForm. ScaleMode = 3 iItemWidth = rCbo. Width
' Installation of new height comboboxа iItemHeight = rForm. ScaleHeight - rCbo. Top - 5 rForm. ScaleMode = iOldScaleMode
' Reception of coordinates in relation to screen Call GetWindowRect (rCbo.hwnd, rec) pt.x = rec. Left pt.y = rec. Top
' then coordinates in the form of Call ScreenToClient (rForm.hwnd, pt)
' Change of the size comboboxа Call MoveWindow (rCbo.hwnd, pt.x, _ pt.y, iItemWidth, iItemHeight, 1) End Sub
Back to the MAINTENANCE
<PICTURE>
53. QUANTITY of FREE MEMORY By means of WIN32
VB4 32, VB5 Level: Advanced
If you should be shown users, how many free memory is accessible by the machine, and you send with 16бит on 32 bats a platform you sweep up, that function API GetFreeSystemResources исяезла. But it it doesn't matter. You should declare only API function and following type in the module:
Declare Sub GlobalMemoryStatus Lib _ "kernel32" (lpBuffer As _ MEMORYSTATUS)
Type MEMORYSTATUS dwLength As Long dwMemoryLoad As Long dwTotalPhys As Long dwAvailPhys As Long dwTotalPageFile As Long dwAvailPageFile As Long dwTotalVirtual As Long dwAvailVirtual As Long End Type
Bring in a floor dwlength the size of type MEMORYSTATUS. The variable of type Long takes 4 байта so all will leave 4*8=32 байта:
Dim ms As MEMORYSTATUS
ms.dwLength = Len (ms) GlobalMemoryStatus ms MsgBox " Total physical memory: " both _ ms.dwTotalPhys and vbCr _ and " Available physical memory: " both _ ms.dwAvailPhys and vbCr and _ " Memory load: " and ms.dwMemoryLoad
You can even write a class, in which инкапсулировать all above-stated.
Back to the MAINTENANCE
<PICTURE>
54. HOW OLD ARE YOU?
VB5 Level: Intermediate
This function returns a difference between two dates in years, months and days:
Function GetAge (dtDOB As Date, _ Optional dtDateTo As Date = 0) _ As String ' dtDateto it is transferred? If dtDateTo = 0 Then dtDateTo = Date End If GetAge = Format $ (dtDateTo - _ dtDOB, " yy - mm - dd ") End Function
Back to the MAINTENANCE
<PICTURE>
55. УЗЕЛОК ABOUT WHICH IT IS IMPOSSIBLE TO FORGET
VB3, VB4 16/32, VB5 Level: Intermediate
I often work above several projects simultaneously. Jumping from one project on another and back, sometimes I lose a trace, in what program in what place I have stopped. For the decision of this problem, take and print any phrase without inverted commas of the comment. Next time, when you start the project, choose item " Start With Full Compile ". If this phrase will be the first mistake in the project, you at once will see its illuminated and your memory will be freshened.
Back to СОДЕРЖАНИ
<PICTURE>
56. TO CREATE HURRIEDLY the FILE BY MEANS OF FUNCTION ARRAY
VB4 16/32, VB5 Level: Intermediate
Method GetRows copies lines Recordsetа (JET) or rdoResultsetа (RDO) in a file. I often use this feature for data transmission between OLE Serverом and client аппликухами. This method uses a variable of type Variant as parameter for storage of returned data. It is a bidimentional file (on internal representation VB)
Dim A As Variant A = Array (10,2)
Back to the MAINTENANCE
<PICTURE>
57. TO FIND CHOSEN КОНТРОЛ IN FILE OPTION BUTTONS
VB4 16/32, VB5 Level: Intermediate Use this code for a finding of an index chosen контрола from a file option buttons
Function WhichOption (Options As _ Object) As Integer
' This function returns index Option Button, whose value true.
Dim i ' If Options - not that object, or not the object in general On Error GoTo WhichOptErr ' Default to failed WhichOption =-1 ' checks everyone OptionButton in a file. I ask to note, that function gives out ' wrong value if indexes go not successively For i = Options.lbound To _ Options.ubound If Options (i) Then ' to remember value of found index WhichOption = i ' and to leave Exit For End If Next WhichOptErr:
End Function
Consider, that iCurOptIndex has type integer, and Option1 this name of a file контролов OptionButton.
iCurOptIndex = WhichOption (Option1)
Important: parameter of function - object. It will work only with parameters-objects or type variant.
Back to the MAINTENANCE
<PICTURE>
58. PACKING VALUES CHECK-BOX IN ONE VARIABLE OF TYPE INTEGER
VB4 16/32, VB5 Level: Intermediate
Using a following code, it is possible to deduce binary representation зачеркнутых check boxов:
Function WhichCheck (ctrl As Object) As _ Integer ' This function returns binary representation of a file контролов, ' where everyone зачеркнутый чекбокс is represented the two in a degree of the index in ' a file, напр.элемент 0 : 2 0 = 1, ' elements 0 and 2 : 2^0 + 2^2 = 5
Dim i Dim iHolder ' if the incorrect parameter is transferred in procedure ' comes back 0 On Error GoTo WhichCheckErr
' binary representation ' a file чекбоксов For i = ctrl. LBound To ctrl. UBound If ctrl (i) = 1 Then ' if will cross out, to add its binary representation iHolder = iHolder Or 2 i End If Next WhichCheckErr: WhichCheck = iHolder
End Function
Function is caused as follows:
iCurChecked = WhichCheck (Check1)
Check1 - a file чекбоксов, iCurChecked - a variable integer. Below the "dual" procedure establishing all чекбоксы according to a variable in which their binary representations are stored is resulted.
Sub SetChecked (ctrl As Object, _ iCurCheck %) ' This sub sets the binary value of an ' array of controls where iCurChecked is ' 2 raised to the index of each checked ' control Dim i ' in case ctrl is not a valid object On Error GoTo SetCheckErr ' use the binary representation to ' set individual check box controls For i = ctrl. LBound To ctrl. UBound If iCurCheck And (2 i) Then ' if it is checked add in its ' binary value ctrl (i) .Value = 1 Else ctrl (i) .Value = 0 End If Next SetCheckErr:
End Sub
This procedure is caused so:
Call SetChecked (Check1, iDesired)
Check1 - a file чекбоксов, iDesired-a variable storing binary representation of a condition чекбоксов.
Back to the MAINTENANCE
<PICTURE>
59. CONDITIONAL COMPILATION OF THE CODE
VB4 16/32, VB5 Level: Intermediate
To the majority of developers feature Conditional Compilation from VB4 when you can declare procedures Windows API for 16 or 32-bit OS is known:
#If Win#32 then ' if 32-bit OS Declare SomeApi.... #Else ' if is started 16-digit OS Declare SomeApi #End IF the Same feature can to work not only with functions Windows API, but also with your own functions:
#If Win32 Then Dim lRc& lRc& = ReturnSomeNumber (35000) #Else Dim lRc % lRc % = ReturnSomeNumber (30000) #End If
#If Win32 Then Private Function ReturnSomeNumber_ (lVar&) As Long ReturnSomeNumber = 399999 #Else Private Function ReturnSomeNumber_ (lVar %) As Integer ReturnSomeNumber = 30000 #End If
End Function
Back to the MAINTENANCE
<PICTURE>
60. TO REDUCE BLINKING DURING LOADING the FORM
VB4, VB5 Level: Intermediate
During loading the form, the following code will help to reduce blinking and flashing GUI by means of functions API:
' Declarations Section #If Win32 Then Declare Function LockWindowUpdate _ Lib "user32" _ (ByVal hwndLock As Long) As Long #Else Declare Function LockWindowUpdate _ Lib "User" _ (ByVal hwndLock As Integer) _ As Integer #End If
Public Sub LoadSomeForm ()
' During loading the form forbids updating a condition of a window ' to get rid of blinking. ' запрещаетобновление GUI LockWindowUpdate frmTest.hWnd ' shows the form frmTest. Show ' here a code concerning to loading of the form, etc. ' Never forget to resolve back updating of window LockWindowUpdate 0 End Sub
Back to the MAINTENANCE
<PICTURE>
61. TO HIDE the INDEX ON CURRENT RECORD in DBGride
VB4 16/32, VB5 Level: Advanced
That the index of record on DBGride did not skip at moving between records (lines grida), use function API LockWindowUpdate (gridname.hwnd) before the beginning of movement on gridу, and LockWindowUpdate (0) after the termination of movings:
' Declarations Section #If Win32 Then Declare Function LockWindowUpdate _ Lib "user32" _ (ByVal hwndLock As Long) As Long #Else Declare Function LockWindowUpdate _ Lib "User" _ (ByVal hwndLock As Integer) _ As Integer #End If
Private Sub cmdHideSelector_Click () LockWindowUpdate DBGrid1.hWnd End Sub
Private Sub cmdShowSelector_Click () LockWindowUpdate 0 End Sub
Back to the MAINTENANCE
<PICTURE>
62. USE POPUP MENUS IN WINDOWS WITHOUT TITLE BAR
VB4 16/32 Level: Intermediate
When you establish property ControlBox in False and BorderStyle in fixed window can receive a window (form) without titlebar (fields of heading). If you will add the menu on this form - the title-bar will appear again. That измежать this проблемму you can place the menu on other form.
Private Sub Command1_Click () Dim frm As New frmMenu Load frm frm. PopupMenu frm.mnutest ' select specific code Unload frm End Sub
Such behaviour is corrected in VB5
Back to the MAINTENANCE
<PICTURE>
63. HOW TO LEARN DIVIDERS OF DATE AND TIME WITHOUT FUNCTIONS API
VB3, VB4 16/32, VB5 Level: Intermediate
Here simple algorithm how to learn dividers of date, time and a decimal point in Windows, not getting in Locale Settings or functions API.
DateDelimiter = Mid $ (Format (Date, _ " General Date "), 3, 1) TimeDelimiter = Mid $ (Format (0.5, _ " Long Time "), 3, 1) DecimalDelimiter = Mid $ (Format (1.1, _ " General Number "), 2, 1)
Back to the MAINTENANCE
<PICTURE>
64. PREVENTION OF MISTAKES AT USE GETSETTING
VB4 16/32, VB5 Level: Intermediate
Use of function GetSetting can generate mistakes, especially in some situations at 16-digit OS at work with INI files. If the required parameter is not present in INI a file you can see the message on a mistake " Invalid procedure call. ". Use mentioned below procedure which substitutes обработчик mistakes:
Public Function GetRegSetting (AppName _ As Variant, Section As Variant, _ Key As Variant, Optional Default _ As Variant) As Variant
' дефолтовое value has type, differently it is necessary ' to use word Set Dim tmpValue As Variant
' installation of size by default ' if the size has not been transferred, ' is received an empty variable of type Variant If Not IsMissing (Default) Then _ tmpValue = Default
' it catches possible mistakes On Error Resume Next
' now it is possible to use function from VB tmpValue = GetSetting (AppName, _ Section, Key, tmpValue)
' after possible mistakes the call repeats here ' with already certain value tmpValue GetRegSetting = tmpValue
End Function
Back to the MAINTENANCE
<PICTURE>
65. DUPLICATION OF LINES OF THE CODE WITHOUT SYNTACTIC MISTAKES
VB3, VB4 16/32, VB5 Level: Beginning Often I should copy a similar code on sense to little changes in each line; for simplification of a problem I do a pattern of that it is necessary to copy, quickly I insert a copy into the necessary place, and I do additions. However often sample text causes mistakes from VB the editor. To overcome this problem it is possible, закомментировав a pattern before use. When you finish editing the inserted fragment, раскомментируйте it and it is ready. It is especially simple under VB5 in which there is command Block Uncomment. Below the example of addition of a member in a collection is resulted.
While Not mRS.EOF oObject. FName = mRS! FName oObject. LName = mRS! LName oObject. Phone = mRS! Phone.. cCollection. Add oObject, oObject. FName Wend
If at your object of 20 or 30 properties, will create more quickly a pattern:
' oObject. = mRS!
Copy it, insert 20 or 30 times, return to the beginning and впечатайте names of properties and fields, and clean a symbol of the comment. The symbol of the comment allows you to run freely by all fragment, not caring about syntactic mistakes.
Back to СОДЕРЖАНИ
<PICTURE>
66. The LABEL FOR LOADING LAST EQUIPMENT DESIGN In VB
VB4 32 Level: Intermediate I am frequent старутю VB and I renew work with last project, but I would not like to block up desktop with icons for current works. As the decision I offer my program which needs to be compiled and started on yours desktopе. This program can be applied and to others, using INI files.
Option Explicit
Declare Function GetPrivateProfile_ String Lib "kernel32" _ Alias "GetPrivateProfileStringA" _ (ByVal lpApplicationName As _ String, ByVal lpKeyName As Any, _ ByVal lpDefault As String, _ ByVal lpReturnedString As _ String, ByVal nSize As Long, _ ByVal lpFileName As String) _ As Long
Public Sub Main () Dim temp As String, rVal $, tmp _ As Long rVal $ = String $ (256, 0) tmp = GetPrivateProfileString_ (" Visual Basic ", _ "vb32location", " ", rVal $, _ ByVal Len (rVal $) - 1, _ "c: \windows \vb.ini") temp = Left $ (rVal $, tmp) rVal $ = String $ (256, 0) tmp = GetPrivateProfileString_ (" Visual Basic ", "RecentFile1", _ " ", rVal $, ByVal Len (rVal $) _ - 1, "c: \windows \vb.ini") temp = temp and """ " and Left $ (rVal $, _ tmp) and " """ Shell temp, 1 End End Sub
Back to the MAINTENANCE
<PICTURE>
67. HOW TO DEDUCE the SYMBOL "and" In LABEL
VB4 16/32, VB5 Level: Beginning
If you want выывести a symbol л&+ on the screen, establish property "UseMnemonic" in False. This property happens it is useful, when, for example, Labelы are used for a conclusion of data from databases. Also you can deduce a symbol "and" in property Caption, having written &&.
Back to the MAINTENANCE
<PICTURE>
68. CREATION OF TIME FILES
VB3, VB4 16/32, VB5 Level: Beginning
I write a program with the databases, using many auxiliary files at a time. At programming databases it is possible to create time files for a conclusion of result of instruction SQL or from a time database more effectively to work with records. I have written function FileAux, возварщающую a name of a time file. If I should create some time files simultaneously, I keep their names in in advance certain variables:
Function FileAux (Ext As String) _ As String Dim i As Long, X As String If InStr (Ext, ".") = 0 Then Ext = "." + Ext End If
' we Search for already available files on the screw i = 0 Do X = "Aux" + Format $ (i, "0000") _ + Ext If FileExists (X) Then i = i + 1 Else Exit Do End If Loop FileAux = X End Function
This function addresses to function FileExists:
Function FileExist (filename As String) _ As Boolean FileExist = Dir $ (filename) <> " " End Function
And here an example of use:
Sub Test () Dim File1 As String, File2 As _ String, File3 As String Dim DB1 As database, DB2 As DataBase Dim FileNum As Integer File1 = FileAux ("MDB") Set DB1 = CreateDataBase (File1) File2 = FileAux ("MDB") Set DB2 = CreateDataBase (File2) File3 = FileAux ("TXT") FileNum = FreeFile Open File3 For OutPut As FileNum ' your code '... Close FileNum End Sub
File1, File2, and File3 should be " Aux0001.MDB, " " Aux0002.MDB, " and " Aux0001.TXT, " accordingly.
Back to the MAINTENANCE
<PICTURE>
69. MOUSE EVENTS DO NOT HAPPEN IF ENABLE IS ESTABLISHED IN FALSE
VB3, VB4 16/32, VB5 Level: Beginning Events MouseMove do not occur, if property Enabled контрола is established in False. My method treats this problem and it can be useful, if you wish to deduce Tooltips or Notes on статусбаре, without dependence from that, enabled контрол or disabled. If property Enabled контрола is established in False контрол, placed for given, nevertheless быдет to respond on movements of the mouse. Copy a code from Command1_MoseMove in Label1_MouseMove. Now you МаусМув works even if Command1 is inaccessible.
Command1 (0), Command1 (1)-Command1 - a file контролов. Label1 (0), Label1 (1) - a file лабелов for контролами. SSPanel1-Работает статусбаром.
Private Sub Form_Load () Dim i As Integer For i = 0 To 1 Label1 (i) .Left = Command1 (i) .Left Label1 (i) .Top = Command1 (i) .Top Label1 (i) .Width = Command1 (i) .Width Label1 (i) .Height = _ Command1 (i) .Height Next i Command1 (0) .enabled = false Command1 (0) .Tag = " Button to Add " Command1 (1) .Tag = " Button to Modify " Command1 (0) .Caption = "&Add" Command1 (1) .Caption = "&Modify"
End Sub
Private Sub Label1_MouseMove (Index As _ Integer, Button As Integer, Shift _ As Integer, X As Single, Y As _ Single) SSPanel1. Caption = Command1 (Index) .Tag End Sub
Private Sub Command1_MouseMove (Index _ As Integer, Button As Integer, _ Shift As Integer, X As Single, Y _ As Single) SSPanel1. Caption = Command! (Index) .tag End Sub
Back to the MAINTENANCE
<PICTURE>
70. HOW TO DEDUCE THE POPUP MENU ON TEXT BOXES
VB4 16/32, VB5 Level: Intermediate
The some people контролы in VB4 and VB5 as, for example, TextBox have the contextual menu which is creeping out at right clique on the specified control on a default. If you want, that another left котекстное the menu standard methods or пропертей for this purpose do not exist. The output consists in отлавливании events Mouse_Down which code will do контрол inaccessible. Then высвечивайте your contextual menu, энаблите контрол back. Procedure PopContextMenu describes the specified method
Sub PopContextMenu (argoControl As _ Control, argoMenu As Control) argoControl. Enabled = False PopupMenu argoMenu argoControl. Enabled = True End Sub
Example of a call in event MouseDown for текстбтокса by name Text1 and menu MyMenu:
Private Sub Text1_MouseDown (Button As _ Integer, Shift As Integer, X As _ Single, Y As Single) If Button = vbRightButton Then PopContextMenu Text1, MyMenu End If End Sub
Back to the MAINTENANCE
<PICTURE>
71. TO ALIGN the FORM In view of ТАСКБАРА
VB3, VB4 16/32, VB5 Level: Intermediate For a centering of the form you should cause only API procedure, and to get two constants. This decision is based on that fact, that GetSystemMetrics returns true value of parameters of the screen which can be borrowed actually таскбаром and Microsoft Office shortcut barом:
Public Const SM_CXFULLSCREEN = 16 Public Const SM_CYFULLSCREEN = 17
#If Win32 then Declare Function GetSystemMetrics _ Lib "user32" _ (ByVal nIndex As Long) As Long #Else Declare Function GetSystemMetrics _ Lib "User" _ (ByVal nIndex As Integer) _ As Integer #End If
Public Sub CenterForm (frm As Form) frm. Left = Screen. TwipsPerPixelX * _ GetSystemMetrics_ (SM_CXFULLSCREEN) / 2 _ - frm. Width / 2 frm. Top = Screen. TwipsPerPixelY * _ GetSystemMetrics_ (SM_CYFULLSCREEN) / 2 _ - frm. Height / 2 End Sub
Back to the MAINTENANCE
<PICTURE>
72. CLEARING THE LINE OF UNNECESSARY SYMBOLS
VB3, VB4 16/32, VB5 Level: Beginning Sometimes happens it is useful to have function which clears a line of undesirable symbols. This small function accepts as parameters a line for clearing and a symbol of which it should be cleared:
Function StringCleaner (s As String, _ Search As String) As String Dim i As Integer, res As String res = s Do While InStr (res, Search) i = InStr (res, Search) res = Left (res, i - 1) and _ Mid (res, i + 1) Loop StringCleaner = res End Function
Back to the MAINTENANCE
<PICTURE>
73. CHECK of OBJECTS BY MEANS OF TYPENAME
VB4 16/32, VB5 Level: Beginning
You can define a class to which the object belongs, by means of function TypeName instead of use of block If TypeOf. Use expression TypeOf for definition of type of object:
If TypeOf myObject is myType then... We do that End If
You can make the same савмое by means of a following code:
if TypeName (myObject) = "myType" Then.... We do that.... End If
Benefit of my decision that to you is not so obligatory to include in your project all classes (or OCXs) with which you work. It is quite good reception for a writing of the general procedures (universal, a general purpose) and, moreover, you can use TypeName in complex checks and blocks Select Case.
Back to the MAINTENANCE
<PICTURE>
74. ADDITION OF THE LINE IN TEXT BOX
VB4 16/32, VB5 Level: Intermediate
Use the given code to force скроллер TextBoxа to move automatically when you add the new text:
' Transition by the end of text MyTextBox. SelStart = Len (MyTextBox. Text) ' the new text will stand here MyTextBox. SelText = NewText $
Back to the MAINTENANCE
<PICTURE>
75. CHECK OF ARGUMENTS IN FUNCTION VAL
VB3, VB4 16/32, VB5 Level: Beginning
At use of function Val, VB is capricious, generating a mistake of discrepancy of types. For example, Val (" 25 % ") correctly returns 25 whereas Val (" 2.5 % ") the entrance parameter incorrectly interprets and returns a mistake of discrepancy of types. It happens only when at a line there is a decimal point and a symbol of "%" or "and". To correct it, clean these symbols from a line before its transfer in Val.
Back to the MAINTENANCE
<PICTURE>
76. LABELS FOR INTERNET
VB4 32, VB5 Level: Advanced
VB5 App Wizard is able to create Web the Browser-form, but it works only with Microsoft Internet Explorer and you should drag behind yourselves SHDOCVW.DLL at distribution of a program. If you use function ShellExecute for start of file Internet Shortcut Windows starts дефолтный a browser and passes on specified URL. This method works as Microsoft and with Netscape browsers if they are correctly registered in the register, and you do not need to move any DLL at distribution of a program.
Private 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 Private Const SW_SHOWNORMAL = 1
' frm: ShellExecute uses обработчик windows. ' you can use обработчик the main window of a program ' sUrl: this name and a way to a file .url (file Internet shortcut) ' specifying your page, напр. ' c: \MyWebPage.url uses Internet Explorer ' for creation of a file of a label
Public Sub GoToMyWebPage (frm as Form, _ sUrl as string) Dim lRet as Long lRet = ShellExecute (frm.hwnd, _ "open", sUrl, vbNull, _ vbNullString, SW_SHOWNORMAL) If lRet <= 32 Then ' there was a mistake. Some of mistakes, ' returned ShellExecute: ' ERROR_FILE_NOT_FOUND = 2& ' ERROR_PATH_NOT_FOUND = 3& ' ERROR_BAD_FORMAT = 11& ' SE_ERR_NOASSOC = 31 ' SE_ERR_OOM = 8 Else ' if the browser is started! End If End Sub
Back to the MAINTENANCE
<PICTURE>
77. VIEWING MAINTENANCE HELP-ФАЙЛА
VB4 32, VB5 Level: Intermediate
Many programmers like to add to the to appendices and the help-files. How to open the maintenance help-file Windows from your program? Here an example of a code with use Win32 API of function.
' - ---Announcement Const HELP_CONTENTS = &H3& ' Functions of the Conclusion of contents Declare Function WinHelp Lib "user32" _ Alias "WinHelpA" _ (ByVal hwnd As Long, _ ByVal lpHelpFile As String, _ ByVal wCommand As Long, _ ByVal dwData As Long) As Long
' ---Code Sub OpenHelpFile (HelpFileName As String) ' HelpFileName - a way to the help-file. WinHelp hwnd, HelpFileName, _ HELP_CONTENTS, 0 End Sub
Back to the MAINTENANCE
<PICTURE>
78. THE TASK OF BORDERS MDI OF THE FORM PRECISELY AS IN DESIGN-TIME
VB3, VB4 16/32, VB5 Level: Beginning
As MDI-forms have properties border, the user can move apart their borders and change the size of MDI-forms. If the user tries to change the sizes of the form, and I do not want it (let remains such as have been created by me) procedure for event MDIForm_Resize () will rescue (whom - to taste):
Private Sub MDIForm_Resize () ' the Interdiction resizingа MDI-forms (extension of borders and its moving мышой). ‘ Годитсятолько for those MDI forms which are deduced as Normal Window If WindowState = 0 Then ' the set height MDI of form Me. Height = 6900 ' the set width MDI of form Me. Width = 10128 ' set left edge MDI of form Me. Left = 1020 ' set right edge MDI of form Me. Top = 1176 ' with the same success it is possible to use method Move to unite ‘ restoration of coordinates of the form in one command End If End Sub
Back to the MAINTENANCE
<PICTURE>
79. FAST SEARCH In the DATABASE
VB3, VB4 16/32, VB5 Level: Beginning In VB there is no built in procedure of type DLookUp from Аксесса. You can use a mentioned below code for reception Name of object on it ID:
Public Function MyDLookUp (Column As _ String, TableName As String, _ Condition As String) As Variant Dim Rec As Recordset On Error GoTo MyDlookUp_Err
' gCurBase - global переменая, specifying on текущкю DB Set Rec = gCurBase. OpenRecordset_ (" Select * From " and TableName) Rec. FindFirst Condition If Not Rec. NoMatch Then ' returns a required field if it is found MyDLookUp = Rec (Column) Exit Function End If
' return if it is not found, or there was other mistake MyDlookUp_Err: MyDLookUp =-1 End Function
Back to the MAINTENANCE
<PICTURE>
80. EASY TRACKING POSITION OF FOCUS
VB3, VB4 16/32, VB5 Level: Intermediate
Lost_Focus and Got_Focus events are often used for check of correctness of input of the text. You can use a mentioned below code for tracking focus on the form I do not program everyone контрол separately. Прместите timer control on the form, establish Interval property = 100 and Enabled = True. Name the control tmrFocusTracking. Timer event should содердать a following code:
Private Sub tmrFocusTracking_Timer () Dim strControlName As String Dim strActive As String strControlName = _ Me. ActiveControl. Name
Do strActive = Me. ActiveControl. Name If strControlName <> strActive _ Then Print strControlName and _ " - Lost Focus ", _ strActive and " - Got Focus " strControlName = strActive End If DoEvents Loop End Sub
To implement universal highlighting, replace the Print statement with this code:
Me. Controls (strActive) .SelStart = 0 Me. Controls (strActive) .SelLength = _ Len (Me. Controls (strActive))
For check (validation) correctness of the text instead of Print statement use a call of procedure of check. Use strActive in a Select Case structure By the moment when there is command Print, strActive it is equal контролу, having focus, and strControlName contains a name контрола which has lost focus. Do not place this procedure somewhere except for the timer.
Back to the MAINTENANCE
<PICTURE>
81. NOT CLOSED FORM
VB3, VB4 16/32, VB5 Level: Beginning
If to expose property ControlBox on the form in False buttons Minimize and Maximize too will disappear. We shall assume, that you wish to enable nevertheless to the user to use buttons Minimize and Maximize, but thus that it could not close the form the button with a dagger. Add a following code in event Query_Unload:
' if at you VB3, раскомментируйте a next line ' Const vbFormControlMenu = 0 Private Sub Form_QueryUnload (Cancel As _ Integer, UnloadMode As Integer) If UnloadMode = vbFormControl_ Menu Then Cancel = True End If End Sub
Back to the MAINTENANCE
<PICTURE>
82. TO CHANGE PROPERTY TO THE WHOLE GROUP KONTROLOV
VB3, VB4 16/32, VB5 Level: Beginning
You can easily make visible/invisible the whole group контролов. In a mode of development, allocate all контролы with which you will make the given operation at performance of the program. Press F4, and appropriate to property Tag a name of group, for example Group1. Now at fulfilment of group operation you will be helped by a following code:
For ind = 0 To Formname. Controls. Count _ - 1 If Formname. Controls (ind) .Tag = _ "Group1" Then Formname. Controls (ind) .Visible _ = True End If Next
Back to the MAINTENANCE
<PICTURE>
83. HOW SIMPLY TO FORMAT AND APPROXIMATE NUMBER
VB3, VB4 16/32, VB5 Level: Intermediate
Example of a rounding off with the set accuracy.
n = 12.345 Format (n, "0.00\0") ' returns " 12.350" Format (n, "0.\0\0") ' returns " 12.00" Format (0.55, " #.0 \0 ") ' returns " .60"
Back to the MAINTENANCE
<PICTURE>
84. BE CAUTIOUS, HERE TO YOU NOT WITH!
VB3, VB4 16/32, VB5 Level: Intermediate
VB the programmers who have got used to With, can be confused following feature VB. We shall consider a code:
Dim x As Integer Dim y As Integer Dim z As Integer x = 10 y = 20 z = 0 ' let function max returns greater of two numbers if (z = max (x, y))> 0 then Msgbox CStr (z) Else Msgbox " How Come? " End if
You expect, what will be highlighted 20 how should occur in With? However, VB will compare z with RHS (right-hand side) the-right party, even before assignment, irrespective of brackets. Be close.
Back to the MAINTENANCE
<PICTURE>
8.5 TO USE BACKQUOTES INSTEAD OF APOSTROPHES
VB3, VB4 16/32, VB5 Level: Intermediate Often at use Transact-SQL I should intercept comments of the user from текстбокса and to send them to a database. However, if the user presses an apostrophe in текстбоксе, there is a mistake of time of performance as SQL Server uses an apostrophe as an attribute of the end of a line. To bypass this problem, intercept input of the user in event KeyPress and replace an apostrophe on here such кавычку «‘» (ASCII (145)):
Private Sub Text1_Keypress_ (KeyAscii as Integer) If KeyAscii = 39 Then KeyAscii = 145 End If End Sub
Also it is possible to replace all unary inverted commas on «‘» before sending in SQL Server.
Back to СОДЕРЖАНИ
<PICTURE>
86. DISTRIBUTION OF NEW VERSIONS OF THE PROGRAM ON THE NETWORK
VB4 16/32, VB5 Level: Intermediate
I write VB programs for a network with approximately 300 users. Difficultly enough in due time to follow distribution of each new version of a program by all machines, therefore I use such feature VB автоинкрементирующаяся numbering of versions for check, whether the upgrade of a program by the concrete machine is required. At compilation of a program establish автоинкремент versions in On. Keep yours setup/upgrade files on a network disk (urgently I recommend to use UNC-ways (\\ ¿¼n_¼áÞ¿¡Ù \¿¼n_ñ¿ß¬á) rather than simply names of disks), and put an INI-file of a program in which number of the newest version is specified. Then insert a following code into a program, event Form_Load:
Open IniFile $ For Input As #1 Line Input #1, sUpgradeVersion $ Close #1
If sUpgradeVersion> (Format (App. Major, "00") and "." And _ Format (App. Minor, "00") and "." And _ Format (App. Revision, "0000")) Then ' start of a upgrade from network disk End End If
If the version in an INI-file above, than the version which has been written down in .exe the program the automatic device will start the program of a upgrade on a network and will finish the performance, that is all the necessary files can be replaced. It is especially useful, when you only start to write a program, that is upgrades and фиксы appear almost time in some days.
Back to the MAINTENANCE
<PICTURE>
87. TO CLOSE THE WINDOW OF THE PROGRAM AS IT DOES WINDOWS 95
VB3, VB4 16/32, VB5 Level: Intermediate
Place this code in declaration section the module:
Public Sub Win95Shrivel (xForm As Form) ' minimizes a window xForm. WindowState = 1 End Sub
Cause it from procedure Unload of the form
Private Sub Form_Unload (Cancel As _ Integer) Win95Shrivel Me End Sub
Each time at unloade forms it all over again быренько is turned off to таскбару, and then disappears. It works and in Windows 3.1x too.