using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WinFormLock
{
public partial class FormLock : Form
{
#region LockWorkStation
[DllImport("user32.dll", EntryPoint = "LockWorkStation")]
private static extern bool LockWorkStation();
#endregion
private DateTimePicker timePicker;
private Button okButton;
private Timer timerInfo;
public FormLock()
{
#region
InitializeComponent();
timePicker = new DateTimePicker();
timePicker.Dock = DockStyle.Top;
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH 时 mm 分";
timePicker.ShowUpDown = true;
this.Controls.Add(timePicker);
okButton = new Button();
okButton.Dock = DockStyle.Bottom;
okButton.Text = "确定(&O)";
okButton.Click += new EventHandler(okButton_Click);
this.Controls.Add(okButton);
timerInfo = new Timer();
timerInfo.Interval = 1000;
timerInfo.Enabled = true;
timerInfo.Tick += new EventHandler(timerInfo_Tick);
this.TopMost = true; // 前端显示。
this.ShowInTaskbar = false; // 禁止在 Windows 任务栏中显示窗体。
this.HelpButton = true;
this.MaximizeBox = this.MinimizeBox = false;
this.AutoScaleMode = AutoScaleMode.Font;
this.Font = new Font(Font.Name, 16F);
int sw = TextRenderer.MeasureText(timePicker.CustomFormat, this.Font).Width + 16;
int sh = timePicker.Height + okButton.Height;
this.ClientSize = new Size(sw, sh);
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.SizeGripStyle = SizeGripStyle.Hide;
this.StartPosition = FormStartPosition.CenterScreen;
#endregion
}
#region TimeSpan
private void timerInfo_Tick(object sender, EventArgs e)
{
this.Text = string.Format("{0:HH:mm:ss}", DateTime.Now);
if (okButton.Enabled)
return;
TimeSpan ts = timePicker.Value.Subtract(DateTime.Now);
switch ((int)Math.Ceiling(ts.TotalSeconds))
{
case 30:
Console.Beep(); // 通过控制台扬声器播放提示音。
this.WindowState = FormWindowState.Normal;
this.Activate();
break;
case 0:
LockWorkStation(); // 锁机。
timerInfo.Dispose();
Application.Exit();
break;
}
}
#endregion
#region OKButton
private void okButton_Click(object sender, EventArgs e)
{
timePicker.Text = string.Format("{0:HH:mm:00}", timePicker.Value);
okButton.Enabled = false;
this.WindowState = FormWindowState.Minimized;
}
#endregion
#region HelpButton
protected override void OnHelpButtonClicked(System.ComponentModel.CancelEventArgs e)
{
base.OnHelpButtonClicked(e);
e.Cancel = true;
switch (this.WindowState)
{
case FormWindowState.Minimized:
this.WindowState = FormWindowState.Normal;
break;
case FormWindowState.Normal:
this.WindowState = FormWindowState.Minimized;
break;
}
}
#endregion
}
}