VBGood网站全文搜索 Google

首页 - 经验之谈 - 通过别名防止api崩溃
发表评论(0)作者:不详, 平台:VB6.0+Win98, 阅读:8974, 日期:2000-11-07
Using the Alias Option to Prevent API Crashes
By Mike Amundsen mike@amundsen.com, http://www.amundsen.com

A number of Windows APIs have parameters that can be more than one data type. For example, the WinHelp API call can accept the last parameter as a Long or String data type depending on the service requested.

Visual Basic allows you to declare this data type as "Any" in the API call, but this can lead to type mismatch errors or even system crashes if the value is not the proper form.

You can prevent the errors and improve the run-time type checking by declaring multiple versions of the same API function in your program. By adding a function declaration for each possible parameter type, you can continue to use strong data type checking.

To illustrate this technique, add the following APIs and constants to a Visual Basic form. Notice that the two API declarations differ only in their initial name ("WinHelp" and "WinHelpSearch") and the type declaration of the last parameter ("dwData as Long" and "dwData as String").

View Source:注释:注:这段代码,我没有验证过。
注释: WinHelp APIs
Private 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
Private Declare Function WinHelpSearch Lib "user32" Alias "WinHelpA" (ByVal hwnd As Long, ByVal lpHelpFile As String, ByVal wCommand As Long, ByVal dwData As String) As Long
Private Const HELP_PARTIALKEY = &H105&
Private Const HELP_HELPONHELP = &H4
Private Const HelpFile = "c:\program files\devstudio\v5\help\vb5.hlp"

Now add two command buttons to your form (cmdHelpAbout and cmdHelpSearch) and place the following code behind the buttons. Be sure to edit the location of the help file to match your installation of Visual Basic.

Private Sub cmdHelpAbout_Click()
      WinHelp Me.hwnd, HelpFile, HELP_HELPONHELP, &H0
End Sub

Private Sub cmdHelpSearch_Click()
      WinHelpSearch Me.hwnd, HelpFile, HELP_PARTIALKEY, "option"
End Sub

When you press on the HelpAbout button, you注释:ll see help about using the help system. When you press on the HelpSearch button, you注释:ll see a list of help entries on the "option" topic.