引用的函数:
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
static extern bool AllocConsole();//开启
[System.Runtime.InteropServices.DllImport("Kernel32")]
public static extern void FreeConsole();//关闭
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "FindWindow")]
extern static IntPtr FindWindow(string lpClassName, string lpWindowName);//找出运行的窗口
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert); //取出窗口运行的菜单
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "RemoveMenu")]
extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //灰掉按钮
[System.Runtime.InteropServices.DllImport("User32.dll ", EntryPoint = "SetParent")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);//设置父窗体
[System.Runtime.InteropServices.DllImport("user32.dll ", EntryPoint = "ShowWindow")]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);//显示窗口
内嵌窗体(我嵌入给一个tabpages的一个页面)
if (AllocConsole())
{
Console.Title = "数据显示";//先定义窗口标题,防止未找到
windowHandle = FindWindow(null, Process.GetCurrentProcess().MainModule.FileName);
if (windowHandle != IntPtr.Zero)//在根目录下或VS下进入
{
Thread.Sleep(100);
SetParent(windowHandle, 数据显示.TabPages[0].Handle);
closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
uint SC_CLOSE = 0xF060;
RemoveMenu(closeMenu, SC_CLOSE, 0x0);//屏蔽关闭按钮
}
else //快捷方式启动进入
{
MessageBox.Show("未找到父窗体,即将重定向!!!","重定向查找");
windowHandle = FindWindow(null, "数据显示");
if (windowHandle != IntPtr.Zero)
{
Thread.Sleep(100);
SetParent(windowHandle, 数据显示.TabPages[0].Handle);
closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
uint SC_CLOSE = 0xF060;
RemoveMenu(closeMenu, SC_CLOSE, 0x0);//屏蔽关闭按钮
}
}
Console.WindowWidth = 100;
Console.SetWindowPosition(0, 0);
Console.ForegroundColor = ConsoleColor.Green;
ShowWindow(windowHandle, 3);
}
else
{
MessageBox.Show("请注意控制台窗口未正常打开,请检查环境!","环境缺失");
return;
}
最后:在绑定之前,父窗体一定要刷出来哈