0

我试图在按下某个热键时获取活动窗口,但是我的程序总是将我的应用程序的主窗体作为活动窗口返回,而不是屏幕上当前显示的任何内容(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 活动窗口的任何想法?

4

1 回答 1

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();
}
于 2013-09-05T14:07:11.673 回答