WPF用户控件库 嵌入外部(VLC)exe

综合网上资源完成的自己的第一篇博客

------------------------------------------------------------------------

网上类似的贴子挺多的,由于情况不太一样。网上相关帖子都是在 MainWindow 嵌入。我需要在原有客户端上开发新的插件即用户控件库实现嵌入外部exe。

主要问题:获取不到窗口句柄。

 

1、利用系统API实现嵌入。

1         [DllImport("user32.dll", SetLastError = true)]
2         public static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
3 
4         [DllImport("user32.dll")]
5         public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

2、当时在获取页面(用户控件库)的句柄问题上碰壁,主要思路是在页面上加Border、Grid等类似的容器控件。然后可通过程序集“PresentationCore”里的方法获取。

但需要注意的是,不能在页面加载过程中获取句柄。可在button的click事件触发、容器控件的load事件触发、、、

 1 using System;
 2 using System.Diagnostics;
 3 using System.Windows;
 4 using System.Windows.Interop;
 5 using System.Reflection;
 6 using System.IO;
 7 
 8 namespace AlarmCenter.Addin.RunVLC
 9 {
10     /// <summary>
11     /// HomePage.xaml 的交互逻辑
12     /// </summary>
13     public partial class HomePage
14     {
15         string RootPath;
16         //定义变量
17         private IntPtr prsmwh;//外部exe文件运行句柄
18         private Process process;//外部exe文件对象
19         public HomePage()
20         {
21             InitializeComponent();
22             RootPath = AlarmCenter.Core.General.GetApplicationRootPath();//获取相对可执行文件路径
23         }
24 
25         public void RunVLC()
26         {
27             //获取当前窗口句柄
28             IntPtr handle = ((HwndSource)PresentationSource.FromVisual(bd_test)).Handle;
29 
30             string path = null;
31             var currentAssembly = Assembly.GetEntryAssembly();
32             var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
33             if (currentDirectory == null) return;
34             //初始化配置,指定可执行文件路径
35             if (AssemblyName.GetAssemblyName(currentAssembly.Location).ProcessorArchitecture == ProcessorArchitecture.X86)
36                 path = RootPath + @"\bin\VLCPlayerSDK\libvlc_x86\vlc.exe";
37             else
38                 path = RootPath + @"\bin\VLCPlayerSDK\libvlc_x64\vlc.exe";
39 
40             process = Process.Start(path, RootPath + "\\bin\\宣传片\\test.mkv -f --no-video-title-show --repeat --no-interact --video-on-top --mouse-hide-timeout=1");
41             prsmwh = process.MainWindowHandle;
42             while (prsmwh == IntPtr.Zero)
43             {
44                 prsmwh = process.MainWindowHandle;
45             }
46             //设置父窗口
47             SDK.SetParent(prsmwh, handle);
48             SDK.ShowWindowAsync(prsmwh, 3);//子窗口最大化 
49         }
50 
51         public override void Dispose()
52         {
53             process?.Kill();
54             base.Dispose();
55         }
56 
57         private void Bd_test_Loaded(object sender, RoutedEventArgs e)
58         {
59             RunVLC();
60         }
61     }
62 }
posted @ 2019-02-27 17:29  仰丶  阅读(958)  评论(0编辑  收藏  举报