4,使用熱鍵及托盤區圖標
為了使程序更方便使用,程序啟動的時候最下化到托盤區,在按下程序熱鍵時會啟動截圖功能。這些功能在程序的主窗口MainForm類中實現。
為了在托盤區顯示圖標,為MainForm添加一個NotifyIcon控件,為其指定一Icon圖標,並設定visable屬性為true
為了實現可以更改熱鍵,首先在項目屬性的Setting中添加如下圖成員:
MainForm.cs文件代碼如下:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using ScreenCutter.PropertIEs;
namespace ScreenCutter
{
public enum KeyModifIErs //組合鍵枚舉
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
public partial class MainForm : Form
{
private ContextMenu contextMenu1;
private MenuItem menuItem1;
private MenuItem menuItem2;
private ScreenBody body;
public MainForm()
{
InitializeComponent();
this.components = new Container();
this.contextMenu1 = new ContextMenu();
this.menuItem2 = new MenuItem();
this.menuItem1 = new MenuItem();
this.contextMenu1.MenuItems.AddRange(
new MenuItem[] { this.menuItem1,this.menuItem2 });
this.menuItem1.Index = 1;
this.menuItem1.Text = "E&xit";
this.menuItem1.Click += new EventHandler(this.menuItem1_Click);
this.menuItem2.Index = 0;
this.menuItem2.Text = "S&et HotKey";
this.menuItem2.Click += new EventHandler(this.menuItem2_Click);
notifyIcon1.ContextMenu = this.contextMenu1;
notifyIcon1.Text = "Screen Cutter";
notifyIcon1.Visible = true;
body = null;
}
private void MainForm_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowstate.Minimized)
{
this.Hide();
this.notifyIcon1.Visible = true;
}
}
private void CutScreen()
{
Image img = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height);
Graphics g = Graphics.FromImage(img);
g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size);
body = new ScreenBody();
body.BackgroundImage = img;
body.Show();
}
private void ProcessHotkey(Message m) //按下設定的鍵時調用該函數
{
IntPtr id = m.WParam; //IntPtr用於表示指針或句柄的平台特定類型
string sid = id.ToString();
switch (sid)
{
case "100":
CutScreen();
break;
default:
break;
}
}
private void MainForm_Load(object sender, EventArgs e)
{
uint ctrHotKey = (uint)KeyModifIErs.Control;
if (Settings.Default.isAltHotKey)
{
ctrHotKey =(uint)(KeyModifiers.Alt | KeyModifIErs.Control);
}
HotKey.RegisterHotKey(Handle, 100, ctrHotKey, Settings.Default.HotKey); //這時熱鍵為Alt+CTRL+A
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
HotKey.UnregisterHotKey(Handle, 100); //卸載第1個快捷鍵
}
//重寫WndProc()方法,通過監視系統消息,來調用過程
protected override void WndProc(ref Message m)//監視Windows消息
{
const int WM_HOTKEY = 0x0312; //如果m.Msg的值為0x0312那麼表示用戶按下了熱鍵
switch (m.Msg)
{
case WM_HOTKEY:
ProcessHotkey(m); //按下熱鍵時調用ProcessHotkey()函數
break;
}
base.WndProc(ref m); //將系統消息傳遞自父類的WndProc
}
private void menuItem1_Click(object Sender, EventArgs e)
{
HotKey.UnregisterHotKey(Handle, 100); //卸載第1個快捷鍵
this.notifyIcon1.Visible = false;
this.Close();
}
private void menuItem2_Click(object Sender, EventArgs e)
{
SetHotKey setHotKey = new SetHotKey();
setHotKey.ShowDialog();
}
}
}