.NET 4 single application instance

前端 未结 4 1908
清歌不尽
清歌不尽 2020-12-03 22:29

I often write .net applications that only support one instance. Formerly I used .net-remoting and now WCF to detect if already an instance of my app is running and giving th

4条回答
  •  甜味超标
    2020-12-03 22:40

    I use a Mutex, and FindWindow to do this.

    Concerning your comment on another answer:
    For information on Local and Global mutexes in Terminal Services, follow this link.

    Terminal Services client processes can use object names with a "Global\" or "Local\" prefix to explicitly create an object in the global or session name space.

    This is the code I use to activate the window:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool IsIconic(IntPtr hWnd);
    
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    private const int SH_SHOW = 5;
    private const int SH_RESTORE = 9;
    
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    
    public void Activate(IntPtr hwnd)
    {
        if (IsIconic(hwnd))
            ShowWindow(hwnd, SH_RESTORE);
        else
            ShowWindow(hwnd, SH_SHOW);
    
        SetForegroundWindow(hwnd);
    }
    

提交回复
热议问题