首页 新闻 赞助 找找看

请问大侠们一个关于打开进程主界面的问题。

0
悬赏园豆:10 [待解决问题]

这是一个WinForm程序,我希望它同时只有一个实例在运行,所以在启动时加了互斥。

如果发现有实例在运行,那么就将窗口显示出来。。此程序只有一个窗口。

我不知道要怎么写。。

下边的写法不对。。请高手帮帮忙,谢谢

 

 

代码如下:

 

 static void Main()
        {
            bool isAppRunning = false;
            Mutex mutex = new System.Threading.Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out isAppRunning);
            if (!isAppRunning)
            {
                Process p = Process.GetProcessesByName("buildmodel")[0];
                SetForegroundWindow(p.Handle);
                ShowWindowAsync(p.Handle, 9);
                SendMessage(p.Handle, 0x18, GetFocus(), IntPtr.Zero); 
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }

        [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 IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
        [DllImport("User32.dll")]
        private static extern IntPtr GetFocus(); 
hexllo的主页 hexllo | 菜鸟二级 | 园豆:318
提问于:2014-10-07 19:20
< >
分享
所有回答(2)
0
 Process[] processes = Process.GetProcessesByName("WinformDemo");
            if (processes.Length >= 2)
            {
                // 这里是多开的情况
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

直接通过进程数来判断,不需要进程锁

jerry128 | 园豆:31 (初学一级) | 2014-10-08 09:24
0
If PrevInstance(IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath), True) Then
            MessageBox.Show("软件已运行!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If

Private Shared Function PrevInstance(ByVal sProName As String, Optional ByVal start As Boolean = False) As Boolean
        Dim i As Integer
        Try
            i = Diagnostics.Process.GetProcessesByName(sProName).Length
        Catch ex As Exception
            i = 0
        End Try
        If start Then
            Return i > 1
        Else
            Return i > 0
        End If
End Function

如果只是判断,上面这样就行了。

不过你这么为用户着想,还要把已经打开的软件激活,就麻烦点。

你要是觉得有必要那就实现吧。我一般不会这么宠着用户的,这样他们会想要上天摘月,下海捞星的。

爱编程的大叔 | 园豆:30839 (高人七级) | 2014-10-08 10:53
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册