C#判断是程序是否已经打开,如果打开就前置显示

 1 [DllImport("user32.dll")]
 2 private static extern bool SetForegroundWindow(IntPtr hWnd);
 3 [DllImport("user32.dll")]
 4 private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
 5 [DllImport("user32.dll")]
 6 private static extern bool IsIconic(IntPtr hWnd);
 7 private const int SW_RESTORE = 9;
 8 
 9 /// <summary>
10 /// 判断是程序是否已经打开,如果打开就前置显示
11 /// </summary>
12 public static void RaiseOtherProcess()
13 {
14 Process proc = Process.GetCurrentProcess();
15 Process.GetProcesses();
16 foreach (Process otherProc in Process.GetProcessesByName(proc.ProcessName))
17 {
18 //ignore "this" process
19 if (proc.Id != otherProc.Id)
20 {
21 // Found a "same named process".
22 // Assume it is the one we want brought to the foreground.
23 // Use the Win32 API to bring it to the foreground.
24 IntPtr hWnd = otherProc.MainWindowHandle;
25 if (IsIconic(hWnd))
26 {
27 ShowWindowAsync(hWnd, 9);
28 }
29 SetForegroundWindow(hWnd);
30 break;
31 }
32 }
33 }
 1 using System;
 2 using System.Diagnostics;
 3 using System.Runtime.InteropServices;
 4 class AppMain
 5 {
 6     [DllImport("user32.dll")] private static extern
 7         bool SetForegroundWindow(IntPtr hWnd);
 8     [DllImport("user32.dll")] private static extern
 9         bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
10     [DllImport("user32.dll")] private static extern
11         bool IsIconic(IntPtr hWnd);
12 
13     private const int SW_HIDE = 0;
14     private const int SW_SHOWNORMAL = 1;
15     private const int SW_SHOWMINIMIZED = 2;
16     private const int SW_SHOWMAXIMIZED = 3;
17     private const int SW_SHOWNOACTIVATE = 4;
18     private const int SW_RESTORE = 9;
19     private const int SW_SHOWDEFAULT = 10;
20 
21     static void Main()
22     {
23         // get the name of our process
24         string proc=Process.GetCurrentProcess().ProcessName;
25         // get the list of all processes by that name
26         Process[] processes=Process.GetProcessesByName(proc);
27         // if there is more than one process...
28         if (processes.Length > 1)
29         {
30             // Assume there is our process, which we will terminate, 
31             // and the other process, which we want to bring to the 
32             // foreground. This assumes there are only two processes 
33             // in the processes array, and we need to find out which 
34             // one is NOT us.
35 
36             // get our process
37             Process p=Process.GetCurrentProcess();
38             int n=0;        // assume the other process is at index 0
39             // if this process id is OUR process ID...
40             if (processes[0].Id==p.Id)
41             {
42                 // then the other process is at index 1
43                 n=1;
44             }
45             // get the window handle
46             IntPtr hWnd=processes[n].MainWindowHandle;
47             // if iconic, we need to restore the window
48             if (IsIconic(hWnd))
49             {
50                 ShowWindowAsync(hWnd, SW_RESTORE);
51             }
52             // bring it to the foreground
53             SetForegroundWindow(hWnd);
54             // exit our process
55             return;
56         }
57         // ... continue with your application initialization here.
58     }
59 }
60 
61 //该片段来自于http://outofmemory.cn

防止程序运行多个实例的方法有多种,如:通过使用互斥量和进程名等.而我想要实现的是:在程序运行多个实例时激活的是第一个实例,使其获得焦点,并在前端显示.


主要用到两个API 函数:


  • ShowWindowAsync 该函数设置由不同线程产生的窗口的显示状态。
  • SetForegroundWindow 该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。系统给创建前台窗口的线程分配的权限稍高于其他线程。

代码如下:



引用以下命名空间:
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;




1
static class Program 2 { 3 /// <summary> 4 /// 该函数设置由不同线程产生的窗口的显示状态。 5 /// </summary> 6 /// <param name="hWnd">窗口句柄</param> 7 /// <param name="cmdShow">指定窗口如何显示。查看允许值列表,请查阅ShowWlndow函数的说明部分。</param> 8 /// <returns>如果函数原来可见,返回值为非零;如果函数原来被隐藏,返回值为零。</returns> 9 [DllImport("User32.dll")] 10 private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); 11 /// <summary> 12 /// 该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。系统给创建前台窗口的线程分配的权限稍高于其他线程。 13 /// </summary> 14 /// <param name="hWnd">将被激活并被调入前台的窗口句柄。</param> 15 /// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零。</returns> 16 [DllImport("User32.dll")] 17 private static extern bool SetForegroundWindow(IntPtr hWnd); 18 private const int WS_SHOWNORMAL = 1; 19 20 /// <summary> 21 /// 应用程序的主入口点。 22 /// </summary> 23 [STAThread] 24 static void Main() 25 { 26 Application.EnableVisualStyles(); 27 Application.SetCompatibleTextRenderingDefault(false); 28 Process instance = RunningInstance(); 29 if (instance == null) 30 { 31 Form1 frm = new Form1(); 32 Application.Run(new Form1()); 33 } 34 else 35 { 36 HandleRunningInstance(instance); 37 } 38 39 } 40 /// <summary> 41 /// 获取正在运行的实例,没有运行的实例返回null; 42 /// </summary> 43 public static Process RunningInstance() 44 { 45 Process current = Process.GetCurrentProcess(); 46 Process[] processes = Process.GetProcessesByName(current.ProcessName); 47 foreach (Process process in processes) 48 { 49 if (process.Id != current.Id) 50 { 51 if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) 52 { 53 return process; 54 } 55 } 56 } 57 return null; 58 } 59 60 /// <summary> 61 /// 显示已运行的程序。 62 /// </summary> 63 public static void HandleRunningInstance(Process instance) 64 { 65 ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //显示,可以注释掉 66 SetForegroundWindow(instance.MainWindowHandle); //放到前端 67 } 68 }

 

 1 我们基本上可以使用Windows API函数ShowWindowAsync方法来正常化/最大化/最小化另一应用程序。
 2 请参阅下面的代码示例片段:
 3 private const int SW_SHOWNORMAL = 1;
 4 private const int SW_SHOWMINIMIZED = 2;
 5 private const int SW_SHOWMAXIMIZED = 3;
 6 
 7 [DllImport("user32.dll")]
 8 private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
 9 private void button1_Click(object sender, EventArgs e)
10 {
11     // 返回写字板程序的句柄
12     IntPtr hWnd = FindWindow("Notepad", "Untitled - Notepad");
13     if (!hWnd.Equals(IntPtr.Zero))
14     {
15         // SW_SHOWMAXIMIZED最大化窗口
16         // SW_SHOWMINIMIZED 最小化窗口
17         // SW_SHOWNORMAL 是窗口正常大小
18         ShowWindowAsync(hWnd, SW_SHOWMAXIMIZED);
19     }
20 }
21 
22 相关的帖子:
23 http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/f8dc9aec-c53f-41cf-a376-aa3d88dda1d9

 

posted @ 2018-02-03 11:05  云傲崖  阅读(47)  评论(0)    收藏  举报