直接上代码:
调用代码
ProcessStartInfo startinfo1 = new ProcessStartInfo();
startinfo1.FileName = "E:\\fastdds\\run\\" + PlanType + ".exe";
startinfo1.Arguments = winInfo;
pss = Process.Start(startinfo1);//做延时的原因是window打开exe时会有一定的时间,这个时间立刻执行是获取不到句柄的
Invoke("OpenZhiding",0.5f);
延时代码内容
public void OpenZhiding(){hWnd = Zhiding.GetProcessWnd(pss.MainWindowHandle);Active();}
激活窗口
/// <summary>/// 激活窗口/// </summary>void Active(){if (KeepForeground){ShowWindow(hWnd, 1);SetForegroundWindow(hWnd);SetWindowPos(hWnd, HWND_TOPMOST, 302, 318, 1575, 591, SWP_NOSIZE | SWP_NOMOVE);}}
获取句柄等操作 zhiding.cs
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;public class Zhiding
{public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);[DllImport("user32.dll", SetLastError = true)]public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);[DllImport("user32.dll", SetLastError = true)]public static extern IntPtr GetParent(IntPtr hWnd);[DllImport("user32.dll")]public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);[DllImport("kernel32.dll")]public static extern void SetLastError(uint dwErrCode);public static IntPtr GetProcessWnd(IntPtr Ptr){IntPtr ptrWnd = Ptr;uint pid = 0;foreach (var item in Process.GetProcesses()){//User.JiemianPlanModel是启动的exe名称,不包含.exe后缀if (item.ProcessName == User.JiemianPlanModel){pid = (uint)item.Id;}}MgrTips.Instance.ShowTip(pid.ToString());bool bResult = EnumWindows(new WNDENUMPROC(delegate (IntPtr hwnd, uint lParam){uint id = 0;if (GetParent(hwnd) == IntPtr.Zero){GetWindowThreadProcessId(hwnd, ref id);if (id == lParam) // 找到进程对应的主窗口句柄 {ptrWnd = hwnd; // 把句柄缓存起来 MgrTips.Instance.ShowTip(ptrWnd.ToString());SetLastError(0); // 设置无错误 return false; // 返回 false 以终止枚举窗口 }}return true;}), pid);return (!bResult && Marshal.GetLastWin32Error() == 0) ? ptrWnd : IntPtr.Zero;}
}