-------------------------------------------------- ------------------------------ Visual Basic has become structured like C, as flexible like Pascal, like Fortran Working in science, more suitable for commercial work than COBOL, more suitable for operational data than XBase, may even be like SMALLTALK, like LISP, longer than list processing. - Quotation from "Visual Basic 5.0 Core Technology" --------------------------------------- ---------------------------------------- a few small things Visual Basic is powerful But I want to say some little things in the beginning. Although it is a small thing, it is sometimes a headache, so let's talk first. If you often name the engineering as the Chinese long file name, you may also encounter an "unknown error" prompt when starting VB5, then run "regedit", open "HKEY_CURRENT_USER / Software / Microsoft / Visual Basic / 5.0 / Recentfiles "button, delete the string value named" 1 ", and VB5 can run normally, but" the latest "in" Open "is emptied. Open the "Requirements Variable Declaration" option. No variable declaration can be normal in many cases, but if there is a spelling error in the program, you will waste a lot of time for the inexplicable error of the program. In addition, I generally turn off "Automatic Syntax Test" because it is very annoying, and after turning off, the grammatical error programs are "red display" (default), enough to prompt. The use of the system color. Windows can customize the system color, that is, the button surface is not necessarily gray, the button text is not necessarily black, so a graph in a gray background is not necessarily fused with the form background. Some people also define the form background color to be gray, but the border is still the user-defined color! So still pay attention. Try to use the constant. VB defines a lot of constants. For example, VBCR is a carriage return, VBLF is a wrap, and VBCRLF is a return bank. Delete the icon Press the DEL key. I have seen an article saying that ICON is to be added to Form_Load = loadingPicture ("", first, loadPicture ("" Return Nothing, so you can write set me.icon = Nothing; second, as before The statement is also redundant. Multi-use hot bonds. For example, Ctrl J Displays the list of properties / method lists, CTRL SHIFT J Display constant list, Ctrl i displays fast information, CTRL Shift i Displays parameter information. (VB cannot be customized to the hotkey.) Full compilation executive. In most cases, execute the program, but full compilation execution can help you quickly exclude some low-level errors, especially should be used for API callback functions, etc. When the program is debugged. DIM, each variable should be declared. Used in other languages such as C, Pascal, etc., the variables are generally defined in VB: DIM I, J AS INTEGER, think of I, J two Integer, actually defining a variant variable I and an integer J.
The correct method should be DIM I as Integer, J AS Integer. Predefined objects and collection of collections. Such as app, err, screen, etc. Object, Forms, Controls, etc. Perhaps our do everything possible to achieve an unusually simple solution in these objects and collections. Search of various attributes. For example, I compiled the Russian block event programming for PictureBox, and it is necessary to prevent the focus away from the focus, and then find that the form has a keypreview property, so now does not need to be fired, but the program is more stable. Pay attention to the transmission method of the parameter. For example, I don't know how to control the input of the text box. Later, I know that I can control the keyascii assignment, this finds that Keyascii is passed by the pointer. In fact, the parameters of the event provided by the VB are passed by the pointer, which can basically be sure to control the behavior of this event after the value of this parameter can be controlled. The call method of the SUB. It is used to the method of calling a function in C or PASCAL, which is also called in VB: Test (x), function names, and parentheses, the space between the parentheses makes it different from the normal call; if it is a function, it does not care about its return value If someone writes: Temp = Test (x). In fact, the correct call method is Test X or Call test (x), of course, it is not necessarily an error like the writing method, but it should be pointed out that I used to use the syntax like Test (X). The array starts from 0. DIM X (10) is actually the same as DIM X (0 to 10), you get eleven elements, not ten. Special, Redim x (0) is equivalent to Redim x (0 to 0), not to delete all array elements, but have an element, be careful (to delete all elements of the dynamic array, with "ERASE"). True false value. The value of TRUE in VB is -1. The value of false is 0. When it is directly determined with the IF statement, there is no difference, but if an aliquot or NOT is used, it may be a result. -------------------------------------------------- ------------------------------2 Chinese function name, variable name, control name, and form name use VB5 and above Regardless of Chinese and English, Chinese functions, variable names, control names, and form names can be used. Every time you reference Chinese, you have some power. Something is not from the heart, so I am now the most skilled operation is "Ctrl C", "Ctrl X", "Ctrl V". I have tried in a variety of languages, and only VB allows this. Visual FoxPro should also, but I think it as the same kind of VB, other such as VC, Dephi, C Builder, Perl, Even JavaScript, Vbscript, can not do this. I have recently heard a statement, thinking that using Chinese functions, variable names, control names, and form names may be difficult to compatibility. Ok, let's take a look at the results: there will be Chinese function names, variable names, control names, and form names, and then find Chinese functions in compilation, variable name - can't find it, then Find control names and form names - found.
In this way, we can determine that the function name and variable name are compiled into the form of an address, so I can't find it; then find the control name and the form name indicating whether the controls and forms are called with the name? Non-also, not, the reason why the control name and the form name is because you may access the control and the "name" attribute of the control in the program - "I want to give it!" Of course, whether to use Chinese programming is determined by yourself. I have used Mail to "network ant" authors, I hope he will change the interface to Chinese and finally, why to use Chinese programming? -------------------------------------------------- ----------------------------- Triple function call dialog box VB has MSGBOX and InputBox two functions for most commonly used The input and output operation, but sometimes it is not our needs, and MsGBox and Inputbox are suspended when executed, most of us is what we want, but in some cases, we hope to perform this type of input and output. Do not suspend the program, but can still execute the program in the background, with the mode dialog, but lost the speed and convenience of MSGBox and InputBox, then the functional call dialog is the preferred scheme. Of course, this only needs to define a function prototype in the standard module, and then call "Custom Form .Show VBModal in this function". The most important question here is: How is the return value returned? First, a global variable can be defined, and these variables are detected after "custom form" uninstalled, which changes to which changes have been made. This method is not bad, I am also used, but it has a problem: use global variables. There are too many global variables, which will cause chaos, one possibility that you can also remember this variable, and you may use the same name when you call the variables else, thereby causing errors, additional, maybe you Joining a new project from each of the previous several programs, it has found that many variables are the same name, and they have to re-change the quantity name. Second, you can use the next method I introduced.
Define a "custom function" of a public type in "Custom Form", add initialization code, then call "Me.Show VBModal", then "custom function = return value", "unload me", When uninstalling the form, you do not unload, hide, and then call "Custom Form. Custom Function" in a function of the standard module defined, as follows: Option ExplicitPrivate Return Value AS StringPublic function Custom Function () AS String Initialization Me.Show vbModal custom function return value = Unload MeEnd FunctionPrivate Sub Form_QueryUnload (cancel As Integer, UnloadMode As Integer) If UnloadMode = vbFormControlMenu Then cancel = True canceled _Click End IfEnd SubPrivate Sub cancel _Click () return value = "" Me .Hidend subprivate sub determination _Click () return value = Enter value me.hidend Sub final, I want to say, because the mode form does not block the program, it is possible that this function is called multiple times, thus "ME. "Runtime Error" when Show VBModal, if you do not want multiple forms, you should avoid this; if you want multiple forms, you should use "New" to generate new "in the standard module" Custom Form, then call, as follows: Public function Custom Function () AS String DIM New Form AS New Custom Form Custom Function = New Form. Custom Function End Function Perhaps Someone Is it really unloaded to be suspicious, very good, you can use "forms" to test yourself. -------------------------------------------------- ------------------------------------------------------------- Of course, I don't have to eat, it makes some programs look more comfortable - at least I think.
For example, VB's WeekDay returns an Integer value, but we want to display the string, the format function returns the English string, so we need to complete the conversion: Private function asking the week (Byval Week AS Integer) AS STRING SELECT CASE Weekly Case vbsunday asked Week = "Sunday" case vbmonday XVAY = "Monday" case vbtuesday asking We= "Tuesday" case vbwednesday inquiry Week = "Wednes" case vbthursday XIDAY = "Thursday" Case vbfriday Xing Week = "Friday "Case vbsaturday XD SELECTEND FUNCTION If you use array, you can write: private function asking Week (Byval Week AS Integer) AS String Dim Week Week = Array (" Japan "," One "," Two " , "Three", "Four", "Five", "Six" inquiry Week = "Week" & Week (Week - VBSunday) End Function Specific Selection That method is of course determined by you. What I want to say is this method It can also be used in other languages, but to note that the arrays are not select case, most tasks that the latter can do cannot be replaced by array, in fact, VB's SELECT CASE is almost all the most powerful, good use of SELECT CASE will streamize a lot of code. However, there are still some other features in VB, making it a wide range of applications, and some cases in this area, please refer to my next article "VB vs Perl". --- -------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Very powerful "custom events". Define events in the class module, and then generate events with raiseevent when appropriate, but there is no more, but When I compiled a Socket communication, I found that the functionality of the event was bigger than I thought. As an example of Socket communication, what I have to do is: Different Socket strings are given to different forms. I have made a class to analyze the socket string and generate different events. The problem is that there is only one Socket control to receive Socket information, so the object generated by this class can only be "main" main forms with the Socket control "So, whether the event generated by this class is just the" main form "? I thought it was. So I am programmed to each event in the "Main Form" and call the function of the PUBLIC type of different forms in the event. But there is a problem: I have toned forms may not be loaded yet, and I don't want it to load it now. I use "form .visible" to detect formal loading or not, it is very unsatisfactory.
Later I found that I can do this: the object generated in the "main form" is defined as public, such as "protocol", as follows: Option ExplicitPublic WitHevents Analyst AS Protocol Private Sub Form_Load () Set Editor = New Protocol Socket Control .connectend Subprivate Sub Socket Control_DataArrival (Byval Bytestotal As Long) Dim Temp AS STRING Socket Control. Analysis Information Tempend Sub In a form that requires events, definition: Option ExplicitPublic Withemations Event Generator AS Agreement Private Sub Form_Load () SET Event Generator = Main Factor. Analyst End Subprivate Sub Event Generator_ 来 () Me.caption = "Escape!" End Sub This way, this method has completed this operating. You can program this event in all forms or only to several forms, so that complicated tasks can be done with a simple method. -------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The control is not strong, but the resources are small. But there is another side: feeling. Because the PictureBox control is true control: there is a window class derived; the image control is not. This can be detected by SPY . Thus, we know that the image control is actually drawn on its parent form, although it is very small, but when refreshed the control, even if it is not refreshed, it is refreshed throughout. The mouse is turned off within the parent window. In this way, in the case of frequent refresh (such as progress bar), as long as the mouse is within the parent form, it will keep flashing. At this time, use the PictureBox control instead of the Image control, flashing is only inside the control. (2 color mouse cursor Generally, the naked eye does not flash, 256 color mouse cursor is very obvious.) --------------------------- -------------------------------------------------- --- Seven control arrays Dynamically increase control array is not a real array, so its dynamic increase and ordinary array are also different. Added an element of an array of controls, uses "LOAD control (N)"; deletes an element of an array of controls, uses "Unload control (N)"; n from it; but then it will find controls after several times "Empty cave" appears in the array, although you can use "for Each" to access each item, but it has been troublesome. Originally, if the control index is "long", "empty" problem is not very serious. Because there are 4,294,96,7295 numbers, even if a "empty hole" is generated for a second, it is also required to have repetition possibilities in 136. In these years, even if we don't have to upgrade Windows, Windows itself will collapse in our software.
Just a pity, the control index is "integer", that is, if a "empty hole" is generated in a second, it will generate a repetition number after 18 hours, resulting in an error.
For example, I solve this in the Socket server: private sub connection _ConnectionRequest (index as integer, byval requestid as long) if index = 0 THEN DIM connection AS long connection number = Space LOAD connection (connection number) connection (connection) Number .localport = 0 Connection (Number). Accept Requestid adds connection connection, "unknown", 0, connection (connection number) .Remotehost, _ connection (connection number) .remotehostip, "Operation" end iFend Subprivate Function empty () AS Long Dim I as long, Temp as long on error Goto Complete for i = connection .lbound to connection .ubound Temp = Connection (i) .localport next i complete: Space = IEND FunctionPrivate SUB Add connection (connection) AS Long, Username AS String, Level As Long, _ Hostname AS String, IP as String, Operation AS String) DIM Item As ListInTItem Set Item = User List .ListItems.Add (, "U" & Connection Number, User Name) Item.Subitems (1) = Level Item.Subitems (2) = Host Name Item.suBItems (3) = IP Item.Subitems (4) = Operation End Sub Because "Empty" does not affect the index value of the array control, So delete more simple: Private sub connection _close (INDEX AS INTEGER) Removes connection indexend subsprivate sub connection _ERROR (Index As INTEGER, BYVAL NUMBER AS INTEGER, _DESBRIPTION As String, Byval Scode As Long, _ByVal Source As String, ByVal HelpFile As String, _ByVal HelpContext As Long, CancelDisplay As Boolean) ShowError "connection" & Index & "error:" & Description CancelDisplay = True to delete the connection IndexEnd SubPrivate Sub delete a connection (ByVal Index As LONG) IF Index> = Index THEN Index = Index - 1 Unload Connection (INDEX) User List .ListItems.Remove "U" & Indexend Subprivate Sub Showerror (Details As String) Me.caption = Details End Sub Finally, I said, VB5 After calling the "close" method, the Socket control is not necessarily "close". It is said that it is necessary to do a "do" loop to constantly detect "State" attribute until it is really "close", I am very It is evil, so it is now generally used with VB6's Socket control.
-------------------------------------------------- ------------------------------------------------------------------------------------------------------------- The saying is transmitted by reference, so it can control the purpose of controlling its input by assigning it: private sub input box _KeyPress (keyascii as integer) if keyascii> VBKEY9 or Keyascii
-------------------------------------------------- ---------------------------- Nine String Return Value when calling the API Description API String Definition To "BYVAL" can be used in the API: Declare Function getClassName lib "user32" alias "getclassnamea" _ (Byval HWnd as stay, _ Byval nmaxcount as long) AS Long and get string to get strings Return value can be used in such a function: public function form class name (Byval Handle as long) AS STRING DIM class name AS String * 256, class name length AS INTEGER class length = getClassName (handle, class name, 255) Form Class name = MID (class name, 1, class length) End function can also be used with such a function: public function form class name (Byval Handle As long) AS STRING Form Name = Space (256) getClassName handle, window Physical class name, 255 form name = API string restore (Form name) End functionpublic function API string restore (original string as string) AS STRING DIM length As long length = INSTR (1, original string, VBNULLCHAR) - 1 IF length <0 THEN API string restore = original string ELSE API string restore = left (original string, length) end ifnd function second method is relatively universal, the first method is relatively simple, specifically used As you wish. But I want to say, I used to call the API (first), but now I like to use the growing string (second), the problem of fixed length strings is first defined "DIM class name" AS String * 256 "After completing the API, execute" class name = MID (class name, 1, class name length) "," Classification "is not a real class, but" real class name Space (256 - LEN (true class name) ", not" I want it too ". ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- Ten generation errors, timely, "runtime error", not only conducive to debugging procedures, but in some cases, it can simplify programming. First, you should know that "on error" statement has strong inclusive, for example There is "On Error Goto Error" in a function, and another function is called in this function. This "another function" produces "Running error", which will also "goto error". Because of this, we You can generate "Runtime Errors" in "another function", and the "on Error" is unified in the original function to simplify programming.
Private function executes the MCI command (command AS String) AS String Dim Returns AS String, execute AS Long Returns = Space (256) Execution = McISendString (command, return, 255, 0) IF execution = 0 THEN Perform mci command = API string restore (return) Else err.raise vbobjectError 1, _ "Execute MCI command error:" & vbrlf & _ command & vbcrf & "Return:" & Execute End IFEND FUNCTION "GOTO" statement has fallen Because it is not structured, but after VB made some hands and feet, "GOTO" is also very easy to use, and it is not easy to erode: VB's line number is effective. This means that in different functions, it can be defined as the line number "error", and it will not be wrong, so "Goto" seems to be "structured". -------------------------------------------------- ----------------------------- Eleven random number, the random number is also a simple question: first use "randomize" Initialize the random number generator, then you can generate random numbers with "RND". (The reason for initialization is that the random number is actually random, and if the value is initialized, if it is determined, the resulting random number sequence is also determined, so it is generally initialized the random number generator with the current time, but I will discuss it in detail here. I want to say here is another problem. For example, WinAmp random playback, just simply calls the random number generator, so it is possible to just listen to this song, the random number generator generates this number, just listen to this song, and maybe some The song can play once after all the cycles. Simple call random number generator, more serious problems will appear on "digging": we customize 10 × 10 square arrays, 99 thunders, the more difficult it is to produce the right thunder.
So I generate "random" "basemap" in the "Russian square": DIM I as long, J AS long, n as longn = file filter .Listcount - 1IF ListCount (random control) <> (N 1 ) THEN IF N> = 0 THEN RedIM Random Control (0 to N) IF T. This is really unpleasant! Later, I found that "orthodox" method should be like this: (standard module) Option Explicitpublic prevwndProc As longprivate system bar object AS New CollectionPublic function SubwndProc (Byval Hwnd As Long, _ byval msg as long, Byval WParam as long, _ byval lParam As Long) As Long On Error Resume Next Select Case Msg Case TRAY_CALLBACK Dim CurTray As the system Tray system Tray Set CurTray = Object .Item ( "H" & hwnd) CurTray.SendEvent lParam, wParam End Select SubWndProc = CallWindowProc (PrevWndProc, hwnd , MSG, WPARAM, LPARAM) END FUNCTIONPUBLIC SUB Register New Object (New Object AS Board, H Window As "System Bar Object .Add Item: = New Object, Key: =" H "& H End Subfublic SUB Logout Object (H window as long) system bar object. Remove "h" & h window END SUB named "System Bar" class module: (part) public SUB initialization (HWND As Long, Icon as stdpicture, _ Optional Tip as string = defTrayTip) gInTray = defInTray gAddedToTray = False gTrayId = 0 gTrayHwnd = hwnd InTray = defInTray TrayTip = Tip Set TrayIcon = Icon registering new object Me, hwndEnd SubPrivate Sub Class_Terminate () If InTray Then InTray = False cancellation objects gTrayHwndEnd SubFriend Sub SendEvent (MouseEvent As Long, Id As Long) Select Case MouseEvent Case WM_MOUSEMOVE RaiseEvent MouseMove (Id) Case WM_LBUTTONDOWN RaiseEvent MouseDown (vbLeftButton, Id) Case WM_LBUTTONUP RaiseEvent MouseUp (vbLeftButton, Id) Case WM_LBUTTONDBLCLK RaiseEvent MouseDblClick (vbLeftButton , Id) Case WM_RBUTTONDOWN RaiseEvent MouseDown (vbRightButton, Id) Case WM_RBUTTONUP RaiseEvent MouseUp (vbRightButton, Id) Case WM_RBUTTONDBLCLK RaiseEvent MouseDblClick (vbRightButton, Id) End SelectEnd Sub in this way, nearly perfect completion of the production of "events", while maintaining the Comparative package, it has a good versatility. In the Tune Function, there is such a problem: timeout. For example, when the function "TimeSetEvent" is accurate, you can define a callback in one millisecond, but you must do all the operations in one millisecond, if otherwise, you need to pay the price of the crash. In the face of this situation, there are several solutions. For example, you can increase a global variable from a "callback function", and detect this variable in a dead loop in the main program to determine the operation, this method is actually very good, just changing the event-driven programming method But in exchange for better response and stability. I prefer event-driven programming methods, and paranoid think the efficiency of event-driven is more efficient, so I use the following method: option expenenable m_tid as longpublic timeenable as booleanprivate curdwuser as longpublic sub timeproc (Byval Umi, _ Byval UMSG AS Long, Byval dwuser as long, _ byval dw1 as long, byval dw2 as long) if m_tid = uid dam = dwuse = true kilofactive. Visible = true kil of postmessage main form .hwnd, WM_KeyDown , 1, 0 End If End If End If End IfEnd SubPublic Sub AddTimer (ByVal dwInt As Long, _ Optional ByVal dwUser As Long = 0) CurdwUser = dwUser m_TID = timeSetEvent (dwInt, 0, _ AddressOf TimeProc, dwUser, TIME_PERIODIC) If m_tid = 0 THEN main form .caption = "Create time function failed" End Subfic Sub Removetimer () IF m_tid> 0 The timekillevent m_tidend Sub This should be "postmessage" a custom message, but there is also another "callback Function ", so no," PostMessage "generates a keydown message, sending" 1 "(on the keyboard is not typing the ASCII value" 1 "key value), so you can take advantage of" Main Fact_keyDown "The event completes this. Ok, I may wish to go back to myself, say "The program is Tiancheng, the wonderful hand is awkward" (this sentence plagiarizes). -------------------------------------------------- ----------------------------- 13. About helping the end, I want to say that VB help is very comprehensive, often check it Help (including online manual), usually encountered problems can generally be solved. However, superstitious, it's not good, let's take a look at this "Small Story of Heart, Desperate and Paste": WritePrivateProfileString Past is a popular function because it allows you to save data between tasks, this It is Visual Basic that should be provided until the version 4 is available. Everyone wants to use this function. Everyone pastes its declaration part from the API declaration file. Everyone has encountered trouble when using it. Then everyone seeks Microsoft product support, or if they work in Microsoft, send emails to the internal Visual Basic programming department. I have seen this inquiry about WritePrivateProfileString in the past.