winform內部打開微信或者其他EXE程序

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Diagnostics;
 4 using System.Linq;
 5 using System.Runtime.InteropServices;
 6 using System.Threading.Tasks;
 7 using System.Windows.Forms;
 8 
 9 namespace WindowsFormsApp1
10 {
11     internal static class Program
12     {
13         /// <summary>
14         /// 應用程序的主入口點。
15         /// </summary>
16         [STAThread]
17         static void Main()
18         {
19             Application.EnableVisualStyles();
20             Application.SetCompatibleTextRenderingDefault(false);
21 
22             // 獲取微信的進程
23             var ps = Process.GetProcesses().Where(m=>m.ProcessName=="WeChat").FirstOrDefault();
24             //Process[] ps2 = Process.GetProcessesByName("WeChat");
25             // 獲取微信的句柄,intClientWndHandle是父窗口的句柄,需要先得到這個句柄
26             var intClientWndHandle = ProcessEx.GetMainWindowHandle(ps.Id);
27             // 父窗體
28             Form1 frm = new Form1();
29             // 設置當前窗體是微信句柄的父級
30             SetParent(intClientWndHandle, (IntPtr)frm.Handle);
31             // 是否顯示控件框
32             frm.ControlBox = false;
33             Application.Run(frm);
34         }
35 
36 
37         [DllImport("user32.dll", EntryPoint = "SetParent")]
38         public static extern int SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
39 
40         [StructLayout(LayoutKind.Sequential)]
41         public struct ProcessEntry32
42         {
43             public uint dwSize;
44             public uint cntUsage;
45             public uint th32ProcessID;
46             public IntPtr th32DefaultHeapID;
47             public uint th32ModuleID;
48             public uint cntThreads;
49             public uint th32ParentProcessID;
50             public int pcPriClassBase;
51             public uint dwFlags;
52 
53 
54             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
55             public string szExeFile;
56         }
57          
58     }
59 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章