调用 User32 PostMessage 时过程调用或参数无效(错误 5)
Posted
技术标签:
【中文标题】调用 User32 PostMessage 时过程调用或参数无效(错误 5)【英文标题】:Invalid Procedure Call or Argument (Error 5) when calling User32 PostMessage 【发布时间】:2017-04-07 17:27:28 【问题描述】:以下代码在该行返回“运行时错误 5:无效的过程调用或参数”:
结果 = PostMessage(h, WM_CHAR, Asc(Mid$(vbCr, i, 1)), 0&)
Private Const WM_CHAR = &H102
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Sub PostToCmdLine()
Dim h As Long
Dim result As Boolean
' find dos prompt window
h = FindWindow(vbNullString, "c:\windows\system32\cmd.exe")
Stop
If h Then
' send "calc.exe" followed by carraige return
result = PostMessage(h, WM_CHAR, Asc(Mid$(vbCr, i, 1)), 0&)
' optional, check postmessage result
If result = False Then MsgBox ("postmessage failed!")
'close the hidden dos prompt window
' SendTxt(h, "exit" & vbCr)
Else
MsgBox ("dos prompt window not found")
End If
End Sub
我做错了什么?
【问题讨论】:
【参考方案1】:这甚至不会调用PostMessage
- 错误就在这个位:
Asc(Mid$(vbCr, i, 1))
变量i
从未被声明或赋值(这是将Option Explicit
添加到所有模块的一个很好的论据......)因此它试图从位置0 读取Mid$
。它基于1 ,因此你的错误。
也就是说,尚不清楚您为什么要尝试从 1 个字符的长文字中提取 1 个字符。 Asc(Mid$(vbCr, i, 1))
与 Asc(vbCr)
相同,总是 13
。就用这个吧:
result = PostMessage(h, WM_CHAR, 13&, 0&)
请注意,这与您对“发送“calc.exe”后跟回车的评论完全不匹配。为了对WM_CHAR
消息执行此操作,您需要发布所有单个字符。通过将字符串视为字节数组,完全跳过Asc
和Mid$
:
Dim chars() As Byte
chars = StrConv("calc.exe" & vbCr, vbFromUnicode)
Dim i As Long
For i = LBound(chars) To UBound(chars)
result = PostMessage(h, WM_CHAR, CLng(chars(i)), 0&)
'Check result to see if you need to bail here.
Next
【讨论】:
以上是关于调用 User32 PostMessage 时过程调用或参数无效(错误 5)的主要内容,如果未能解决你的问题,请参考以下文章
执行从 C# 到 EuroTruck 的密钥输出不起作用(PostMessage、user32.dll)