C# 激活其它进程的窗口并显示到最前

public partial class Frm1
{
    [DllImport("user32.dll")]
    private static extern bool
    SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")]
    private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    private static extern bool IsIconic(IntPtr hWnd);
    // 消息函数
    [DllImport("user32.dll", EntryPoint = "PostMessageA")]
    public static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string strclassName, string strWindowName);
    [DllImportAttribute("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
    public const int WM_SYSCOMMAND = 0x0112;
    public const int SC_MAXIMIZE = 0xF030;//窗体最大化消息
    public const int SC_NOMAL = 0xF120;//窗体还原消息

    private void Frm1_Load(object sender, EventArgs e)
    {
        CheckAppExists();
    }
    //判断是否重复打开
    public void CheckAppExists()
    {
        string name = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
        System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(name);//获取指定的进程名   

        if (myProcesses.Length > 1) //如果可以获取到知道的进程名则说明已经启动
        {
            MessageBox.Show("程序已启动!");
            Process[] process = Process.GetProcessesByName(name);//在所有已启动的进程中查找需要的进程;
            if (process.Length > 0)//如果查找到
            {
                IntPtr handle = process[0].MainWindowHandle;
                IntPtr hWnd = process[0].MainWindowHandle;
                SendMessage(hWnd, WM_SYSCOMMAND, SC_NOMAL, 0);
                SetForegroundWindow(hWnd);
            }
            Application.Exit();//关闭系统
        }
    }
}

 参考网站:(16条消息) C# 如何判断并且激活,最大化已有的外部应用程序的窗口? (源码例程)_jamex的博客-CSDN博客_c# 激活已经运行的程序

posted @ 2023-01-15 11:09  东经115  阅读(1000)  评论(0编辑  收藏  举报