C#使用Process类运行外部程序,已运行的程序自动还原主窗体
作者:C/S框架网  发布日期:2012-11-30 10:26:02
  C#使用Process类运行外部程序,已运行的程序自动还原主窗体



 

C# Code:

private const int WS_SHOWNORMAL = 1;

[DllImport("User32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

[DllImport("User32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);



/// <summary>
/// 运行外部程序,如程序已运行自动还原主窗体
/// </summary>
/// <param name="processName">进程名称</param>
/// <param name="filePath">需要运行的程序文件</param>
/// <param name="args">启动程序的命令行参数</param>
public static void RunProgram(string processName, string filePath, string args)
{
   try
   {
      //查找进程
      Process por = FindProcess(processName, filePath);
      if (por != null)
      {
         //如程序已运行自动还原主窗体
         ShowWindowAsync(por.MainWindowHandle, WS_SHOWNORMAL);
         SetForegroundWindow(por.MainWindowHandle);
         return;
      }
      
      //启动进程
      ProcessStartInfo p = new ProcessStartInfo();
      p.FileName = filePath;
      p.WindowStyle = ProcessWindowStyle.Normal;
      p.Arguments = args;
      Process pr = Process.Start(p);
      
      Application.DoEvents();
      Thread.Sleep(2000);//等待启动程序
   }
   catch (Exception ex)
   {
      Msg.ShowException(ex);
   }
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898



调用:

C# Code:

string file = Application.StartupPath @"\ERP.AttendImporter.exe";

MdiTools.RunProgram("ERP.AttendImporter", file, "User:" Loginer.CurrentUser.Account);


 

上一篇 下一篇