c# SendKeys到前台窗口在Windows 7不工作

本文关键字:Windows 工作 窗口 SendKeys 前台 | 更新日期: 2023-09-27 17:49:45

我试图在Visual Studio 2012中用c#构建一个在Windows 7上运行的全局热键应用程序。我有一切工作,除了SendKeys从未显示在应用程序中。

下面是我用来发送击键的代码:

更新以调试GetFocusedWindow示例。

StringBuilder className = new StringBuilder(256);
IntPtr hWnd = GetForegroundWindow();
GetClassName(hWnd, className, className.Capacity);
Debug.WriteLine("Foreground window: {0}={1}", hWnd.ToInt32().ToString("X"), className);
hWnd = GetFocusedWindow();
GetClassName(hWnd, className, className.Capacity);
Debug.WriteLine("Focused window: {0}={1}", hWnd.ToInt32().ToString("X"), className);
SendKeys.Send("Hello World");

当我调试程序时,聚焦记事本,并按热键,我得到以下调试消息,按键永远不会插入记事本:

Foreground Window: 4F02B6=Notepad
Focused Window: 1B6026A=WindowsForms10.Window.8.app.0.bf7d44_r11_ad1

如何发送击键到当前前台窗口?

c# SendKeys到前台窗口在Windows 7不工作

前景窗口并不一定意味着聚焦窗口。顶层前台窗口的子窗口可能拥有焦点,而您正在向其父窗口发送键。

从另一个进程检索焦点子窗口有点棘手。尝试以下GetFocusedWindow的实现,使用它代替GetForegroundWindow(未测试):

static IntPtr GetFocusedWindow()
{
    uint currentThread = GetCurrentThreadId();
    IntPtr activeWindow = GetForegroundWindow();
    uint activeProcess;
    uint activeThread = GetWindowThreadProcessId(activeWindow, out activeProcess);
    if (currentThread != activeThread)
        AttachThreadInput(currentThread, activeThread, true);
    try
    {
        return GetFocus();
    }
    finally
    {
        if (currentThread != activeThread)
            AttachThreadInput(currentThread, activeThread, false);
    }
}
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
[DllImport("user32.dll", SetLastError = true)]
static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

更新以解决注释:

当我使用这个函数时,它将焦点设置为我的应用程序窗口。

很难判断你这边出了什么问题,当焦点在记事本内部时,以下方法对我有用:

private async void Form1_Load(object sender, EventArgs e)
{
    var className = new StringBuilder(200);
    while (true)
    {
        await Task.Delay(500);
        IntPtr focused = GetFocusedWindow();
        GetClassName(focused, className, className.Capacity);
        var classNameStr = className.ToString();
        this.Text = classNameStr;
        if (classNameStr == "Edit")
            SendKeys.Send("Hello!");
    }
}