2023年11月29日发(作者:)

C#_winform内嵌控制台

引⽤的函数:

[System.Runtime.InteropServices.DllImport("", 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("", EntryPoint = "FindWindow")]

extern static IntPtr FindWindow(string lpClassName, string lpWindowName);//

找出运⾏的窗⼝

[System.Runtime.InteropServices.DllImport("", EntryPoint = "FindWindow")]

private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[System.Runtime.InteropServices.DllImport("", EntryPoint = "GetSystemMenu")]

extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert); //

取出窗⼝运⾏的菜单

[System.Runtime.InteropServices.DllImport("", EntryPoint = "RemoveMenu")]

extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //

灰掉按钮

[System.Runtime.InteropServices.DllImport(" ", EntryPoint = "SetParent")]

private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);//

设置⽗窗体

[System.Runtime.InteropServices.DllImport(" ", 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;

}

最后:在绑定之前,⽗窗体⼀定要刷出来哈