只启动一个窗体,如果再次启动则激活该窗体
只启动一个窗体,如果再次启动则激活该窗体
以前就很想实现这个功能,不过不知从何处下手,初步做了一下只实现了只启动一个窗体,却无法实现激活该窗体,这是一个很大的遗憾呀!也是唯一美中不足之处.在网上找了好久,终于实现了这个功能,在这和大家一起分享一下. 1
using System;
2
using System.Collections.Generic;
3
using System.Windows.Forms;
4
using System.Diagnostics;
5
using System.Runtime.InteropServices;
6
7
namespace WindowsApplication2
8
{
9
static class Program
10
{
11
/// <summary>
12
/// 应用程序的主入口点。
13
/// </summary>
14
15
[DllImport("User32.dll")]
16
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
17
[DllImport("User32.dll")]
18
private static extern bool SetForegroundWindow(IntPtr hWnd);
19
private const int WS_SHOWNORMAL = 1;
20
21
[STAThread]
22
static void Main()
23
{
24
//得到正在运行的例程
25
Process instance = RunningInstance();
26
if (instance == null)
27
{
28
//如果没有其它例程,就新建一个窗体
29
Application.EnableVisualStyles();
30
Application.SetCompatibleTextRenderingDefault(false);
31
Application.Run(new Form1());
32
}
33
else
34
{
35
//处理发现的例程
36
HandleRunningInstance(instance);
37
}
38
}
39
/// <summary>
40
/// 得到正在运行的进程
41
/// </summary>
42
/// <returns></returns>
43
public static Process RunningInstance()
44
{
45
Process current = Process.GetCurrentProcess();
46
Process[] processes = Process.GetProcessesByName(current.ProcessName);
47
48
//遍历正在有相同名字运行的进程
49
foreach (Process process in processes)
50
{
51
//忽略现有的进程
52
if (process.Id != current.Id)
53
{
54
//确保进程从EXE文件运行
55
if (process.MainModule.FileName == current.MainModule.FileName)
56
{
57
// 返回另一个进程实例
58
return process;
59
}
60
}
61
}
62
//没有其它的进程,返回Null
63
return null;
64
}
65
/// <summary>
66
/// 处理正在运行的进程,也就是将其激活
67
/// </summary>
68
/// <param name="instance">要处理的进程</param>
69
public static void HandleRunningInstance(Process instance)
70
{
71
//确保窗口没有被最小化或最大化
72
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
73
//设置真实进程为foreground window
74
SetForegroundWindow(instance.MainWindowHandle);
75
}
76
}
77
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

(作者:侯垒)