我有一个Windows窗体应用程序,我想按需打开一个控制台(当我按下按钮时),我可以使用标准的控制台类进行交互.有没有办法做到这一点?
是的,你需要与Win32互操作才能做到这一点.
public class ConsoleHelper
{
public static int Create()
{
if (AllocConsole())
return 0;
else
return Marshal.GetLastWin32Error();
}
public static int Destroy()
{
if (FreeConsole())
return 0;
else
return Marshal.GetLastWin32Error();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeConsole();
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以调用Create()来创建与您的应用关联的控制台窗口.