C#에서 현재 실행중인 프로그램을 다시 실행하는 경우가 발생할 때 중복실행 여부를
확인하여 그에 대한 처리를 할 수 있도록 하는 코드이다.
System.Threading.Mutex 클래스를 이용한다.
기본적인 사용법은 다음과 같다.
static void Main() {
bool createdNew;
Mutex gM1 = new Mutex(true,"MyMutex", out createdNew);
if (createdNew) {
Application.Run(new frmMain());
gM1.ReleaseMutex();
}else {
MessageBox.Show("이미 실행되어 있습니다.");
}
}
이를 응용하여 네이트온과 같이 실행중인 경우 트레이에 있을 때 중복 실행이 되면 기존에 실행중인
프로그램을 활성화 시키는 방법이다.
public static extern void BringWindowToTop(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SetForegroundWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[STAThread]
static void Main() {
bool createNow = true;
using(System.Threading.Mutex mutex =
new System.Threading.Mutex(true, "ServerControllerMutex", out createNow)) {
if (createNow) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
else {
IntPtr wHandle = FindWindow(null, "PDA 수신 서버");
if (wHandle != IntPtr.Zero) {
ShowWindow(wHandle, 1);
BringWindowToTop(wHandle);
SetForegroundWindow(wHandle);
}
Application.Exit();
}
}
}






46666
45
81










댓글을 달아 주세요