程式啟動時最小化至系統匣,按下熱鍵啟動截圖。於 MainForm 中實現:
NotifyIcon 控制項,設定 Icon 與 Visible = true。Settings 中新增熱鍵相關設定(如 HotKey、isAltHotKey)。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, menuItem2;
private ScreenBody body;
public MainForm()
{
InitializeComponent();
this.components = new Container();
contextMenu1 = new ContextMenu();
menuItem2 = new MenuItem { Index = 0, Text = "S&et HotKey" };
menuItem1 = new MenuItem { Index = 1, Text = "E&xit" };
menuItem1.Click += menuItem1_Click;
menuItem2.Click += menuItem2_Click;
contextMenu1.MenuItems.AddRange(new[] { menuItem2, menuItem1 });
notifyIcon1.ContextMenu = 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();
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(Point.Empty, Point.Empty, Screen.AllScreens[0].Bounds.Size);
body = new ScreenBody { BackgroundImage = img };
body.Show();
}
private void ProcessHotkey(Message m)
{
IntPtr id = m.WParam;
if (id.ToString() == "100") CutScreen();
}
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);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
HotKey.UnregisterHotKey(Handle, 100);
}
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY) ProcessHotkey(m);
base.WndProc(ref m);
}
private void menuItem1_Click(object sender, EventArgs e)
{
HotKey.UnregisterHotKey(Handle, 100);
notifyIcon1.Visible = false;
this.Close();
}
private void menuItem2_Click(object sender, EventArgs e)
{
new SetHotKey().ShowDialog();
}
}
}