使用c#捕獲windows的關機事件

來源:互聯網
上載者:User
window

  在公司上班,下班時需要簽退,而我呢隔三差五就會忘那麼一次。怎麼辦呢,於是就想能不能捕獲windows的關機事件,做一個程式讓它在關機的時候提醒我一下呢。

  非常幸運很容易就找到了Microsoft.Win32命名空間下面的SystemEvents類,他有一個靜態事件SessionEnding在系統登出或者關機時發生,此事件只有在winform的程式下有效,而在控制台程式下面無效,不能激發事件;還有一點我們必須在程式推出時將加上的事件移除掉,否則就容易造成記憶體溢出。

  關鍵代碼如下:

  using System;
  using System.Collections.Generic;
  using System.Windows.Forms;
  using Microsoft.Win32;
  namespace Shutdown
  {
  static class Program
  {
  /**////
  /// 應用程式的主進入點。
  ///
  [STAThread]
  static void Main()
  {
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  FormShutdown formShutdown = new FormShutdown();
  SystemEvents.SessionEnding += new SessionEndingEventHandler(formShutdown.SystemEvents_SessionEnding);
  Application.Run(formShutdown);
  }
  }
  }Form 的代碼:
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Text;
  using System.Windows.Forms;
  using Microsoft.Win32;
  namespace Shutdown
  {
  public partial class FormShutdown : Form
  {
  const string MESSAGE_TXT = "您簽退了嗎?";
  const string MESSAGE_TITLE = "提示";
  public FormShutdown()
  {
  InitializeComponent();
  }
  internal void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  {
  DialogResult result = MessageBox.Show(MESSAGE_TXT, MESSAGE_TITLE, MessageBoxButtons.YesNo);
  e.Cancel = (result == DialogResult.No);
  }
  private void FormShutdown_Load(object sender, EventArgs e)
  {
  this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - 200, 0);
  }
  protected override void OnClosed(EventArgs e)
  {
  SystemEvents.SessionEnding -= new SessionEndingEventHandler(this.SystemEvents_SessionEnding);
  base.OnClosed(e);
  }
  }
  }

  此程式在使用c#2.0在Windows2003下測試通過。大家在使用SystemEvents.SessionEnding事件時切記要在程式退出時移除事件。

  不過有兩點遺憾之處:

  1. 使用這種方式不能捕獲休眠時的事件

  2. 這個程式佔用的記憶體太多了,只有這麼一個小功能居然佔了12M的記憶體,這都是.Net framework惹的貨;實在是不可思議。

  大家有沒有什麼好主意可以克服這兩個缺點呢?



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.