Der Code prüft ob bereits einen Instanz der Anwendung läuft und bringt diese dann auf Wunsch in den Vordergrund. Die neu gestartete Instanz kann dann über Application.Exit() beendet werden.
Hinweis: Fenster die minimiert oder unsichtbar sind werden nicht in den Fordergrund gebracht. Hier ist die Implementierung der APIAufrufe "GetWindowPlacement" und "SetWindowPlacement" erforderlich.
1 using System;
2 using System.Windows.Forms;
3 using System.Runtime.InteropServices;
4
5
6 namespace Toolbox
7 {
8 /// <summary>
9 /// This class helps to create a Application which allowed onyl on instance (like word, excel, eg)
10 /// </summary>
11 internal abstract class SingleInstanceManager
12 {
13 //TODO: create your own GUID with GuidGen!!!
14 private const string APPID="{AD0C0725-18BE-4eaa-8FE6-17F0FC14A971}";
15
16 #region Win32API
17 [DllImport("user32.dll")]
18 private static extern long BringWindowToTop(long hwnd);
19
20 [DllImport("user32.dll")]
21 private static extern long SetForegroundWindow(long hwnd);
22 #endregion
23
24 #region Worker
25
26 /// <summary>
27 /// check whether an other instance of the current application is running
28 /// </summary>
29 /// <returns>
30 /// true if you can start a new instance,
31 /// false if an instance is running
32 /// </returns>
33 public static bool StartNewApplication()
34 {
35 return StartNewApplication(false);
36 }
37
38 /// <summary>
39 /// check whether an other instance of the current application is running
40 /// </summary>
41 /// <param name="BringToTop">
42 /// true: the other instance will shown
43 /// false: the other instance will not shown
44 /// </param>
45 /// <returns>
46 /// true if you can start a new instance,
47 /// false if an instance is running
48 /// </returns>
49 public static bool StartNewApplication(bool BringToTop)
50 {
51 bool retVal = true;
52 System.Threading.Mutex mu = new System.Threading.Mutex(false, APPID);
53
54 if (mu.WaitOne(0, false) == true)
55 {
56 //start a new one
57 retVal = true;
58 }
59 else
60 {
61 //an instance is running
62 retVal = false;
63
64 if (BringToTop)
65 {
66 foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName))
67 {
68 if (p.Id != System.Diagnostics.Process.GetCurrentProcess().Id)
69 {
70 //p.MainWindowHandle;
71 SetForegroundWindow(p.MainWindowHandle.ToInt64());
72 BringWindowToTop(p.MainWindowHandle.ToInt64());
73 }
74 }
75 }//end BringToTop
76
77 }//end Running ?
78 return retVal;
79 }
80 #endregion
81 }
82 }
83
Keine Kommentare:
Kommentar veröffentlichen