在WPF中使用Winfom控件
首先要解決在WPF中如何使用Winfom控件的問(wèn)題,官方對(duì)此有支持的方式。
添加winform相關(guān)的程序集
在引用管理器中添加winfrom相關(guān)的程序集System.Windows.Forms
和WindowsFormsIntegration
。
在XAML頭中加入對(duì)這兩個(gè)程序集命名空間的引用
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
使用Winform控件
然后使用winform的控件,得在外面套一層WindowsFormsHost(好像添加了WindowsFormsIntegration,不使用wfi:也能使用)
<wfi:WindowsFormsHost Margin="0,0,400,73">
<wf:TextBox />
</wfi:WindowsFormsHost>
效果:
這樣就可以在WPF中使用Winform控件,但是不推薦,除非特殊情況。
問(wèn)題
這種方式存在的問(wèn)題:
-
WindowsFormsHost依舊是顯示在最前,暫時(shí)沒(méi)找到解決方法,盡量從設(shè)計(jì)上避免
-
后臺(tái)無(wú)法獲取到WindowsFormsHost內(nèi)部控件的名稱(chēng),只能通過(guò)
WindowsFormsHost
獲取內(nèi)部控件的句柄。
在Winfom控件中嵌入exe程序
準(zhǔn)備Winfrom控件
WindowsFormsHost
中控件換成Panel
<wfi:WindowsFormsHost Name="WFHost" Margin="0,0,400,73">
<wf:Panel />
</wfi:WindowsFormsHost>
更換父窗體的句柄
將獲取主窗體句柄換成獲取Panel句柄,然后設(shè)置窗體大小跟WindowsFormsHost
控件一樣
//當(dāng)前窗體/容器(主程序)句柄
IntPtr hwnd = WFHost.Child.Handle;
//設(shè)置窗體位置和大小
MoveWindow(appWin, 0, 0, (int)WFHost.ActualWidth, (int)WFHost.ActualHeight, true);
完整實(shí)現(xiàn)代碼:
上述功能完整實(shí)現(xiàn)的代碼如下
可以更新到上一篇的MainWindow的代碼中去。
var exeName = "C:\\WINDOWS\\system32\\mspaint";
//使用Process運(yùn)行程序
Process p = new Process();
p.StartInfo.FileName = exeName;
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.Start();
//獲取窗體句柄
while (p.MainWindowHandle.ToInt32() == 0)
{
System.Threading.Thread.Sleep(100);
}
IntPtr appWin = p.MainWindowHandle;//子窗體(外部程序)句柄
//當(dāng)前窗體/容器(主程序)句柄
IntPtr hwnd = WFHost.Child.Handle;
//設(shè)置父窗體(實(shí)現(xiàn)窗體嵌入)
SetParent(appWin, hwnd);
//設(shè)置窗體樣式
var style = GetWindowLong(appWin, GWL_STYLE);
SetWindowLong(appWin, GWL_STYLE, style & ~WS_CAPTION & ~WS_THICKFRAME);
//設(shè)置窗體位置和大小
MoveWindow(appWin, 0, 0, (int)WFHost.ActualWidth, (int)WFHost.ActualHeight, true);
實(shí)現(xiàn)效果:
搞個(gè)Grid分多行和列,進(jìn)行拖動(dòng)操作,可以看到子窗體顯示區(qū)域限制在WindowsFormsHost 內(nèi)部了,拖動(dòng)變化子窗體不會(huì)超出顯示區(qū)域。
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-584073.html
問(wèn)題和后續(xù)更新
子窗體實(shí)現(xiàn)大小還是固定的,沒(méi)有隨著控件變化實(shí)時(shí)調(diào)整,需要窗體或者控件調(diào)整大小重繪時(shí),使用MoveWindow
刷新,以達(dá)到子窗體尺寸跟隨控件尺寸的大小,實(shí)現(xiàn)更好的嵌入。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-584073.html
到了這里,關(guān)于WPF嵌入外部exe應(yīng)用程序-使用Winfom控件承載外部程序的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!