键盘设置为其他语言时使用英语SendKeys.SendWait

时间:2019-03-19 18:36:38

标签: c# sendkeys

在我的application中,我正在使用SendKeys.SendWait发送text到屏幕:

SendKeys.SendWait("password");

text位于English上,但是当键盘设置为其他语言时,text类型的SendKeys.SendWait被设置为其他语言而不是English

关于如何确保仅在text中设置English的任何建议?

1 个答案:

答案 0 :(得分:0)

我使用SendKeys.Send进行了快速测试,以将文本发送到几个输入字段。无论我使用的是英文键盘还是其他语言的键盘,它都会发送相同的文本,因此我不确定为什么会看到不同的结果。示例:

SendKeys.Send("username");
SendKeys.Send("{TAB}");
SendKeys.Send("påsswørd");
SendKeys.SendWait("{ENTER}");

一种可能性是,您可以在呼叫SendKeys之前暂时将键盘更改为英语,然后再将其设置回原来的水平。 this answer中有一个很好的例子。

另一个选择是使用Win32 API函数将消息发送到窗口。问题将是如何找到正确的窗口来发送文本到。我不确定它能否可靠地完成。这是一个示例(未经测试):

using System.Runtime.InteropServices;

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, string lParam);

// Windows message constants
const int WM_SETTEXT = 0x000C;

public void DoLogin(string username, string password)
{
    // Get handle for current active window
    IntPtr hWndMain = GetForegroundWindow();

    if (!hWndMain.Equals(IntPtr.Zero))
    {
        IntPtr hWnd;

        // Here you would need to find the username text input window
        if ((hWnd = FindWindowEx(hWndMain, IntPtr.Zero, "UserName", "")) != IntPtr.Zero)
            // Send the username text to the active window
            SendMessage(hWnd, WM_SETTEXT, 0, username);

        // Here you would need to find the password text input window
        if ((hWnd = FindWindowEx(hWndMain, IntPtr.Zero, "Password", "")) != IntPtr.Zero)
            // Send the password text
            SendMessage(hWnd, WM_SETTEXT, 0, password);

        // Send ENTER key to invoke login
        SendKeys.SendWait("{ENTER}");
    }
}