管理

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

Posted on 2025-10-06 14:51  lzhdim  阅读(8609)  评论(0)    收藏  举报
/***

    进程工具类

    Austin Liu 刘恒辉
    Project Manager and Software Designer

    E-Mail: lzhdim@163.com
    Blog:   http://lzhdim.cnblogs.com
    Date:   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 API

        private 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;
        }
    }
}

 

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved