If args.Length > 0 AndAlso args(0).ToLower() = "-c" Then
'通过命令行 xxxx.exe -c 参数启动,Console
'注意:不用 Main(string[] args)、System.Environment.GetCommandLineArgs(); 也可以取得命令行参数在任何地方
'启动
NativeMethods.AllocConsole()
Console.WriteLine("控制台以启动")
End If
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
Finally
'关闭
NativeMethods.FreeConsole()
End Try
Public Shared Sub inputHandler(ByVal consoleEvent As ConsoleCtrl.ConsoleEvent)
MsgBox(consoleEvent.ToString)
If consoleEvent = ConsoleCtrl.ConsoleEvent.CtrlC Then
Console.WriteLine("Stopping due to user input")
' Cleanup code here.
System.Environment.[Exit](-1)
End If
End Sub
Dim cc As ConsoleCtrl
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ConsoleCtrl.AllocConsole()
cc = New ConsoleCtrl
AddHandler cc.ControlEvent, AddressOf inputHandler
End Sub
End Class
''' <summary>
''' Class to catch console control events (ie CTRL-C) in C#.
''' Calls SetConsoleCtrlHandler() in Win32 API
''' </summary>
Public Class ConsoleCtrl
Implements IDisposable
''' <summary>
''' The event that occurred.
''' </summary>
Public Enum ConsoleEvent
CtrlC = 0
CtrlBreak = 1
CtrlClose = 2
CtrlLogoff = 5
CtrlShutdown = 6
End Enum
''' <summary>
''' Handler to be called when a console event occurs.
''' </summary>
Public Delegate Sub ControlEventHandler(ByVal consoleEvent As ConsoleEvent)
''' <summary>
''' Event fired when a console event occurs
''' </summary>
Public Event ControlEvent As ControlEventHandler
Private eventHandler As ControlEventHandler
Public Sub New()
' save this to a private var so the GC doesn't collect it...
eventHandler = New ControlEventHandler(AddressOf Handler)
SetConsoleCtrlHandler(eventHandler, True)
End Sub
Protected Overrides Sub Finalize()
Try
Dispose(False)
Finally
MyBase.Finalize()
End Try
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Private Sub Dispose(ByVal disposing As Boolean)
If eventHandler IsNot Nothing Then
SetConsoleCtrlHandler(eventHandler, False)
eventHandler = Nothing
End If
End Sub
Private Sub Handler(ByVal consoleEvent As ConsoleEvent)
RaiseEvent ControlEvent(consoleEvent)
End Sub
<DllImport("kernel32.dll")> _
Public Shared Function SetConsoleCtrlHandler(ByVal e As ControlEventHandler, ByVal add As Boolean) As Boolean
End Function
<DllImport("kernel32")> _
Public Shared Function AllocConsole() As Boolean
End Function
<DllImport("kernel32")> _
Public Shared Function FreeConsole() As Boolean
End Function
End Class