综合网上资源完成的自己的第一篇博客
------------------------------------------------------------------------
网上类似的贴子挺多的, 由于情况不太一样. 网上相关帖子都是在 MainWindow 嵌入. 我需要在原有客户端上开发新的插件即用户控件库实现嵌入外部 exe.
主要问题: 获取不到窗口句柄.
1, 利用系统 API 实现嵌入.
- [DllImport("user32.dll", SetLastError = true)]
- public static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
- [DllImport("user32.dll")]
- public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
2, 当时在获取页面 (用户控件库) 的句柄问题上碰壁, 主要思路是在页面上加 Border,Grid 等类似的容器控件. 然后可通过程序集 "PresentationCore" 里的方法获取.
但需要注意的是, 不能在页面加载过程中获取句柄. 可在 button 的 click 事件触发, 容器控件的 load 事件触发,,,
- using System;
- using System.Diagnostics;
- using System.Windows;
- using System.Windows.Interop;
- using System.Reflection;
- using System.IO;
- namespace AlarmCenter.Addin.RunVLC
- {
- /// <summary>
- /// HomePage.xaml 的交互逻辑
- /// </summary>
- public partial class HomePage
- {
- string RootPath;
- // 定义变量
- private IntPtr prsmwh;// 外部 exe 文件运行句柄
- private Process process;// 外部 exe 文件对象
- public HomePage()
- {
- InitializeComponent();
- RootPath = AlarmCenter.Core.General.GetApplicationRootPath();// 获取相对可执行文件路径
- }
- public void RunVLC()
- {
- // 获取当前窗口句柄
- IntPtr handle = ((HwndSource)PresentationSource.FromVisual(bd_test)).Handle;
- string path = null;
- var currentAssembly = Assembly.GetEntryAssembly();
- var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
- if (currentDirectory == null) return;
- // 初始化配置, 指定可执行文件路径
- if (AssemblyName.GetAssemblyName(currentAssembly.Location).ProcessorArchitecture == ProcessorArchitecture.X86)
- path = RootPath + @"\bin\VLCPlayerSDK\libvlc_x86\vlc.exe";
- else
- path = RootPath + @"\bin\VLCPlayerSDK\libvlc_x64\vlc.exe";
- process = Process.Start(path, RootPath + "\\bin\\ 宣传片 \\test.mkv -f --no-video-title-show --repeat --no-interact --video-on-top --mouse-hide-timeout=1");
- prsmwh = process.MainWindowHandle;
- while (prsmwh == IntPtr.Zero)
- {
- prsmwh = process.MainWindowHandle;
- }
- // 设置父窗口
- SDK.SetParent(prsmwh, handle);
- SDK.ShowWindowAsync(prsmwh, 3);// 子窗口最大化
- }
- public override void Dispose()
- {
- process?.Kill();
- base.Dispose();
- }
- private void Bd_test_Loaded(object sender, RoutedEventArgs e)
- {
- RunVLC();
- }
- }
- }
WPF 用户控件库 嵌入外部(VLC)exe
来源: http://www.bubuko.com/infodetail-2970583.html