本帖最后由 thelord 于 2014-8-26 15:49 编辑
@linyinlu,@aquablue
生成 __shutdown.lock__ 文件说明已经检测到 adminstrator 用户登陆,配置没问题。现在的问题是点确定后会不会有关机被阻挡的提示
代码如下,欢迎讨论:
[mw_shl_code=javascript,true]
using System;
using System.Windows.Forms;
using System.Diagnostics; //进程类
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Win32;
namespace WFBeforeShutdown
{
public partial class MainForm : Form
{
private string user2check;
private string marker = "__shutdown.lock__";
private Timer timer = new Timer();
public MainForm()
{
InitializeComponent();
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.WindowState = FormWindowState.Minimized;
// 自定义关机和logoff的事件
this.Text = "关机提示";
SystemEvents.SessionEnding += new SessionEndingEventHandler(this.SystemEvents_SessionEnding);
// 检查定时器
timer.Interval = 5000;
timer.Tick += new EventHandler(CheckAction);
timer.Enabled = true;
}
internal void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
timer.Stop();
if (e.Reason == SessionEndReasons.SystemShutdown)
{
e.Cancel = File.Exists(marker);
}
}
protected override void OnLoad(EventArgs e)
{
//this.Hide(); // 会接收不到事件?
LoadConfigFile();
base.OnLoad(e);
}
protected override void OnClosed(EventArgs e)
{
SystemEvents.SessionEnding -= new SessionEndingEventHandler(this.SystemEvents_SessionEnding);
base.OnClosed(e);
}
void CheckAction(object sender, EventArgs e)
{
try
{
if (IsInactiveUser(user2check))
{
if (!File.Exists(marker))
{
File.Create(marker);
}
}
else
{
if (File.Exists(marker))
{
File.Delete(marker);
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
}
public bool IsInactiveUser(string userName)
{
if (userName.Length == 0)
{
return false;
}
string sessionQuery;
string cmd = "qwinsta.exe";
execute(cmd, "", out sessionQuery);
string pattern = @"(?<!>console[ ]+)(" + userName + @")[ ]+[0-9]+";
bool match = Regex.IsMatch(sessionQuery, pattern);
return match;
}
public void LoadConfigFile()
{
try
{
XmlReader reader = XmlReader.Create("config.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "user")
{
user2check = reader.ReadElementString();
break;
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("Error: Load config file fail! {0}", ex.Message);
System.Environment.Exit(0);
}
}
private void execute(string cmd, string args, out string strRst)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = cmd,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
proc.WaitForExit();
strRst = proc.StandardOutput.ReadToEnd();
//MessageBox.Show(strRst);
proc.Close();
}
}
}[/mw_shl_code] |