WPF 中如何实例化只实例化一个

 

  在很多系统中,我们只需要实例化一个实例,如:一个对话框打开后,再次点击运行程序该对话框Active ,不需要重新实例化

 

namespace RTFTest
{
    ///


    /// Interaction logic for App.xaml
    ///

    public partial class App : Application
    {

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            InstanceOne();
        }

        private void InstanceOne()
        {
            Process[] processes = Process.GetProcesses();
            Process currentProcess = Process.GetCurrentProcess();
            for (int i = 0; i < processes.Length; i++)
            {
                if (processes == null || currentProcess.Id == processes[i].Id) continue;
                if (processes[i].ProcessName == "RTFTest")
                {
                    IntPtr hWnd = processes[i].MainWindowHandle;
                    if (NativeMethods.IsIconic(hWnd))
                    {
                        NativeMethods.ShowWindowAsync(hWnd, NativeMethods.SW_RESTORE);
                    }
                    NativeMethods.SetForegroundWindow(hWnd);
                    Environment.Exit(0);
                }
            }
        }

    }


    public static class NativeMethods
    {
        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        public static extern bool IsIconic(IntPtr hWnd);
        public const int SW_RESTORE = 9;

    }

}

 

你可能感兴趣的:(Code)