Demand
WinForm program output type is a Windows program (not a command-line program)
At run time want to enter some information compile development debugging, how to realize this function
Answer:
AllocConsole,freeconsole These two APIs can call and close the command line at any time.
Code Demo:
API section
UsingSystem;
UsingSystem.Collections.Generic;
UsingSystem.Linq;
UsingSystem.Text;
UsingSystem.Runtime.InteropServices;
NamespaceWindowsFormsApplication1
{
PublicPartialClassNativeMethods {
///<summary>
///Start the console
///</summary>
///<returns></returns>
[DllImport ("Kernel32.dll")]
PublicStaticexternboolAllocConsole ();
///<summary>
///Release the console
///</summary>
<returns></returns>
[DllImport ("Kernel32.dll")]
public static extern bool freeconsole ();
}
}
Implementation of startup parameters
UsingSystem;
UsingSystem.Collections.Generic;
UsingSystem.Linq;
UsingSystem.Windows.Forms;
UsingSystem.Runtime.InteropServices;
UsingSystem.Diagnostics;
NamespaceWindowsFormsApplication1
{
StaticClassProgram
{
///<summary>
///The main entry point for the application.
///</summary>
[STAThread]
StaticvoidMain (String[] args)
{
Try
{
If(args. Length>0&&args[0]. ToLower ()=="-C")
{//Start with the command line xxxx.exe-c parameter, Console
//Note: Do not use Main (string[] args), System.Environment.GetCommandLineArgs (); You can also get command line arguments anywhere
//Start
Nativemethods.allocconsole ();
Console.WriteLine ("Console to start");
}
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (False);
Application.Run (New Form1 ());
}
finally
{
// off (if it is not written in this position, it is OK)
Nativemethods.freeconsole ();
}
}
}
}
Program implementation
UsingSystem;
UsingSystem.Collections.Generic;
UsingSystem.ComponentModel;
UsingSystem.Data;
UsingSystem.Drawing;
UsingSystem.Linq;
UsingSystem.Text;
UsingSystem.Windows.Forms;
NamespaceWindowsFormsApplication1
{
PublicPartialClassForm1:form
{
PublicForm1 ()
{
InitializeComponent ();
}
PrivatevoidBtnopenconsole_click (Objectsender, EventArgs e)
{
//Turn on the console
Nativemethods.allocconsole ();
}
PrivatevoidBtncloseconsole_click (Objectsender, EventArgs e)
{
//Close the console
Nativemethods.freeconsole ();
}
private void< Span style= "color: #000000;" > btnout_click (object sender, eventargs e)
{
// analog output
Console.WriteLine (TextBox1.Text);
}
}
}