目录
如何意想天开地对一个没有源码的窗体UI加以改造,甚至响应来自这个点击事件,在自己的程序里编写事件代码?
本文提供两个VS2022的C#程序,一个是模拟没有源码的目标程序,一个是实现以上想法的主程序。
页面展示
1、目标程序的窗体
2、主程序的窗体
3、实现效果
实现过程
1、查找目标窗体
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(
string lpClassName, /* 窗体类名 */
string lpWindowName /* 窗体标题 */
);
IntPtr hProcessB = CWindowsAPI.FindWindow(null, "把柄程序B");
2、隐藏目标窗体中的控件
不是必须要隐藏
[DllImport("user32.DLL")] public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("user32.dll")] public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); IntPtr hControl1 = CWindowsAPI.FindWindowEx(hProcessB, IntPtr.Zero, "WindowsForms10.Window.8.app.0.141b42a_r9_ad1", null); CWindowsAPI.ShowWindow(hControl1, CWindowsAPI.SW_HIDE); IntPtr hControl2 = CWindowsAPI.FindWindowEx(hProcessB, IntPtr.Zero, null, "toolStrip1"); CWindowsAPI.ShowWindow(hControl2, CWindowsAPI.SW_HIDE); IntPtr hControl3 = CWindowsAPI.FindWindowEx(hProcessB, IntPtr.Zero, null, "menuStrip1"); CWindowsAPI.ShowWindow(hControl3, CWindowsAPI.SW_HIDE);
3、移动控件
[DllImport("user32.dll", EntryPoint = "SetParent")]
public static extern int SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
public const uint SWP_NOSIZE = 0x0001;
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags);
CWindowsAPI.SetParent(menuStrip1.Handle, hProcessB);
CWindowsAPI.SetParent(toolStrip1.Handle, hProcessB);
CWindowsAPI.SetParent(label1.Handle, hProcessB);
CWindowsAPI.SetParent(textBox1.Handle, hProcessB);
CWindowsAPI.SetParent(btnRun.Handle, hProcessB);
CWindowsAPI.SetWindowPos(label1.Handle, IntPtr.Zero, 30, 155, 0, 0, CWindowsAPI.SWP_NOSIZE);
CWindowsAPI.SetWindowPos(textBox1.Handle, IntPtr.Zero, 100, 150, 0, 0, CWindowsAPI.SWP_NOSIZE);
CWindowsAPI.SetWindowPos(btnRun.Handle, IntPtr.Zero, 100, 200, 0, 0, CWindowsAPI.SWP_NOSIZE);