2014-11-10 3 views
0

저는 숙련 된 프로그래머가 아니므로 조언이나 안내 또는 예제를 높이 평가할 수 있습니다! C# (.Net 프레임 워크 4.5) Windows 서비스 (Session0 변수 문제가 발생했습니다) 바꾸고있는 Windows 폼 응용 프로그램이 있습니다. 응용 프로그램에서 프로세스를 열어야합니다 (예 : 메모장 사용). 메모장이 아직 열려 있는지 5 분마다 확인하십시오. 메모장이 열려 있지 않으면 양식 응용 프로그램에서 메모장 인스턴스를 열어야합니다. 이미 열려있는 경우 응용 프로그램에서 사용자가 메모장의 다른 인스턴스를 열지 못하게해야합니다. 내 코딩은 현재 메모장의 모든 인스턴스를 닫습니다. 메모장의 두 번째 인스턴스를 열지 못하게하려면 응용 프로그램이 필요합니다. 문제는 사용자가 응용 프로그램과 전혀 상호 작용할 수 없다는 것입니다. 사용자가 양식을 보지 못하는 코딩에 유의하십시오. 여기 내 지금까지 코딩되어있다 : 당신은 기계 당 하나 개의 인스턴스로 제한하려면사용자가 프로세스 인스턴스를 두 개 이상 실행하지 못하도록 함

private void Form1_Load(object sender, EventArgs e) 
    { 
     this.ShowInTaskbar = false; 
     this.Visible = false; 
     //handle Elapsed event 
     myTimer.Tick += new EventHandler(OnElapsedTime); 
     //This statement is used to set interval to 5 minute (= 300,000 milliseconds) 
     myTimer.Interval = 60000;//300000; 
     //enabling the timer 
     myTimer.Enabled = true; 
     WatchForProcessStart("Notepad.exe"); 
    } 

    private void OnElapsedTime(object source, EventArgs e) 
    { 
     bool status = IsProcessOpen("notepad"); 
      if (status == true) 
      { 
       //TraceService("Notepad is already open" + DateTime.Now); 
      } 
      else 
      { 
      Process process = new Process(); 
      process.StartInfo.FileName = "notepad.exe"; 
      process.EnableRaisingEvents = true; 
      process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; 
      process.Start(); 
      //TraceService("Notepad opened" + DateTime.Now); 
      } 
    } 

    public bool IsProcessOpen(string procName) 
    { 
     System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName(procName); 
     if (proc.Length > 0) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

    private ManagementEventWatcher WatchForProcessStart(string processName) 
    { 
     string queryString = 
      "SELECT TargetInstance" + 
      " FROM __InstanceCreationEvent " + 
      "WITHIN 10 " + 
      " WHERE TargetInstance ISA 'Win32_Process' " + 
      " AND TargetInstance.Name = '" + processName + "'"; 

     // The dot in the scope means use the current machine 
     string scope = @"\\.\root\CIMV2"; 

     // Create a watcher and listen for events 
     ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString); 
     watcher.EventArrived += ProcessStarted; 
     watcher.Start(); 
     return watcher; 
    } 

    private void ProcessStarted(object sender, EventArrivedEventArgs e) 
    { 
     ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value; 
     string processName = targetInstance.Properties["Name"].Value.ToString(); 
     bool status = IsProcessOpen("notepad"); 
     if (status == true) 
     { 
      System.Diagnostics.Process.Start("cmd.exe", "/c taskkill /IM notepad.exe"); 
     } 
     else 
     { 
      Process process = new Process(); 
      process.StartInfo.FileName = "notepad.exe"; 
      process.EnableRaisingEvents = true; 
      process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; 
      process.Start(); 
     } 
    } 
+0

가능한 [단일 인스턴스로 프로그램을 제한하는 방법] 중복 가능 (http://stackoverflow.com/questions/4369720/how-to-restrict-a-program-to-a-single-instance) –

답변

1

Mutex

var mutexId = "MyApplication"; 
using (var mutex = new Mutex(false, mutexId)) 
{ 
    if (!mutex.WaitOne(0, false)) 
    { 
     MessageBox.Show("Only one instance of the application is allowed!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Hand); 
     return; 
    } 
    // Do scome work 
} 

에서 그것을 감싸의 mutexId는

글로벌 \로 시작해야
관련 문제