在Winform中嵌入exe程序
|
admin
2024年1月24日 23:23
本文熱度 494
|
開發(fā)環(huán)境:.NET Framework版本:4.8
開發(fā)工具:Visual Studio 2022 - 這里為了方便調(diào)用,以容器控件的方式來(lái)實(shí)現(xiàn)
- 創(chuàng)建自定義控件,繼承自
Control ,然后需要使用下面的Windows Api
#region win32 api
//設(shè)置新 窗口樣式 private const int GWL_STYLE = -16;
private const int WS_VISIBLE = 0x10000000;
[DllImport("user32.dll", SetLastError = true)] public static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)] public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, int dwNewLong); [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)] public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, int dwNewLong);
public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong) { if (IntPtr.Size == 4) { return SetWindowLongPtr32(hWnd, nIndex, dwNewLong); } return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); }
[DllImport("user32.dll", SetLastError = true)] private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
[DllImport("user32.dll", SetLastError = true)] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32", SetLastError = true)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
#endregion
- 以路徑形式的嵌入,這個(gè)方式不太好,很多程序啟動(dòng)后嵌入不了
if (AppProcess != null) { Release(); } try { ProcessStartInfo startInfo = new ProcessStartInfo(appFilename); startInfo.UseShellExecute = true; startInfo.WindowStyle = ProcessWindowStyle.Minimized; AppProcess = Process.Start(startInfo); AppProcess.EnableRaisingEvents = true; AppProcess.WaitForInputIdle(); Embed(AppProcess.MainWindowHandle); } catch { Release(); } return Path.GetFileNameWithoutExtension(appFilename); - 以窗口標(biāo)題的形式嵌入,這個(gè)主要還是依賴于句柄,不過(guò)是多做了一層根據(jù)標(biāo)題找句柄的封裝
public string Embed(string className, string windowName) { try { IntPtr handle = FindWindow(className, windowName); Embed(handle); } catch { } return windowName; }
public string Embed(IntPtr handle) { try { SetParent(handle, this.Handle); SetWindowLong(new HandleRef(this, handle), GWL_STYLE, WS_VISIBLE); MoveWindow(handle, 0, 0, this.Width, this.Height, true); } catch { } StringBuilder title = new StringBuilder(256); GetWindowText(handle, title, title.Capacity); return title.ToString(); } - 調(diào)用,直接將控件拖到窗體中,然后調(diào)用對(duì)應(yīng)方法即可
- 關(guān)于句柄和窗口標(biāo)題的獲取,可以使用Spy++獲取,如果在Vs2022上找不到,請(qǐng)點(diǎn)擊工具->獲取工具和功能->單個(gè)組件->勾選C++核心功能,安裝完畢后就會(huì)在工具菜單內(nèi)出現(xiàn)
- 以下演示效果為已經(jīng)預(yù)先使用Spy++獲取到了標(biāo)題和句柄
轉(zhuǎn)載:https://mp.weixin.qq.com/s/KXyUe-ALW9nb9jKRhkXtCQ
該文章在 2024/1/24 23:23:04 編輯過(guò)
|
|