Rya*_* S. 8 c# sharpdevelop .net-4.0
我正在编写一个C#应用程序,需要在控制台关闭时上传文件(通过X按钮,或者计算机关闭).
我怎么能这样做?
AppDomain.CurrentDomain.ProcessExit += new EventHandler (OnExit);
Run Code Online (Sandbox Code Playgroud)
仅在我exit向控制台发出命令时运行,而不是在我按下红色关闭按钮时运行.
请仅在解决方案通过X按钮关闭控制台时运行解决方案,并且当计算机关闭时(通常通过Windows,我知道如果电源被拉到xD则不能).
Mar*_*aiß 10
您必须调用WIN32 API,为此,请在这里查看这篇文章 http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/707e9ae1-a53f-4918-8ac4- 62a1eddb3c4a /
我从那里复制了相关的代码:
class Program
{
private static bool isclosing = false;
static void Main(string[] args)
{
SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
Console.WriteLine("CTRL+C,CTRL+BREAK or suppress the application to exit");
while (!isclosing) ;
}
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
// Put your own handler here
switch (ctrlType)
{
case CtrlTypes.CTRL_CLOSE_EVENT:
isclosing = true;
Console.WriteLine("Program being closed!");
break;
}
return true;
}
#region unmanaged
// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
它完全符合您的需求.
问候,