目录
参考的代码来源:https://bbs.youkuaiyun.com/topics/390344060
参考的代码来源:https://bbs.youkuaiyun.com/topics/390344060
参考的代码,有部分更改:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_Tank_Scout
{
public class exe2Winform
{
#region 字段
/*
Application.Idle:当应用程序完成处理并即将进入空闲状态时发生
-->appIdleEvent:要处理的事件
-->订阅了Application_Idle:确保应用程序嵌入此容器
调用:-->EmbedProcess:将指定的程序嵌入指定的控件
*/
EventHandler appIdleEvent = null;
Control ParentCon = null;
string strGUID = "";
#endregion
#region Win32 API
[DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
private static extern long GetWindowLong(IntPtr hwnd, int nIndex);
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", 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);
[DllImport("user32.dll", SetLastError = true)]
private static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags);
[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", EntryPoint = "PostMessageA", SetLastError = true)]
private static extern bool PostMessage(IntPtr hwnd, uint Msg, uint wParam, uint lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetParent(IntPtr hwnd);
[DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SWP_NOOWNERZORDER = 0x200;
private const int SWP_NOREDRAW = 0x8;
private const int SWP_NOZORDER = 0x4;
private const int SWP_SHOWWINDOW = 0x0040;
private const int WS_EX_MDICHILD = 0x40;
private const int SWP_FRAMECHANGED = 0x20;
private const int SWP_NOACTIVATE = 0x10;
private const int SWP_ASYNCWINDOWPOS = 0x4000;
private const int SWP_NOMOVE = 0x2;
private const int SWP_NOSIZE = 0x1;
private const int GWL_STYLE = (-16);
private const int WS_VISIBLE = 0x10000000;
private const int WM_CLOSE = 0x10;
private const int WS_CHILD = 0x40000000;
private const int SW_HIDE = 0; //{隐藏, 并且任务栏也没有最小化图标}
private const int SW_SHOWNORMAL = 1; //{用最近的大小和位置显示, 激活}
private const int SW_NORMAL = 1; //{同 SW_SHOWNORMAL}
private const int SW_SHOWMINIMIZED = 2; //{最小化, 激活}
private const int SW_SHOWMAXIMIZED = 3; //{最大化, 激活}
private const int SW_MAXIMIZE = 3; //{同 SW_SHOWMAXIMIZED}
private const int SW_SHOWNOACTIVATE = 4; //{用最近的大小和位置显示, 不激活}
private const int SW_SHOW = 5; //{同 SW_SHOWNORMAL}
private const int SW_MINIMIZE = 6; //{最小化, 不激活}
private const int SW_SHOWMINNOACTIVE = 7; //{同 SW_MINIMIZE}
private const int SW_SHOWNA = 8; //{同 SW_SHOWNOACTIVATE}
private const int SW_RESTORE = 9; //{同 SW_SHOWNORMAL}
private const int SW_SHOWDEFAULT = 10; //{同 SW_SHOWNORMAL}
private const int SW_MAX = 10; //{同 SW_SHOWNORMAL}
#endregion Win32 API
#region 属性
/// <summary>
/// application process
/// 应用程序进程
/// </summary>
Process m_AppProcess = null;
/// <summary>
/// 标识内嵌程序是否已经启动
/// </summary>
public bool IsStarted { get { return (this.m_AppProcess != null); } }
#endregion 属性
#region 方法
public exe2Winform(Control C, string Titlestr)
{
/*
Application.Idle:当应用程序完成处理并即将进入空闲状态时发生
-->appIdleEvent:要处理的事件
-->订阅了Application_Idle:确保应用程序嵌入此容器
调用:-->EmbedProcess:将指定的程序嵌入指定的控件
*/
appIdleEvent = new EventHandler(Application_Idle);
ParentCon = C;
strGUID = Titlestr;
}
/// <summary>
/// 窗体最大化和窗体化时重新改变尺寸
/// </summary>
public void Resize()
{
EmbedProcess(m_AppProcess, ParentCon);
}
/// <summary>
/// 将属性<code>AppFilename</code>指向的应用程序打开并嵌入此容器
/// </summary>
public IntPtr Start(string FileNameStr)
{
if (m_AppProcess != null)
{
Stop();
}
try
{
ProcessStartInfo info = new ProcessStartInfo(FileNameStr);
info.UseShellExecute = true;
//info.WindowStyle = ProcessWindowStyle.Normal;
info.WindowStyle = ProcessWindowStyle.Maximized;
m_AppProcess = System.Diagnostics.Process.Start(info); //启动由包含进程启动信息
m_AppProcess.WaitForInputIdle(); //使 System.Diagnostics.Process 组件无限期地等待关联进程进入空闲状态
/*
Application.Idle:当应用程序完成处理并即将进入空闲状态时发生
-->appIdleEvent:要处理的事件
-->订阅了Application_Idle:确保应用程序嵌入此容器
调用:-->EmbedProcess:将指定的程序嵌入指定的控件
*/
Application.Idle += appIdleEvent;
}
catch
{
if (m_AppProcess != null)
{
if (!m_AppProcess.HasExited)
m_AppProcess.Kill();
m_AppProcess = null;
}
}
return m_AppProcess.Handle;
}
/// <summary>
/// 确保应用程序嵌入此容器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Application_Idle(object sender, EventArgs e)
{
if (this.m_AppProcess == null || this.m_AppProcess.HasExited)
{
this.m_AppProcess = null;
Application.Idle -= appIdleEvent;
return;
}
Thread.Sleep(300);//这里加阻塞 ,时间可以大些
Application.DoEvents();
if (m_AppProcess.MainWindowHandle == IntPtr.Zero)
return;
Application.Idle -= appIdleEvent;
/*
Application.Idle:当应用程序完成处理并即将进入空闲状态时发生
-->appIdleEvent:要处理的事件
-->订阅了Application_Idle:确保应用程序嵌入此容器
调用:-->EmbedProcess:将指定的程序嵌入指定的控件
*/
EmbedProcess(m_AppProcess, ParentCon);
}
/// <summary>
/// 应用程序结束运行时要清除这里的标识
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void m_AppProcess_Exited(object sender, EventArgs e)
{
m_AppProcess = null;
}
/// <summary>
/// 将属性<code>AppFilename</code>指向的应用程序关闭
/// </summary>
public void Stop()
{
if (m_AppProcess != null)// && m_AppProcess.MainWindowHandle != IntPtr.Zero)
{
try
{
if (!m_AppProcess.HasExited)
m_AppProcess.Kill();
}
catch (Exception)
{
}
m_AppProcess = null;
}
}
/// <summary>
/// 将指定的程序嵌入指定的控件
/// </summary>
private void EmbedProcess(Process app, Control control)
{
// Get the main handle
if (app == null || app.MainWindowHandle == IntPtr.Zero || control == null)
return;
try
{
// Put it into this form
// app.MainWindowHandle-获取关联进程主窗口的窗口句柄 , control.Handle-获取控件绑定到的窗口句柄
//private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
SetParent(app.MainWindowHandle, control.Handle);
}
catch (Exception)
{
}
try
{
// Remove border and whatnot
/*
HandleRef-用要包装的对象和由非托管代码使用的资源的句柄初始化 System.Runtime.InteropServices.HandleRef 类的新实例
Wrapper-获取保存资源句柄的对象, Handle-获取资源的句柄
Handle-句柄实际上是一种指向某种资源的指针
所以Windows给每个使用GlobalAlloc等函数声明的内存区域指定一个句柄(本质上仍是一个指针,但不要直接操作它),
平时只是在调用API函数时利用这个句柄来说明要操作哪段内存。
*/
SetWindowLong(new HandleRef(this, app.MainWindowHandle), GWL_STYLE, WS_VISIBLE);
SendMessage(app.MainWindowHandle, WM_SETTEXT, IntPtr.Zero, strGUID);
}
catch (Exception)
{
}
try
{
// Move the window to overlay it on this window
//control.Width-获取或设置控件的宽度, control.Height-获取或设置控件的高度
MoveWindow(app.MainWindowHandle, 0, 0, control.Width, control.Height, true);
}
catch (Exception)
{
}
}
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
const int WM_SETTEXT = 0x000C;
#endregion
}
}
自己修改的部分:
/// <summary>
/// 窗体最大化和窗体化时重新改变尺寸
/// </summary>
public void Resize()
{
EmbedProcess(m_AppProcess, ParentCon);
}
主程序部分:
using FinalGauge.PanelView;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_Tank_Scout
{
/// <summary>
/// panel_Right 分为 上, 中, 下 三个面板;
/// splitContainer1.Panel1 为上;
/// splitContainer_Right_Middle 为中:
/// splitContainer_Right_Middle.Panel1 为左边的 Panel
/// splitContainer_Right_Middle.Panel2 为右边的 Panel
/// splitContainer2.Panel2 为下.
/// </summary>
public partial class MainForm : Form
{
PhotoelectricControl_Form photoelectricControl_Form = PhotoelectricControl_Form.GetPhotoelectricControl_Form();
SatelliteNavigation_Form satelliteNavigation_Form = SatelliteNavigation_Form.GetSatelliteNavigation_Form();
AutomobileConditionControl_Form automobileConditionControl = new AutomobileConditionControl_Form();
PowerControl_Form powerControl = new PowerControl_Form();
TargetReafffirmation_Form targetReafffirmation_Form = TargetReafffirmation_Form.GetTargetReafffirmation_Form(); //目标确认窗体
exe2Winform fr = null; //加载场景的对象
bool fromax = false; //保证Resize在Load后面调用
public MainForm()
{
InitializeComponent();
}
/// <summary>
/// 加载某个控制页面
/// </summary>
private void Load_Form(Form form)
{
this.splitContainer1.Panel1.Controls.Clear();
form.FormBorderStyle = FormBorderStyle.None;
form.TopLevel = false;
form.BackColor = this.splitContainer1.Panel1.BackColor;
form.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Panel1.Controls.Add(form);
form.Show();
}
/// <summary>
/// 系统退出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 系统退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// 切换到光电总控界面
/// panel_Right 分为 上, 中, 下 三个面板
/// splitContainer1.Panel1 为上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_光电总控_Click(object sender, EventArgs e)
{
Load_Form(this.photoelectricControl_Form);
}
/// <summary>
/// 切换卫星导航界面
/// panel_Right 分为 上, 中, 下 三个面板
/// splitContainer1.Panel1 为上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_卫星导航_Click(object sender, EventArgs e)
{
Load_Form(this.satelliteNavigation_Form);
}
/// <summary>
/// 页面加载时显示某个界面
/// 显示光电总控
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Load(object sender, EventArgs e)
{
fromax = true;
Load_Form(this.photoelectricControl_Form); //默认加载光电总控
//this.WindowState = FormWindowState.Normal;
//加载主屏幕
fr = new exe2Winform(this.panel_Screen, "GUID: " + System.Guid.NewGuid().ToString());
fr.Start(RelativePath.getRelativePath(@"Investigation_Maximized\侦查场景.exe"));
//加载指南针
UserControlTurn userControlTurn = new UserControlTurn();
elementHost_direction.Child = userControlTurn;
}
private void button_电源管理_Click(object sender, EventArgs e)
{
Load_Form(this.powerControl);
}
private void button_车况总控_Click(object sender, EventArgs e)
{
Load_Form(this.automobileConditionControl);
}
private void 目标确认ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.targetReafffirmation_Form.Show(); //启动目标确认窗体
}
/// <summary>
/// 窗体最大化和正常化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Resize(object sender, EventArgs e)
{
if (fromax == true)
{
if (this.WindowState == FormWindowState.Maximized)
{
//fr.Stop(); //先关闭之前的场景
this.panel_Screen.Size = new Size(1560, 815);
fr.Resize();
//加载主屏幕
//fr = new exe2Winform(this.panel_Screen, "GUID: " + System.Guid.NewGuid().ToString());
//fr.Start(RelativePath.getRelativePath(@"Investigation_Maximized\侦查场景.exe"));
}
else if (this.WindowState == FormWindowState.Normal)
{
//fr.Stop(); //先关闭之前的场景
this.panel_Screen.Size = new Size(839, 462);
fr.Resize();
//加载主屏幕
//fr = new exe2Winform(this.panel_Screen, "GUID: " + System.Guid.NewGuid().ToString());
//fr.Start(RelativePath.getRelativePath(@"Investigation_Normal\侦查场景.exe"));
}
}
}
/*
* panel_Right 分为 上, 中, 下 三个面板
* splitContainer1.Panel1 为上
* splitContainer_Right_Middle 为中:
* splitContainer_Right_Middle.Panel1 为左边的 Panel
* splitContainer_Right_Middle.Panel2 为右边的 Panel
* splitContainer2.Panel2 为下.
*/
}
}
注意调用代码:
/// <summary>
/// 页面加载时显示某个界面
/// 显示光电总控
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Load(object sender, EventArgs e)
{
fromax = true;
Load_Form(this.photoelectricControl_Form); //默认加载光电总控
//this.WindowState = FormWindowState.Normal;
//加载主屏幕
fr = new exe2Winform(this.panel_Screen, "GUID: " + System.Guid.NewGuid().ToString());
fr.Start(RelativePath.getRelativePath(@"Investigation_Maximized\侦查场景.exe"));
//加载指南针
UserControlTurn userControlTurn = new UserControlTurn();
elementHost_direction.Child = userControlTurn;
}
改变窗体大小时调用的代码:
/// <summary>
/// 窗体最大化和正常化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Resize(object sender, EventArgs e)
{
if (fromax == true)
{
if (this.WindowState == FormWindowState.Maximized)
{
//fr.Stop(); //先关闭之前的场景
this.panel_Screen.Size = new Size(1560, 815);
fr.Resize();
//加载主屏幕
//fr = new exe2Winform(this.panel_Screen, "GUID: " + System.Guid.NewGuid().ToString());
//fr.Start(RelativePath.getRelativePath(@"Investigation_Maximized\侦查场景.exe"));
}
else if (this.WindowState == FormWindowState.Normal)
{
//fr.Stop(); //先关闭之前的场景
this.panel_Screen.Size = new Size(839, 462);
fr.Resize();
//加载主屏幕
//fr = new exe2Winform(this.panel_Screen, "GUID: " + System.Guid.NewGuid().ToString());
//fr.Start(RelativePath.getRelativePath(@"Investigation_Normal\侦查场景.exe"));
}
}
}
获取相对路径的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test_Tank_Scout
{
public static class RelativePath
{
/// <summary>
/// 获得相对路径, 此处为:ReconVehicleSimulator\Test_Tank_Scout\ + filename
/// </summary>
/// <param name="filename">数据文件,包括后缀,例如:DBforScout.db</param>
/// <returns></returns>
public static string getRelativePath(string filename)
{
string sDebug = System.Windows.Forms.Application.StartupPath; //获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称
string[] temp = sDebug.Trim().Split('\\');
string currentPath = "";
for (int i = 0; i < temp.Length-4; i++)
{
currentPath += temp[i] + "\\";
}
string relativePath = currentPath + filename;
return relativePath;
}
}
}