调用User32 PostMessage时无效的过程调用或参数(错误5)

时间:2016-11-23 15:57:21

标签: vba postmessage user32

以下代码在以下行返回“运行时错误5:无效的过程调用或参数”:

result = 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 个答案:

答案 0 :(得分:1)

这甚至从未调用PostMessage - 错误就在这一点:

Asc(Mid$(vbCr, i, 1))

变量i永远不会被声明或赋值(并且是将Option Explicit添加到所有模块的好参数...)所以它试图从Mid$读取位置0.它基于1,因此您的错误。

尽管如此,我还不清楚为什么你要尝试从1个字符长的文字中提取1个字符。 Asc(Mid$(vbCr, i, 1))Asc(vbCr)相同,始终 13。只需使用:

result = PostMessage(h, WM_CHAR, 13&, 0&)

请注意,这与您对"发送" calc.exe"的评论不符。然后是carraige返回"一点都不为了使用WM_CHAR消息执行此操作,您需要发布所有单个字符。只需将字符串视为字节数组即可完全跳过AscMid$

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