我想将“{TAB}”密钥发送到另一个应用窗口(将密钥发送到窗口而不是文本框)。
我试过了:
SendMessage(hWnd, WM_SETHOTKEY, VK_TAB, 0)
什么都没发生。
我的目标是:
当应用程序窗口不成为焦点时,将tab键发送到我的应用程序或其他应用程序。
(我知道sendkey在这种情况下并不专业,没有选择(这是我第一次使用它)。)
我做了很多尝试,我总是回到同样的结果:
什么都没发生。
有谁知道答案?
答案 0 :(得分:7)
SendKeys要求您发送密钥的应用程序处于活动状态。
从上面链接:
使用SendKeys将键击和击键组合发送到活动应用程序。
为了解决这个限制,您将不得不求助于使用WinApi函数。
请参阅此MSDN Forum Post以获取示例
以下是发布内容的修改示例:
Public Class Form1
Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd As IntPtr, ByVal hWndChildAfterA As IntPtr, ByVal lpszClass As String, ByVal lpszWindow As String) As IntPtr
Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As IntPtr, ByVal lParam As String) As IntPtr
Const WM_SETTEXT As Integer = &HC
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim destination As IntPtr = FindWindow(Nothing, "Untitled - Notepad")
Dim destControl As IntPtr = FindWindowEx(destination, IntPtr.Zero, "Edit", Nothing)
SendMessage(destControl, WM_SETTEXT, IntPtr.Zero, "Hello" & vbTab & "GoodBye" & vbCrLf)
End Sub
End Class
使用WM_KEYDOWN
添加了一个附加示例我创建了另一个小应用程序,其Window Title设置为TestForm并覆盖WndProc方法以确定应用程序是否获得了TabKey。
发送表单
Public Class Form1
Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
Const WM_KEYDOWN As Integer = &H100
Const VK_TAB As Integer = &H9
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim destination As IntPtr = FindWindow(Nothing, "TestForm")
SendMessage(destination, WM_KEYDOWN, VK_TAB, 0)
End Sub
End Class
测试表格
在MyBase.WndProc(m)上放置一个断点,然后查看m以查看已发送的内容。
Public Class Form1
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
End Sub
End Class
答案 1 :(得分:1)
之前几次与这种类型的斗争,我会建议一些事情要看。
第一个是autoit,其中包含一个可以从vb.net引用的dll,并且使用起来非常简单,并且有很好的文档记录。每当我需要控制第三方程序时,我倾向于使用它。
另一个是ui automation classes 请参阅此示例:
http://blog.functionalfun.net/2009/06/introduction-to-ui-automation-with.html
答案 2 :(得分:0)
您需要先激活其他窗口。检查Change focus to another window in VB.NET。然后使用发送密钥。