Home Backend Development C#.Net Tutorial C# captures the windows shutdown event and does some sample code to do what you want to do before the system shuts down.

C# captures the windows shutdown event and does some sample code to do what you want to do before the system shuts down.

Mar 11, 2017 pm 01:41 PM

C# Capture Windows shutdown events and do some things you want to do before the system shuts down;

Sometimes we may want to record or process some things when Windows shuts down. Here are several methods.

Method one:

        /// <summary>
        /// 窗口过程的回调函数
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                //此消息在OnFormClosing之前
                case WindowsMessage.WM_QUERYENDSESSION:
                    //MessageBox.Show("WndProc.WM_QUERYENDSESSION.我要阻止系统关闭!");
                    //this.Close();
                    //this.Dispose();
                    //Application.Exit();
                    m.Result = (IntPtr)1; //阻止Windows注销、关机或重启
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
Copy after login

Method two:

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            switch (e.CloseReason)
            {
                case CloseReason.ApplicationExitCall:
                    e.Cancel = true;
                    MessageBox.Show("拦截关闭要求事件!");
                    break;
                case CloseReason.FormOwnerClosing:
                    e.Cancel = true;
                    MessageBox.Show("拦截自身关闭事件!");
                    break;
                case CloseReason.MdiFormClosing:
                    e.Cancel = true;
                    MessageBox.Show("拦截MDI窗体关闭事件!");
                    break;
                case CloseReason.None:
                    break;
                case CloseReason.TaskManagerClosing:
                    e.Cancel = true;
                    MessageBox.Show("拦截任务管理器关闭事件!");
                    break;
                case CloseReason.UserClosing:
                    
                    //注销或关机会触发此事件;
                    //MessageBox.Show("拦截用户关闭事件!");
                    e.Cancel = false;
                    break;
                case CloseReason.WindowsShutDown:
                    e.Cancel = true;
                    MessageBox.Show("拦截关机事件!");
                    break;
                default:
                    break;
            }

            base.OnFormClosing(e);
        }
Copy after login

Method three:

//当用户试图注销或关闭系统时发生。  
            SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);

//下面是系统注销或关闭事件处理程序,  
        private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
        {
            if (MessageBox.Show(this, "是否允许系统注销!", "系统提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                e.Cancel = true;
            }
            else
            {
                e.Cancel = false;
            }
            SessionEndReasons reason = e.Reason;
            switch (reason)
            {
                case SessionEndReasons.Logoff:
                    MessageBox.Show("用户正在注销。操作系统继续运行,但启动此应用程序的用户正在注销。");
                    break;
                case SessionEndReasons.SystemShutdown:
                    MessageBox.Show("操作系统正在关闭。");
                    break;
            }
        }
        //如果把上面的事件处理程序修改成如下  
        //private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)  
        //       {  
        //          e.Cancel = true; 
        //   } 

        //那会出现什么情况,你点击开始菜单关机选择注销、关机、或重新启动将会失效,电脑不能正常关机了,进一步的话把程序做成Windows服务,晕,恶作剧? 

        //SessionEnded事件同上,事件参数类为SessionEndedEventArgs,同SessionEndingEventArgs相比少了Cancel属性,Cancel属性同一些windows下的某些事件差不多,
        比如Form.Closing事件,Control.Validating事件。

        //补充,如果需要获取应用程序需要的系统信息,可以访问System.Windows.Forms.SystemInformation类,这也是一个很有用的类,它提供了一组静态属性。
Copy after login

The above is the detailed content of C# captures the windows shutdown event and does some sample code to do what you want to do before the system shuts down.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime after writing the code How to run sublime after writing the code Apr 16, 2025 am 08:51 AM

There are six ways to run code in Sublime: through hotkeys, menus, build systems, command lines, set default build systems, and custom build commands, and run individual files/projects by right-clicking on projects/files. The build system availability depends on the installation of Sublime Text.

How to solve complex BelongsToThrough relationship problem in Laravel? Use Composer! How to solve complex BelongsToThrough relationship problem in Laravel? Use Composer! Apr 17, 2025 pm 09:54 PM

In Laravel development, dealing with complex model relationships has always been a challenge, especially when it comes to multi-level BelongsToThrough relationships. Recently, I encountered this problem in a project dealing with a multi-level model relationship, where traditional HasManyThrough relationships fail to meet the needs, resulting in data queries becoming complex and inefficient. After some exploration, I found the library staudenmeir/belongs-to-through, which easily installed and solved my troubles through Composer.

laravel installation code laravel installation code Apr 18, 2025 pm 12:30 PM

To install Laravel, follow these steps in sequence: Install Composer (for macOS/Linux and Windows) Install Laravel Installer Create a new project Start Service Access Application (URL: http://127.0.0.1:8000) Set up the database connection (if required)

git software installation git software installation Apr 17, 2025 am 11:57 AM

Installing Git software includes the following steps: Download the installation package and run the installation package to verify the installation configuration Git installation Git Bash (Windows only)

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

See all articles