当前位置: 首页 > news >正文

进程工具类 - C#小函数类推荐

进程工具类 - C#小函数类推荐

Posted on 2025-10-06 14:51  lzhdim  阅读(0)  评论(0)    收藏  举报
/***进程工具类Austin Liu 刘恒辉Project Manager and Software DesignerE-Mail: lzhdim@163.comBlog:   http://lzhdim.cnblogs.comDate:   2024-01-15 15:18:00***/namespace Lzhdim.LPF.Utility
{using System;using System.Diagnostics;using System.Runtime.InteropServices;using System.Text;/// <summary>/// 进程工具类/// </summary>public class ProcessUtil{#region Windows 32 APIprivate delegate bool EnumWindowProc(IntPtr hWnd, IntPtr lParam);[DllImport("user32.dll")]private static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowProc lpEnumFunc, IntPtr lParam);[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);[DllImport("user32.dll", SetLastError = true)]private static extern int GetWindowTextLength(IntPtr hWnd);#endregion Windows 32 API/// <summary>/// 根据进程名查找底下的某个窗体/// </summary>/// <param name="processName">进程名</param>/// <param name="windowTitle">窗体名</param>/// <returns>该窗体的句柄</returns>public static IntPtr FindWindowHandleFormProcess(string processName, string windowTitle){IntPtr intPtr = IntPtr.Zero;bool bIsFind = false;Process[] processes = Process.GetProcessesByName(processName); // 替换为实际进程名foreach (Process process in processes){EnumChildWindows(process.MainWindowHandle, (hWnd, param) =>{int length = GetWindowTextLength(hWnd);if (length > 0){StringBuilder sb = new StringBuilder(length);GetWindowText(hWnd, sb, length + 1);if (sb.ToString() == windowTitle){intPtr = hWnd;bIsFind = true;return true;}}return true;}, IntPtr.Zero);if (bIsFind) break;}return intPtr;}}
}