互聯(lián)網(wǎng)網(wǎng)站建設(shè)制作精品成品網(wǎng)站源碼
今次介紹一個(gè)應(yīng)用程序單例唯一運(yùn)行方案的代碼。
我們知道,有些應(yīng)用程序在操作系統(tǒng)中需要單例唯一運(yùn)行,因?yàn)槌绦蚨嚅_的話會(huì)對(duì)程序運(yùn)行效果有影響,最基本的例子就是打印機(jī),只能運(yùn)行一個(gè)實(shí)例。這里將筆者單例運(yùn)行的代碼共享出來(lái),需要的讀者請(qǐng)自己復(fù)用該代碼到自己的項(xiàng)目中即可。
1、? 項(xiàng)目目錄;
下面是項(xiàng)目目錄,因?yàn)槭且欢未a,所以給出的例子比較簡(jiǎn)單。
????????
2、? 代碼介紹;
這里的代碼挺簡(jiǎn)單的,就是獲取應(yīng)用程序的GUID和運(yùn)行的進(jìn)程進(jìn)行判斷,因?yàn)镚UID唯一,所以更改了程序名稱或者改變了目錄都不會(huì)有影響;而運(yùn)行進(jìn)程判斷是附加的方式,防止當(dāng)前目錄的程序運(yùn)行多次。
1 namespace ProgramInstance2 {3 using System;4 using System.Diagnostics;5 using System.Reflection;6 using System.Runtime.InteropServices;7 using System.Threading;8 9
10 /// <summary>
11 /// 單例程序操作類
12 /// </summary>
13 internal class SingleInstance
14 {
15 /// <summary>
16 /// 程序是否運(yùn)行
17 /// </summary>
18 /// <returns>true 程序已運(yùn)行;false 程序未運(yùn)行</returns>
19 internal static bool IsRunning(out Process process)
20 {
21 //如果判斷全系統(tǒng)唯一,直接用下列方法;如果判斷當(dāng)前文件夾唯一,則將GUID判斷去掉;
22 new Mutex(true,
new Guid(((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
typeof(GuidAttribute))).Value).ToString("N"),
out bool createdNew);
23 process = RunningInstance();
24 return (!createdNew || (process != null));
25 }
26 /// <summary>
27 /// 獲取當(dāng)前程序進(jìn)程實(shí)例
28 /// </summary>
29 /// <returns>程序進(jìn)程實(shí)例</returns>
30 private static Process RunningInstance()
31 {
32 Process currentProcess = Process.GetCurrentProcess();
33 foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
34 {
35 if ((process.Id != currentProcess.Id) &&
(Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == currentProcess.MainModule.FileName))
36 {
37 return process;
38 }
39 }
40 return null;
41 }
42 }
43 }
1 namespace SingleInstance2 {3 using System;4 using System.Diagnostics;5 using System.Runtime.InteropServices;6 using System.Windows.Forms;7 8 /// <summary>9 /// 程序類
10 /// </summary>
11 internal static class Program
12 {
13 [DllImport("User32.dll")]
14 private static extern bool SetForegroundWindow(IntPtr hWnd);
15 [DllImport("User32.dll")]
16 private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
17
18 /// <summary>
19 /// 應(yīng)用程序的主入口點(diǎn)
20 /// </summary>
21 [STAThread]
22 static void Main()
23 {
24 if (ProgramInstance.SingleInstance.IsRunning(out Process process))
25 {
26 ShowWindowAsync(process.MainWindowHandle, 9 | 1);
27 SetForegroundWindow(process.MainWindowHandle);
28
29 return;
30 }
31
32
33 Application.EnableVisualStyles();
34 Application.SetCompatibleTextRenderingDefault(false);
35
36 Application.Run(new Form1());
37 }
38 }
39 }
3、? 運(yùn)行截圖;
因?yàn)槭谴a段復(fù)用,所以這里不提供運(yùn)行截圖了。
4、? 源碼下載;
需要該例子代碼的,請(qǐng)移步到下面鏈接進(jìn)行下載:
https://download.csdn.net/download/lzhdim/88158095
上面介紹了C#編寫的應(yīng)用程序單例運(yùn)行的例子,希望對(duì)有該需求的讀者以幫助。后面會(huì)將筆者認(rèn)為有用的代碼段共享出來(lái),讓需要的讀者進(jìn)行代碼段復(fù)用。
注:如果需要應(yīng)用程序多開(放到其它文件夾中,或者在當(dāng)前文件夾中復(fù)制更改應(yīng)用程序名稱),請(qǐng)將GUID的判斷去掉即可。