首页 新闻 会员 周边 捐助

如何恢复单实例的最小化到托盘的程序

0
悬赏园豆:30 [已关闭问题] 关闭于 2009-04-13 20:57

我用C#写了一个最小化到托盘的程序,并使它单实例运行,运行第二个实例时,恢复第一个实例的窗口,并置于最前。

当第一个实例最小化时,调用自己的方法可以正常恢复窗口,运行第二个实例时,可以恢复窗口,但只有之前激活的TabPage中可以正常显示内容,其他TabPage中全部是空白。代码如下,希望大虾指点。

P.s. 查了一些资料,貌似被隐藏的窗体不能用instance.MainWindowHandle获得句柄,而根据窗体名字获得句柄的方法似乎有些问题,但不知如何解决

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private const int WS_SHOWNORMAL = 1;
        public const Int32 AW_BLEND = 0x00080000;
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("User32.dll")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

       
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process instance = RunningInstance();
            if (instance == null)
            {

                Application.Run(new Form1());

            }
            else
            {
                HandleRunningInstance(instance);
            }

        }


       
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
        public static void HandleRunningInstance(Process instance)
        {
            if (instance.MainWindowHandle.ToInt32() != 0)
            {
                ShowWindowAsync(instance.MainWindowHandle, 9);
                SetForegroundWindow(instance.MainWindowHandle);

            }
            else
            {
                IntPtr hwnd = FindWindow(null, "窗体名字");
                ShowWindowAsync(hwnd, 9);
                SetForegroundWindow(hwnd);

            }
        }

    }

Ayane的主页 Ayane | 初学一级 | 园豆:170
提问于:2009-04-09 23:00
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册