命名空间
using System.Runtime.InteropServices;
声明部分
private static IntPtr hwnd_win; //根据窗体的标题查找窗体的句柄,第一个参数是窗体类名,一般为null。第二个参数是窗体的标题 [DllImport("user32.dll")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); //遍历所有子窗体 [DllImport("user32.dll")] private static extern int EnumChildWindows(int hWndParent, CallBack lpfn, int lParam); /// <summary> /// 获取类名字 /// </summary> /// <param name="hwnd">需要获取类名的句柄</param> /// <param name="lpClassName">类名(执行完成以后查看)</param> /// <param name="nMaxCount">缓冲区</param> /// <returns></returns> [DllImport("user32.dll", EntryPoint = "GetClassName")] private static extern int GetClassName(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount); /// <summary> /// 设置窗体是否可用 /// </summary> /// <param name="hwnd">窗体句柄</param> /// <param name="fEnable">是否可用</param> /// <returns>非零表示成功,零表示失败</returns> [DllImport("user32")] public static extern bool EnableWindow( IntPtr hwnd, bool fEnable ); public delegate bool CallBack(IntPtr hwnd, int lParam);
主要代码
/// <summary> /// 遍历子控件 /// </summary> /// <param name="hwnd"></param> /// <param name="lParam"></param> /// <returns></returns> public static bool ChildWindowEnable(IntPtr hwnd, int lParam) { try { StringBuilder s = new StringBuilder(2000); GetClassName(hwnd, s, 255); if (s.ToString() == "WindowsForms10.BUTTON.app.0.378734a") { EnableWindow(hwnd, true ); } return true; } catch (Exception) { return false; } } public static bool ChildWindowDisable(IntPtr hwnd, int lParam) { try { StringBuilder s = new StringBuilder(2000); GetClassName(hwnd, s, 255); if (s.ToString() == "WindowsForms10.BUTTON.app.0.378734a") { EnableWindow(hwnd, false); } return true; } catch (Exception) { return false; } } private void btnSetEnable_Click(object sender, EventArgs e) { hwnd_win = FindWindow(null, formTitle.Text.Trim()); CallBack cb = new CallBack(ChildWindowEnable); EnumChildWindows(hwnd_win.ToInt32(), cb, 0); } private void btnSetDisable_Click(object sender, EventArgs e) { hwnd_win = FindWindow(null, formTitle.Text.Trim()); CallBack cb = new CallBack(ChildWindowDisable); EnumChildWindows(hwnd_win.ToInt32(), cb, 0); }