c# - Mutex 失败后将窗口置于前台

标签 c# winforms process mutex foreground

我想知道如果无法为新实例创建互斥锁,是否有人可以告诉我将我的应用程序带到前台的最佳方法。

例如:应用程序 X 正在运行但处于后台。我看不到它,所以我尝试运行另一个实例;因为互斥量返回 false,所以最好的办法是将现有实例带到前台。

有谁知道与您自己的应用程序交互但从单独的进程进行交互的最佳方式?

最佳答案

您需要获取其他应用程序主窗口的 hWnd。我记得如何做到这一点的唯一方法是遍历所有窗口,直到找到你的窗口。可能有更直接的方法

[DllImport("user32.dll")] private static extern 
              int EnumWindows(EnumWindowsProc ewp, int lParam); 

public delegate bool EnumWindowsProc(int hWnd, int lParam);

public void EnumerateAllWindows()
{
   EnumWindowsProc ewp = new EnumWindowsProc(EvalWindow);
   EnumWindows(ewp, 0);
 }

private bool EvalWindow(int hWnd, int lParam)
{
    //this will be called for each window..         
    // use GetWindowThreadProcessId to get the PID for each window
    // and use Process.GetProcessById to get the PID you are looking for
    // then bring it to foregroun using of these calls below:

}

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    public static extern bool BringWindowToTop(IntPtr hWnd);

    DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd

关于c# - Mutex 失败后将窗口置于前台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1733980/

相关文章:

c# - 如何在 C# 中检查我的互联网是否超时

.NET - 获取在另一个域中的机器上运行的进程

c# - Marshall结构通过sendmessage将其传递给delphi记录

c# - 将 WPF 控件放入 Windows 窗体窗体?

c# - 尽管更改分辨率,视频捕获输出始终为 320x240

c# - StructureMap 可以返回特例吗?

C# DataSet.Tables[0].GetChanges();总是返回所有行

c# - 不使用 OnPaint 则无效

java - 获取刚刚启动的进程的PID

c++ - 父进程和子进程计时