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

问题描述 投票:1回答:1

在我的application我使用SendKeys.SendWait发送text屏幕:

SendKeys.SendWait("password");

textEnglish但是当键盘设置为其他语言text SendKeys.SendWait类型用其他语言设置而不是在English

有任何建议如何确保text将只在English设置?

c# sendkeys
1个回答
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}");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.