当我双击Winform或Wpf的程序两次

时间:2014-01-08 11:46:21

标签: c# wpf winforms single-instance

如果我有一个Winform或Wpf的程序,例如A.exe,我双击它,一个窗口显示,然后我隐藏它,然后再次双击A.exe,我该如何制作hiden窗口再来一次?

winform摘要(需要1,4和5)和Wpf(需要1,2和3):

1。 SingleInstanceAppliction类

internal class SingleInstanceAppliction
{
    private static Mutex _mutex;
    static SingleInstanceAppliction()
    {
        WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
    }
    internal static int WM_SHOWME { get; private set; }
    internal static void SetGuid(string guid)
    {
        _mutex = new Mutex(true, guid);
    }
    internal static void ReleaseMutex()
    {
        _mutex.ReleaseMutex();
    }
    internal static bool IsFirst()
    {
        return _mutex.WaitOne(TimeSpan.Zero, true);
    }
    [DllImport("user32")]
    private static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
    [DllImport("user32")]
    private static extern int RegisterWindowMessage(string message);
    internal static void PostMessage()
    {
        PostMessage((IntPtr)0xffff, WM_SHOWME, IntPtr.Zero, IntPtr.Zero);
    }
}

2.对于App.xaml.cs中的Wpf

    protected override void OnStartup(StartupEventArgs e)
    {
        SingleInstanceAppliction.SetGuid("{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
        if (SingleInstanceAppliction.IsFirst())
        {
            base.OnStartup(e);
            SingleInstanceAppliction.ReleaseMutex();
        }
        else
        {
            SingleInstanceAppliction.PostMessage();
            Shutdown();
        }
    }

3.对于MainWindow.xaml.cs中的Wpf

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        var source = PresentationSource.FromVisual(this) as HwndSource;
        source.AddHook(WndProc);
    }
    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == SingleInstanceAppliction.WM_SHOWME)
        {
            if (WindowState == WindowState.Minimized)
            {
                WindowState = WindowState.Normal;
            }
            var top = Topmost;
            Topmost = true;
            Topmost = top;
        }
        return IntPtr.Zero;
    }

4.对于Program.cs中的Winform

    [STAThread]
    private static void Main()
    {
        SingleInstanceAppliction.SetGuid("{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
        if (SingleInstanceAppliction.IsFirst())
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            SingleInstanceAppliction.ReleaseMutex();
        }
        else
        {
            SingleInstanceAppliction.PostMessage();
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

5.对于Form1.cs中的Winform

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == SingleInstanceAppliction.WM_SHOWME)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                WindowState = FormWindowState.Normal;
            }
            var top = TopMost;
            TopMost = true;
            TopMost = top;
        }
        base.WndProc(ref m);
    }

2 个答案:

答案 0 :(得分:2)

在Winforms(VB.NET)中,您可以将其设为单实例应用程序

Project Properties > Application > Make single instance application

此选项在C#或Visual Studio的快速版本中不可用:http://msdn.microsoft.com/en-us/library/vstudio/8fz4ssw2(v=vs.100).aspx

所以这可能有用:How can I enforce a single instance of my application?

答案 1 :(得分:0)

你可以试试这个:

static class Program
{
    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

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


    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool createdNew = true;
        using (Mutex mutex = new Mutex(true, "SomeUniqueName", out createdNew))
        {
            if (createdNew)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new MyForm());
            }
            else
            {
                Process current = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        SetForegroundWindow(process.MainWindowHandle);
                        ShowWindowAsync(process.MainWindowHandle, 9);    //9 == SW_RESTORE
                        break;
                    }
                }
            }
        }
    }
}