如何只运行一个实例,而在第二次和以后运行时激活原程序而不重新创建一个新实例,本文收集来源于internet

调用实现类

            Process p = DCSingleInstance.GetRunningInstance();
            if (p != null)
            {
                DCSingleInstance.HandleRunningInstance(p);
                return;
            }

 DCSingleInstance.GetRunningInstance();
            if (p != null)
            {
                DCSingleInstance.HandleRunningInstance(p);
                
return;
            }


 DCSingleInstance
    {
        [DllImport("User32.dll")]
        
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport(
"User32.dll")]
        
private static extern bool SetForegroundWindow(IntPtr hWnd);

        
private const int WS_SHOWNORMAL = 1;


        
public static Process GetRunningInstance()
        {
            Process currentProcess 
= Process.GetCurrentProcess();
            
string currentFileName = currentProcess.MainModule.FileName;
            Process[] processes 
= Process.GetProcessesByName(currentProcess.ProcessName);
            
foreach (Process process in processes)
            {
                
if (process.MainModule.FileName == currentFileName)
                {
                    
if (process.Id != currentProcess.Id)
                        
return process;
                }
            }
            
return null;
        }


        
public static bool HandleRunningInstance(Process instance)
        {

            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
            
return SetForegroundWindow(instance.MainWindowHandle);
        }

        
public static bool HandleRunningInstance()
        {
            Process p 
= GetRunningInstance();
            
if (p != null)
            {
                HandleRunningInstance(p);
                
return true;
            }
            
return false;
        }


    }

 

相关文章:

  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2021-09-22
  • 2022-12-23
  • 2021-06-27
  • 2021-12-26
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-26
  • 2022-01-18
  • 2021-10-03
  • 2022-12-23
相关资源
相似解决方案