For example:
The function process is defined as follows:
Public Function f! (X !)
F = x + x
End Function
The main program is as follows:
Privme Sub Commandl_Click ()
Dim y %
Y = 3
Print f (y)
End Sub
The preceding example shows that x is a single-precision parameter, and y is an integer parameter. When the program is running, the compilation error message "The ByRef parameter type does not match" is displayed.
If the value is numeric, the value of the real parameter is passed to the form parameter according to the type of the parameter. For example:
The function process is defined as follows:
Public Function f! (ByVal x %)
F = x + x
End Function
The main program is as follows:
Priva ~ SubCommandI_Click ()
Dim y!
Y = 3.4
Print f (y)
End Sub
The result displayed after the program runs is 6.
5. Scope of Variables
A local variable is called during the process to allocate the storage space of the variable. When the process call ends, the allocated storage space will be reclaimed, that is, called once, initialized once, and the variable will not be preserved: form-level variables: when the form is loaded, the storage space of the variable is allocated until the form is detached from the memory.
For example, if you want to enter a value in the text box, press the Eenter key each time until the input value is 9999. After the box is entered, calculate the average value of the input number.
Private Sub Textl_Key Press (Key Ascii As Integer)
Dim sum !, N %
If KeyAscii = 13 Then
If Val (Text1) = 9999 Then
Sum = sum/n
Print sum
Else
Sum = sum + Text1
N = n + 1
Text1 = ""
End If
End If
End Sub
There is no syntax error in this process. You can enter several numbers for the running program, but when you enter 9999, the program displays an error of "overflow. Because sum and n are local variables, each time you press a key, the local variables are initialized to o, so there will be the above error.
Improvement Method: declare the local variables to be preserved as Static variables or form-level variables. The variable to be preserved can also be declared as a form-level variable in the General Declaration section.
6. "stack overflow" occurs in recursive calls"
The following describes the process of finding a factorial recursive function:
PublicFunctionfac (nAsInteger) Asinteger
If n = 1 Then
Fac = 1
Else
Fac = n * fac (n-1)
End If
End Function
Private Sub Commandl_Click () 'calls the recursive function and shows that fac (5) = 120
Print "fac (5)": fac (5)
End Sub
If the value of N is 5 when the main program is called, 120 is displayed. If the value of N is-5, an error message "overflow stack space" is displayed.
In fact, every recursive call is performed. The system stacks the current status information (such as the form parameter, local variable, and return address at the end of the call) until the recursion condition is reached. In the preceding example, when n = 5, the parameter n-L is called every time, until n = L is the end of the recursive call, and the current parameter is continuously popped up from the stack until the stack is empty. When 'N'-5 is used, the n-1 parameter is-6, the stack is pressed, the recursive call is performed, and n-1 cannot reach the termination condition of N = l until the stack is full, generate STACK benefit error information.
Therefore, when designing a recursive process, we must consider the conditions for termination and the value or operation at the time of termination in the process, and each recursive call, the parameters must converge to the end direction, otherwise, stack overflow occurs.
Chapter 7 common controls (1)
7.1 key knowledge points
1. Single-choice buttons and check boxes
Value is a common attribute of Single-choice buttons and check boxes. It is used to check whether single-choice buttons or check boxes are selected.
Single-choice buttons and check boxes can respond to click events, but usually do not need to write the event process.
2. Framework
The main function of the framework is to combine other controls to classify various functions in a form for user recognition. After a frame is used to group the single-choice buttons in the same font, each group of single-choice buttons is independent, that is, operations performed on one group of radio buttons do not affect the selection of radio buttons in other groups.
Caption is an important attribute of the framework.
Generally, you do not need to write the event process.
3. list box
The main attributes of a list box include text, list, listlndex, listcount, And so ~ Ed. When the multiselect attribute is 1 or 2, multiple selections are allowed. In this case, the selected attribute is often required to determine which items are selected.
The commonly used methods of the list box are addltem, removeltem, and clear.
In general, the list box does not need to be written, and the items in the list box do not need to be changed.
4. Combo box
A combo is a control formed by combining the features of a text box and a list box. The type of the combo is determined by its style attribute. Drop-down box (style is 0) and simple box (style is 1) allow users to enter options not in the list in the text box.
5. scroll bar
Common attributes that are unique to a scroll bar include Max, Min, value, smallchange, and largechange.
The important events of the scroll bar are change and scroll.
6. Clock Control
The commonly used attribute of the clock control is interval, and its value is in the unit of 0. 001 seconds.
The enabled attribute of the clock control is different from that of other controls. When the enabled attribute of the clock control is true, the timer event occurs at a millisecond interval of the interval attribute value. If the enabled attribute of the clock control is set to false or the interval attribute is set to 0, the timer stops running.
Timer is the only event of the clock control.
You can use the clock to play images continuously to achieve animation effects.
7.3 Common Errors and difficulties
1. Missing Object Name
During vbprogramming, a common mistake for beginners is to omit the object name, especially when using the list box. For example, if you want to reference the currently selected project in the list1 list box, listl. List (listlndex) is incorrect. Even if the current focus is on listl, VB does not regard listlndex as the attribute of list l, but a variable. Therefore, the correct reference method is listl. 1ist (listl. listlndex ).
2. Columns attribute of the list box
The columns attribute of the list box determines whether the list box is horizontal or vertical, and how to display items in the column. If horizontal scrolling is performed, the columns attribute determines how many columns are displayed, as shown in Table 2.7.2. Figure 2.7.1 shows a list box with two horizontal scrolling columns.
During the program running, this attribute is read-only. That is to say, you cannot change the multi-column list box to a single-column list box or change the single-column list box to a multi-column list box.
Columns attributes of the list box in Table 2.7.2
Column Type
0 (default) Items 1 to n are arranged in one column, and the list box vertically scrolls the project in multiple columns. first fill in the first column, then fill in the second column ...... The list box is horizontally rolled and a specified number of columns are displayed.
3. Domain-level verification
Domain-level verification refers to the verification of data input to an independent domain. During domain-level verification, content in a form-like domain is generally not considered. The appropriate time for domain-level verification is:
(1) When you enter a key in a domain, a keyboard event (KeyDown, KeyUp, and KeyPress) is involved ). For more information, see section 4.7 of the tutorial.
(2) when a user attempts to leave a domain, the CansesValidate attribute and the Validate event are involved.
(3) When the content of a domain changes, the Change event is involved.
The CausesValidation attribute and the Validate event usually work collaboratively.
The CausesValidate attribute determines whether the Validate event occurs. If the CausesValidate attribute of the control is False, the Validate event of the control will never occur. If the CausesValidate attribute of the control is Tree, when the focus attempts to move to another control whose CausesValidate attribute is True, the original control's Validate event occurs: when the focus attempts to move to another control whose CausesValidate attribute is False, the Validate event of the original control does not occur temporarily. When will this happen? It does not occur until the focus is moved to a control with the CausesValidate attribute being True.
For example, suppose there is a program as shown in 2.7.2. When the focus attempt is to move from textl to text2, The validate event of textl occurs: Similarly, when the focus attempt is to move from text2 to textl, The validate event of text2 occurs. When the focus attempt is to move from textl to text3, The validate event of texti does not occur temporarily because the causesvalidate of text3 is false. Then, if the focus attempt is to move to text2, The validate event of textl occurs.
Figure 2.7.2 causesvalidate attribute and validate event
This feature of the causesvalidate attribute and the validate event is often applied in the program shown in 2.7.3. When invalid data is entered in the text box and you do not know how to enter valid data, you often choose the Help Command for help or select the cancel command to end the data input. In this case, you do not want to execute the verification program. If the verification program is executed and invalid data is found, the help or cancel option cannot be selected, and the user is pinned. Now, you only need to set the causesvalidate attribute of the text box to true, and the causesvalidate attribute of the command button to false. When the verification program is placed in the validate process, the problem is solved. By default, the causesvalidation attribute of all controls is tree.
Figure 2.7.3 causesvalidate attribute and validate event of the command button
Not all controls have a validate event. Only controls that can be used to input data (such as text boxes, check boxes, and scroll bars) have this event. The validate event process is as follows:
Privme sub object_validate (cancel as Boolean)
...
Endsub
When the cancel parameter is set to tree, the focus will not leave the object.
If you want to use the validate event and causesvalidation attribute to verify the data, you should use the following program.
Sub txtMath_Validate (Cancel As Boolean)
If Val (txtMath. Text) <0 Or Val (txtMath. Text)> 100 Then
Cancel = True
End If
End Sub
Common controls (2)
8.1 key knowledge points
1. Menu
Each menu item is a control with a Click event. When the program is running, if you Click a menu item, the Click event process of the menu item is run.
You can use the menu editor to design a pop-up menu and use the PopupMenu method to display it in the program.
Controls can be used to implement real-time menus, that is, menus dynamically created by applications as needed. Use the Load statement to create menu items and UnLoad to clear them.
2. Dialog Box
In VB Applications, there are three types of dialog boxes: pre-defined dialog box, General dialog box, and user-defined dialog box.
The pre-defined dialog box is a system-defined dialog box that can be directly displayed by calling functions such as InputBox and MsgBox.
The general dialog box provides users with six types of dialog boxes: open, save as, color, Font, print, and help. Using them can reduce the workload of the design program.
The custom dialog box is a form with special attribute settings. BorderStyle, ControlBox, and MaxBu ~ On And MinButton should be 1, False, False, and False respectively.
The dialog box is divided into two modes.
3. Multiple Forms
Common methods and statements for forms include Load, Unload, Show, and Hide.
Multiple events are involved in the loading and unloading of forms. For the timing and order of these events, see section 4.5 of the tutorial.
4. Advanced controls
In VB, users can load and use many extended advanced controls provided by VB and developed by third parties. Their properties can be simply set on the property page.
(1) The sstab control can be used to create tabs.
(2) progressbar is used to indicate the process of transaction processing.
(3) The slider control is a window containing a slider and a selectable scale mark. It provides you with the scale setting function in a visual way.
(4) updown can be used to set certain program parameters, which are usually bundled with the text box.
(5) animation is used to show AVI video files. The four important methods of animation are open, play, stop, and close. common attributes include center and Autoplay. If the center is tme, the animation is played in the center of the control. If autoplay is true, the animation is automatically played when the file is opened with open. Otherwise, play is required.
5. Mouse
In addition to click and dblclick, mouse events include mousedown, mouseup, and mousemove.
The three mouse events have the same parameters.
(1) button: You can use vblefibu ~ On, vbrightbutton, and vbmiddlebutton can easily detect which mouse button is pressed.
(2) shift: You can use vbaltmask, vbctrlmask, vbshiftmask, and their logical combinations to check the statuses of ALT, Ctrl, and shift keys. If you want to check whether the CTRL and shift keys are simultaneously pressed, apply the expression (shift andvbctrlmask) and (shifiandvbshifimask ).
(3) X, Y: indicates the position of the current mouse pointer.
The meanings of the MouseDown and MouseUp buttons are different from those of MouseMove. For MouseDown and MouseUp, the button parameter specifies which mouse button triggers the event, and for MouseMove, it indicates all the current statuses.
6. keyboard
Keyboard Events include KeyPress, KeyUp, and KeyDown.
The information received by KeyUp and KeyDown is not exactly the same as that received by KeyPress.
("KeyUp and KeyDown can detect function keys, edit keys, and arrow keys that cannot be detected by KeyPress.
(2) KeyPress receives the ASCII characters entered by the user through the keyboard. For example, if the keyboard is in lowercase and the user presses "A" key on the keyboard, the KeyAscii value is 97: When the keyboard is in uppercase, the user presses "A" key on the keyboard, the KeyAscii value is 65. KeyUp and KeyDown receive the Keyboard Scan code that the user presses on the keyboard. For example, the KeyCode value is 65 regardless of whether the keyboard is in the lower case or upper case.
In short, if you need to detect the characters entered by the user on the keyboard, you should select the KeyPress event: If you need to detect the physical key that the user presses, select the KeyUp or KeyDown event.
By default, When you click a control on a form, the KeyPress, KeyUp, and KeyDown of the form do not occur. To enable these three events, you must set the KeyPreview attribute of the form to True, and the default value is False.
Once the KeyPreview attribute of the form is set to True, the keyboard information must go through two platforms (the form-level keyboard event process and the control's keyboard event process) to reach the control. For example, assume there are two processes:
SubForm_KeyPress (KeyAsciiAsInteger)
KeyAscii = KeyAscii + 1
End Sub
Private Subtxt Test KeyPress (KeyAscii As Integer)
Key Ascii = KeyAscii + 1
End Sub
When you enter the lowercase character "a" on the keyboard, txtTest receives the character "c ".
This feature can be used to verify the input data. For example, if all the characters are converted to uppercase in the KeyPress event of the form, all controls on the form cannot receive lowercase characters.
The user should decide whether to put data verification at the form level or the control level as needed.
7. Normal drag and drop
The differences between manual drag-and-drop and automatic drag-and-drop are shown in Table 2.8.1.
Dragging the source object at runtime does not automatically change the location of the source object. You must program it to re-place the control.
The drag icon is determined by the Draglcon attribute of the source object.
Table 2.8.1 differences between manual drag-and-drop and automatic drag-and-drop
Automatic drag and drop of Objects
The source object DragMode is set to 0 and the Drag method is used to start the "Drag" operation. The DragMode is set to 1 without the MouseDows event.
A DragOver event occurs on the intermediate object. A DragOver event occurs on the intermediate object.
DragOver and DragDrop events of the target object: DragOver and DragDrop events
8. OLE drag and drop
When the OLEDragMode attribute of the source object is] (Automatic), the OLE "drag" operation is automatically supported. When the OLEDropMode attribute of the target object is set to 2 (Automatic ), automatically supports the OLE "release" operation.
Controls that fully support OLE drag and drop include TextBox, PictureBox, and Image.
The following controls are supported: ListBox, ComboBox, DirListBox, and FileListBox.
Controls that only support OLE drag-and-drop events include label, commandbutton, optionbutton, checkbox, frame, and DriveListBox.
8.3 Common Errors and difficulties
1. Differences between menu items in the top menu bar of the form and those in the sub-menu
The menu items in the top menu bar of the form are defined in the menu editor, but they are different.
(1) Shortcut Keys cannot be defined for menu items in the top menu bar of the form, while shortcut keys can be used for menu items in sub-menus.
(2) When there is a key letter (the letter after "&" in the menu title), press Alt + the key letter to select the menu item in the top menu bar of the form, press the key letter to select the menu items in the sub-menu (when the sub-menu is opened ). When the sub-menu is not opened, you cannot select a menu item by pressing the key letter.
(3) Although all menu items can respond to the click event, the menu items in the top menu bar of the form do not need to write the event process.
2. setting attributes of the general dialog box does not take effect in the program.
In the program, attribute settings in the general dialog box do not work. In most cases, attribute settings are performed only after the pop-up dialog box. For example, the following program code has such a problem. The correct method is to put the pop-up dialog box statement at the end, that is, put commondialogl. Action = l behind all attribute setting statements.
Commondialog1.action = 1
Conmaondialog1.filename = "*. BMP"
Commondialogl. initdir = "C:/Windows"
Commondialog1.filter = "pictures (*. BMP) | *. BMP | all files (*. *) | *.*"
Commondialog1.filterindex = 1
3. An error occurred while adding an existing form to the project.
Loading Errors often occur when you use the "add form" command in the "project" menu to add an existing form, most of which are due to form name conflict. For example, if you open a project named Forml, and want to load the Forml form of another project, an error will certainly occur.
[Note]
The difference between the form name and the Form file name. In a project, there can be two forms with the same file name (distributed in different folders), but two forms with the same name cannot appear at the same time.
4. Create a Real-Time menu'
Real-time menus are dynamically created by applications as needed. In VB, a common real-time menu is a "file" menu, which displays the recently used project.
To create a real-time menu, you must combine the control array, use the Load statement to create a menu item, and use UnLoad to clear the menu item.
Create a Real-Time menu;
(1) create a sample menu item in the menu editor.
The attributes of the sample menu items are shown in Table 2.8.4. SET Index to o, indicating that the sample menu item is an element of the control array, and its subscript is o. The Name attribute of the sample menu item is required and will be used as the Name of the control array. On the-F side, assume that the array is named NameA ~ Ay. Visible can be set to True. If it is set to False, the menu item is invisible at the beginning.
Table 2.8.4 real-time menu sample menu items
Property Name Caption Index Visible
If the set value is required, it can be 0 or False.
(2) create a menu item using the Load statement in the program.
For example, Load NameArray (1) creates a new menu item (marked as 1 in the control array F), sets its Visible attribute to True, and sets the Caption attribute.
The menu items dynamically created inherit most of the attributes except Index, so you must set the Caption and Visible attributes. In addition, the position of the sample menu item in the menu system determines the position where the new menu item appears.
(3) write code for real-time menu items.
Each real-time menu item is a member of the control array with the same name and shares the event process.
The following is a real-time menu item code example:
Subnamearray_click (index as integer)
Select case index
Case 0
Msgbox ("namearmy (0) (sample menu item) is clicked! ")
Case 1
Msgbox ("namearray (1) (the first single order) isclicked! ")
Case 2
Msgbox ("namearray (2) (second real-time menu item) is clicked! ")
End select
End sub
(4) Delete real-time menu items.
Although visible is set to false, real-time menu items are not displayed when the program is running, but sometimes real-time menu items need to be destroyed from the memory.