CatchForm,背景設為螢幕截圖(Graphics.CopyFromScreen)。CatchForm 上以滑鼠拖曳繪製矩形選取區域。CatchForm → 顯示原視窗並貼上圖片。直接在視窗上繪製矩形會產生大量殘影。解法:
originBmp。originBmp → 在副本上繪製目前矩形 → 將副本整張繪製到視窗 → 釋放副本。Point _downPt; bool _selecting = false, _finished = false;
Rectangle _selectRect; Bitmap _originBmp;
void CatchForm_Load() {
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
_originBmp = new Bitmap(this.BackgroundImage);
}
void CatchForm_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left && !_selecting) {
_selecting = true; _downPt = new Point(e.X, e.Y);
}
}
void CatchForm_MouseMove(object sender, MouseEventArgs e) {
if (!_selecting) return;
Bitmap temp = (Bitmap)_originBmp.Clone();
Point pt = new Point(Math.Min(_downPt.X, e.X), Math.Min(_downPt.Y, e.Y));
int w = Math.Abs(e.X - _downPt.X), h = Math.Abs(e.Y - _downPt.Y);
_selectRect = new Rectangle(pt, new Size(w, h));
using (Graphics g = Graphics.FromImage(temp))
g.DrawRectangle(Pens.Blue, _selectRect);
using (Graphics g = this.CreateGraphics())
g.DrawImage(temp, Point.Empty);
temp.Dispose();
}
void CatchForm_MouseUp(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left && _selecting) { _selecting = false; _finished = true; }
}
void CatchForm_MouseDoubleClick(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left && _finished && _selectRect.Contains(e.Location)) {
Bitmap crop = new Bitmap(_selectRect.Width, _selectRect.Height);
using (Graphics g = Graphics.FromImage(crop))
g.DrawImage(_originBmp, new Rectangle(0,0,_selectRect.Width,_selectRect.Height), _selectRect, GraphicsUnit.Pixel);
Clipboard.SetImage(crop);
crop.Dispose();
this.DialogResult = DialogResult.OK; this.Close();
}
}
void CatchForm_MouseClick(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Right) { this.DialogResult = DialogResult.Cancel; this.Close(); }
}
void btnCapture_Click() {
if (chkHideCurrent.Checked) { this.Hide(); Thread.Sleep(50); }
using (CatchForm cf = new CatchForm()) {
Bitmap screen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
using (Graphics g = Graphics.FromImage(screen))
g.CopyFromScreen(Point.Empty, Point.Empty, screen.Size);
cf.BackgroundImage = screen;
if (cf.ShowDialog() == DialogResult.OK) {
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap))
richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
Clipboard.Clear();
}
}
this.Show();
}