按下热键时获取前景窗口

时间:2013-09-05 13:32:08

标签: c# .net winforms

我正在尝试按下某个热键时显示活动窗口但是我的程序总是将我的应用程序的主窗体作为活动窗口返回,而不是屏幕上当前显示的任何内容(Firefox,Chrome等)。 )。我怀疑,一旦我按下热键,表单就会被认为是活动的,这就是为什么它被作为前景窗口返回?

这是我用来获取当前活动窗口的内容

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

public IntPtr getCurrentlyActiveWindow()
{
    //Debugging
    const int nChars = 256;
    IntPtr handle = IntPtr.Zero;
    StringBuilder Buff = new StringBuilder(nChars);
    handle = GetForegroundWindow();
    GetWindowText(handle, Buff, nChars);
    MessageBox.Show(Buff.ToString());

    return GetForegroundWindow();
}

关于如何获取ACTUAL活动窗口的任何想法?

1 个答案:

答案 0 :(得分:0)

我把一切都整理好了,在得到当前活动的窗口之前,我不小心把焦点放在了我的表格上。这就是我最终的结果

//Listen for the hotkey
protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (m.Msg == WM_HOTKEY)
    {
        Keys vk = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
        int fsModifiers = ((int)m.LParam & 0xFFFF);

        //Perform action when hotkey is pressed
        if (vk == userHotkey)
        {
            minimizeWindow();
        }
    }
}

//Minimize the currently active window
private void minimizeWindow()
{
    //Get a pointer to the currently active window
    IntPtr hWnd = getCurrentlyActiveWindow();
    if (!hWnd.Equals(IntPtr.Zero))
    {
        //Minimize the window
        ShowWindowAsync(hWnd, SW_SHOWMINIMIZED);
    }
}

//Get the currently active window
private IntPtr getCurrentlyActiveWindow()
{
    this.Visible = false;
    return GetForegroundWindow();
}