有没有办法在C#来检测Windows关机/注销和取消操作(询问用户后)没有办法、操作、用户、Windows

2023-09-02 21:31:19 作者:有一种爱叫我一直在

一些解释:对于一个项目我工作我必须写在后台运行的程序,检测文件更改,并上载修改过的文件到一个Web服务,使之提供给其他人。相当简单的同步,如果不是因为如此,当用户修改一个大文件,并决定关闭其计算机的编辑后的权利。

Some explanation : for a project I'm working on I have to write a program that is running in the background, detects changes to files, and uploads the modified files to a web service to make it available to others. Quite simple synchronization if it were not for the case when a user modifies a big file and decides to shutdown its computer right after the edit.

我可以取消上传,等待下一次重新启动做上传,但我能想象用户在第二天早上下载的网页文件到另一台计算机和不理解为什么从昨天晚上AREN他的变化牛逼那里。

I could cancel the upload and wait for the next reboot to do the upload, but I can imagine the user downloading the file from the web to another computer the next morning and don't understanding why his changes from last night aren't there.

所以我的想法是,以检测当用户注销或重新启动Windows,然后如果我在上传的中间,只要求用户我们仍在进行同步,您只需更改文件foo.txt的是。你确定要重新启动吗?直到您重新启动计算机,你的改变将不会提供给其他人!。如果用户说没有,我需要取消重新启动/关闭登录电子

So my idea was to detect when the users logs off or reboots Windows, and if I'm in the middle of an upload, just asking the user "We're still synchronizing file Foo.txt that you just changed. Are you sure you want to reboot ? You're changes won't be available to others until you restart your computer !". If the users says no, I'd need to cancel the reboot/loging off

这可能吗?

推荐答案

有一个静态类名为 SystemEvents 暴露这种行为:

There is a static class called SystemEvents that exposes this behaviour:

http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx

但是,它不能某些行动加以区分,并不会暂停的操作系统进程超时后卫。我用过一次,但默认超时中配置的注册表是有点短,所以可能需要增加。

However, it cannot differentiate between certain actions and doesn't pause the OS process time-out guard. I used it once, but the default time-out as configured in the registry is a little short so will likely need increasing.

要削减长话短说,这一切都感觉有点hackish的。

To cut a long story short, it all felt a little hackish.