C# Winform窗体应用程序中调用第三方Exe文件

C# Winform窗体应用程序中调用第三方Exe文件

//命名空间
using System.Runtime.InteropServices;
using System.Windows.Forms;
  1. 对调用第三方exe应用程序时涉及到的接口进行简单封装
public class ThirdExeInterface
{
    
    
		[DllImport("User32.dll", EntryPoint = "SetParent")]
		private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

		[DllImport("user32.dll", EntryPoint = "ShowWindow")]
		private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

		[DllImport("user32.dll", SetLastError = true)]
		private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
      
      IntPtr intPtr = new IntPtr();
	  //检测进程是否存在
	  public bool CheckProcessExists(string  szProcessName)
		{
    
    
			try
			{
    
    
				Process[] processes = Process.GetProcessesByName(szProcessName );
				foreach (Process p in processes)
				{
    
    
					if (System.IO.Path.Combine(Application.StartupPath, szProcessName) == p.MainModule.FileName)
						return true;
				}
			}
			catch (Exception e)
			{
    
    
				MessageBox.Show(e.Message);
			}
			return false;
		}

        //杀死进程
		private void KillProcess(string  szProcessName)
		{
    
    
			Process[] processes = Process.GetProcessesByName(szProcessName);
			foreach (Process p in processes)
			{
    
    
				if (System.IO.Path.Combine(Application.StartupPath, szProcessName) == p.MainModule.FileName)
				{
    
    
					p.Kill();
					p.Close();
				}
			}
		}
		
		//运行
		public void RunThirdExe(string  szProcessName)
		{
    
    
			try
			{
    
    
				if (CheckProcessExists())
				{
    
    
					KillProcess();
				}

				string fexePath = szProcessName; // 外部exe位置,如 fexePath  = @"DrawingTools.exe";//位于执行目录下

				Process p = new Process();
				p.StartInfo.FileName = fexePath;
				p.StartInfo.UseShellExecute = false;
				p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
				p.Start();

				while (p.MainWindowHandle.ToInt32() == 0)
				{
    
    
					System.Threading.Thread.Sleep(100);
				}
				SetParent(p.MainWindowHandle, this.Handle);
				intPtr = p.MainWindowHandle;
				MoveWindow(p.MainWindowHandle, 0, 30, this.Width - 18, this.Height - 50, true);
			}
			catch (Exception e)
			{
    
    
				MessageBox.Show(e.Source + " " + e.Message);
			}
		}
        
        //隐藏
		public void HideThirdExe()
		{
    
    
			ShowWindow(intPtr, (int)ProcessWindowStyle.Normal);//隐藏
		}
}

2.当需要运行第三方应用程序时,调用RunThirdExe()
3.当需要隐藏调用的程序时,调用HideThirdExe()

猜你喜欢

转载自blog.csdn.net/CXYLVCHF/article/details/111226066