轉(zhuǎn)帖自http://www.yesky.com/20030407/1661941.shtml
如何確保在C#中只有一個(gè)程序(實(shí)例)運(yùn)行?
解答:主要應(yīng)用System.Diagnostics名字空間中的Process類來實(shí)現(xiàn),思路,我們在運(yùn)行程序前,查找進(jìn)程中是否有同名的進(jìn)程,同時(shí)運(yùn)行位置也相同程,如是沒有運(yùn)行該程序,如果有,就將同名的同位置的程序窗口置前. 主要代碼:
[C#] public static Process RunningInstance() { Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName (current.ProcessName); //查找相同名稱的進(jìn)程 foreach (Process process in processes) { //忽略當(dāng)前進(jìn)程 if (process.Id != current.Id) { //確認(rèn)相同進(jìn)程的程序運(yùn)行位置是否一樣. if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) { //Return the other process instance. return process; } } } //No other instance was found, return null. return null; }
|