5

基本上,我如何判断我的程序是否在所有其他程序之上?

4

4 回答 4

12

一个相当简单的方法是 P/Invoke GetForegroundWindow()并比较返回到应用程序的 form.Handle 属性的 HWND。

using System;
using System.Runtime.InteropServices;

namespace MyNamespace
{
    class GFW
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        public bool IsActive(IntPtr handle)
        {
            IntPtr activeHandle = GetForegroundWindow();
            return (activeHandle == handle);
        }
    }
}

然后,从您的表格中:

if (MyNamespace.GFW.IsActive(this.Handle))
{
  // Do whatever.
}
于 2012-08-21T04:42:21.360 回答
1

您可以使用:

if (GetForegroundWindow() == Process.GetCurrentProcess().MainWindowHandle)
{
     //do stuff
}

WINAPI 导入(在类级别):

[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool GetForegroundWindow();

分配一个属性来保存该值,并通过 IDE 或在 InitializeComponent() 之后将检查添加到表单的 GotFocus 事件;

例如:

//.....
InitalizeComponent();
this.GotFocus += (myFocusCheck);
//...

private bool onTop = false;

private void myFocusCheck(object s, EventArgs e)
{
    if(GetFore......){ onTop = true; }
}
于 2012-08-21T05:00:07.260 回答
0

如果你的窗口继承了表单,你可以检查 Form.Topmost 属性

于 2014-07-23T07:46:45.503 回答
0

这个答案给出了一个很好的解决方案: https ://stackoverflow.com/a/7162873/386091

/// <summary>Returns true if the current application has focus, false otherwise</summary>
public static bool ApplicationIsActivated()
{
    var activatedHandle = GetForegroundWindow();
    if (activatedHandle == IntPtr.Zero) {
        return false;       // No window is currently activated
    }

    var procId = Process.GetCurrentProcess().Id;
    int activeProcId;
    GetWindowThreadProcessId(activatedHandle, out activeProcId);

    return activeProcId == procId;
}


[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);

如果您的程序显示对话框或具有可拆卸的窗口(例如,如果您使用 Windows 对接框架),Euric 当前接受的解决方案将不起作用。

于 2015-12-15T19:06:50.360 回答