캡처 도구로 만든 전 과정 기록 - 코드 목록
16352 단어 .Net
csc /target:winexe *.cs
최종 실행 효과 그래프는 다음과 같습니다.
XP 환경에서 테스트한 결과, 단축키: 윈+X(선택 영역 열기 또는 숨기기), 윈+C(캡처 메모리에 저장), 윈+S(캡처 파일을 저장).
다음은 코드 목록입니다.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
namespace MyQuickAndDirtyNote
{
public static class HotKeyManager
{
public static event EventHandler HotKeyPressed;
public static int RegisterHotKey(Keys key, KeyModifiers modifiers)
{
_windowReadyEvent.WaitOne();
int id = System.Threading.Interlocked.Increment(ref _id);
_wnd.Invoke(new RegisterHotKeyDelegate(RegisterHotKeyInternal), _hwnd, id, (uint)modifiers, (uint)key);
return id;
}
public static void UnregisterHotKey(int id)
{
_wnd.Invoke(new UnRegisterHotKeyDelegate(UnRegisterHotKeyInternal), _hwnd, id);
}
delegate void RegisterHotKeyDelegate(IntPtr hwnd, int id, uint modifiers, uint key);
delegate void UnRegisterHotKeyDelegate(IntPtr hwnd, int id);
private static void RegisterHotKeyInternal(IntPtr hwnd, int id, uint modifiers, uint key)
{
RegisterHotKey(hwnd, id, modifiers, key);
}
private static void UnRegisterHotKeyInternal(IntPtr hwnd, int id)
{
UnregisterHotKey(_hwnd, id);
}
private static void OnHotKeyPressed(HotKeyEventArgs e)
{
if (HotKeyManager.HotKeyPressed != null)
{
HotKeyManager.HotKeyPressed(null, e);
}
}
private static volatile MessageWindow _wnd;
private static volatile IntPtr _hwnd;
private static ManualResetEvent _windowReadyEvent = new ManualResetEvent(false);
static HotKeyManager()
{
Thread messageLoop = new Thread(delegate()
{
Application.Run(new MessageWindow());
});
messageLoop.Name = "MessageLoopThread";
messageLoop.IsBackground = true;
messageLoop.Start();
}
private class MessageWindow : Form
{
public MessageWindow()
{
_wnd = this;
_hwnd = this.Handle;
_windowReadyEvent.Set();
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY)
{
HotKeyEventArgs e = new HotKeyEventArgs(m.LParam);
HotKeyManager.OnHotKeyPressed(e);
}
base.WndProc(ref m);
}
protected override void SetVisibleCore(bool value)
{
// Ensure the window never becomes visible
base.SetVisibleCore(false);
}
private const int WM_HOTKEY = 0x312;
}
[DllImport("user32", SetLastError=true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private static int _id = 0;
}
public class HotKeyEventArgs : EventArgs
{
public readonly Keys Key;
public readonly KeyModifiers Modifiers;
public HotKeyEventArgs(Keys key, KeyModifiers modifiers)
{
this.Key = key;
this.Modifiers = modifiers;
}
public HotKeyEventArgs(IntPtr hotKeyParam)
{
uint param = (uint)hotKeyParam.ToInt64();
Key = (Keys)((param & 0xffff0000) >> 16);
Modifiers = (KeyModifiers)(param & 0x0000ffff);
}
}
[Flags]
public enum KeyModifiers
{
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
NoRepeat = 0x4000
}
}
using System;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace MyQuickAndDirtyNote
{
public class MyQuickAndDirtyNoteMain
{
[STAThread]
public static void Main(string[] args)
{
Application.Run(new MyQuickAndDirtyNoteBackService());
//Application.Run(new SolidControlOpaqueForm());
}
}
public class TransparencyKeyForm : Form
{
public TransparencyKeyForm()
{
Button testButton = new Button();
testButton.Text = "Test Button";
testButton.BackColor = Color.White;
this.Controls.Add(testButton);
this.BackColor = Color.White;
this.TransparencyKey = Color.White;
}
}
public class SolidControlOpaqueForm : Form
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// http://stackoverflow.com/questions/5201315/semi-transparent-form-but-opaque-controls-in-c-sharp
this.TransparencyKey = Color.Red;
var hb = new HatchBrush(HatchStyle.Percent10, this.TransparencyKey);
e.Graphics.FillRectangle(hb,this.DisplayRectangle);
}
}
}
using System;
using System.IO;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;
namespace MyQuickAndDirtyNote
{
public class MyQuickAndDirtyNoteBackService : Form, SystemTrayHandler
{
public MyQuickAndDirtyNoteBackService()
{
InitializeComponent();
}
private void InitializeComponent()
{
HotKeyManager.RegisterHotKey(Keys.C, KeyModifiers.Windows);
HotKeyManager.RegisterHotKey(Keys.S, KeyModifiers.Windows);
HotKeyManager.RegisterHotKey(Keys.X, KeyModifiers.Windows);
HotKeyManager.HotKeyPressed += new EventHandler(HotKeyManager_HotKeyPressed);
this.Text = "Shotit";
//this.FormBorderStyle = FormBorderStyle.None;
this.Opacity = 0.0f;
this.ShowInTaskbar = false;
CreateMaskedAreaForSelection();
SystemTrayLoader.WrapFormWithSysTray(this);
}
public void OnSystemTrayShow(object sender, EventArgs e)
{
resizableSelectionForm.Visible = true;
}
public void OnSystemTrayExit(object sender, EventArgs e)
{
resizableSelectionForm.IsCloseAllowed = true;
Application.Exit();
}
private void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
{
if (e.Key == Keys.C) {
SaveCapturedImageToClipboard();
}
if (e.Key == Keys.S) {
SaveCapturedImageToFile();
}
if (e.Key == Keys.X) {
ToggleResizableSelectionFormVisible();
}
}
private void ToggleResizableSelectionFormVisible()
{
resizableSelectionForm.Visible = !resizableSelectionForm.Visible;
}
private void SaveCapturedImageToFile()
{
Bitmap bitmap = GetDesktopImage();
// Displays a SaveFileDialog so the user can save the Image
// assigned to Button2.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//saveFileDialog1.Parent = resizableSelectionForm;
saveFileDialog1.Filter = "PNG Image|*.png|JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog(resizableSelectionForm);
// If the file name is not an empty string open it for saving.
if(saveFileDialog1.FileName != null && saveFileDialog1.FileName.Length > 0)
{
switch(saveFileDialog1.FilterIndex)
{
case 1 :
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Png);
break;
case 2 :
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Jpeg);
break;
case 3 :
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
break;
case 4 :
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Gif);
break;
}
}
}
private void SaveCapturedImageToClipboard()
{
if(InvokeRequired)
{
Invoke((MethodInvoker)delegate
{
// Clipboard.SetImage(GetDesktopImage()); // Save BMP to clipboard
//Clipboard.SetDataObject(GetPngDataObjFromBmp(), false);
Clipboard.SetImage(GetPngFromBmp(GetDesktopImage()));
});
}
else
{
// http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/f0ad430f-4c7b-4bee-928b-afd933a58769/
Clipboard.SetImage(GetPngFromBmp(GetDesktopImage()));
}
}
private Image GetPngFromBmp(Bitmap bitmap)
{
// http://stackoverflow.com/questions/3517965/convert-bmp-to-png-in-memory-for-clipboard-pasting-in-net
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png);
return Image.FromStream(stream);
}
}
private Bitmap GetDesktopImage()
{
Rectangle rect = resizableSelectionForm.Bounds;
Graphics graphics;
Bitmap bitmap;
bitmap = new Bitmap(rect.Width, rect.Height);
graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(rect.Left, rect.Top, 0, 0, new Size(rect.Width, rect.Height));
graphics.Dispose();
return bitmap;
}
private void CreateMaskedAreaForSelection()
{
if (resizableSelectionForm == null)
{
/*
maskedAreaForm = new Form();
maskedAreaForm.Text = "Test";
selectionPanel = new SizeablePanel();
maskedAreaForm.Controls.Add(selectionPanel);
maskedAreaForm.Show();
*/
resizableSelectionForm = new ResizableSelectionForm();
resizableSelectionForm.ShowInTaskbar = false;
resizableSelectionForm.Show(this);
}
else
{
resizableSelectionForm.Show();
}
}
//private Form maskedAreaForm = null;
//private Panel selectionPanel = null;
private ResizableSelectionForm resizableSelectionForm = null;
}
}
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MyQuickAndDirtyNote
{
public class SizeablePanel : Panel {
private const int cGripSize = 20;
private bool mDragging;
private Point mDragPos;
public SizeablePanel() {
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.BackColor = Color.White;
}
protected override void OnPaint(PaintEventArgs e) {
ControlPaint.DrawSizeGrip(e.Graphics, this.BackColor,
new Rectangle(this.ClientSize.Width - cGripSize, this.ClientSize.Height - cGripSize, cGripSize, cGripSize));
base.OnPaint(e);
}
private bool IsOnGrip(Point pos) {
return pos.X >= this.ClientSize.Width - cGripSize &&
pos.Y >= this.ClientSize.Height - cGripSize;
}
protected override void OnMouseDown(MouseEventArgs e) {
mDragging = IsOnGrip(e.Location);
mDragPos = e.Location;
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e) {
mDragging = false;
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e) {
if (mDragging) {
this.Size = new Size(this.Width + e.X - mDragPos.X,
this.Height + e.Y - mDragPos.Y);
mDragPos = e.Location;
}
else if (IsOnGrip(e.Location)) this.Cursor = Cursors.SizeNWSE;
else this.Cursor = Cursors.Default;
base.OnMouseMove(e);
}
}
}
using System;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace MyQuickAndDirtyNote
{
public class ResizableSelectionForm : Form {
public ResizableSelectionForm() {
this.FormBorderStyle = FormBorderStyle.None;
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.BackColor = Color.Green;
this.Opacity = 0.5;
this.TopMost = true;
this.MinimumSize = new Size(40, 30);
/*
System.Text.StringBuilder disclaimerText = new System.Text.StringBuilder();
disclaimerText.Append(@"[Ctrl + S] - Save screenshot to disk.");
disclaimerText.Append(Environment.NewLine);
disclaimerText.Append(@"[Ctrl + C] - Save screenshot to clip board.");
disclaimerText.Append(Environment.NewLine);
disclaimerText.Append(@"[Ctrl + X] - Toggle visibility of Shotit.");
disclaimerText.Append(Environment.NewLine);
disclaimerText.Append(@"You can exit with options in system tray.");
disclaimerText.Append(Environment.NewLine);
disclaimerText.Append(@"Thanks! Powered by Wooooooody!");
Label disclaimerLabel = new Label();
disclaimerLabel.Text = disclaimerText.ToString();
disclaimerLabel.Width = 400;
disclaimerLabel.Height = 300;
this.Controls.Add(disclaimerLabel);
*/
}
private const int cGrip = 14; // Grip size
//private const int cCaption = 25; // Caption bar height;
protected override void OnPaint(PaintEventArgs e) {
Rectangle rc = new Rectangle(this.ClientSize.Width - cGrip, this.ClientSize.Height - cGrip, cGrip, cGrip);
ControlPaint.DrawSizeGrip(e.Graphics, this.BackColor, rc);
//
//rc = new Rectangle(0, 0, this.ClientSize.Width, 32);
//e.Graphics.FillRectangle(Brushes.DarkBlue, rc);
}
public bool IsCloseAllowed
{
set;
get;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (!IsCloseAllowed) {
e.Cancel = true;
}
base.OnFormClosing(e);
}
protected override void WndProc(ref Message m) {
if (m.Msg == 0x84) { // Trap WM_NCHITTEST
Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
pos = this.PointToClient(pos);
/*
if (pos.Y < cCaption) {
m.Result = (IntPtr)2; // HTCAPTION
return;
}
*/
if (pos.X >= this.ClientSize.Width - cGrip && pos.Y >= this.ClientSize.Height - cGrip)
{
m.Result = (IntPtr)17; // HTBOTTOMRIGHT
return;
} else {
m.Result = (IntPtr)2; // HTCAPTION
return;
}
}
if(m.Msg == 0xA3) // WM_NCLBUTTONDBLCLK
{
m.Result = IntPtr.Zero;
return;
}
base.WndProc(ref m);
}
}
}
using System;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace MyQuickAndDirtyNote
{
public interface SystemTrayHandler
{
void OnSystemTrayShow(object sender, EventArgs e);
void OnSystemTrayExit(object sender, EventArgs e);
}
public class SystemTrayLoader
{
public static void WrapFormWithSysTray(SystemTrayHandler handler)
{
ContextMenu trayMenu = new ContextMenu();
NotifyIcon trayIcon = new NotifyIcon();
// Create a simple tray menu with only one item.
trayMenu.MenuItems.Add("Show Infected Area", handler.OnSystemTrayShow);
trayMenu.MenuItems.Add("Exit Shotit", delegate(object sender, EventArgs e)
{
trayIcon.Visible = false;
handler.OnSystemTrayExit(sender, e);
trayIcon.Dispose();
});
// Create a tray icon. In this example we use a
// standard system icon for simplicity, but you
// can of course use your own custom icon too.
trayIcon.Text = "Shotit by wooooody```";
trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);
// Add menu to tray icon and show it.
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
// Double Click
trayIcon.DoubleClick += handler.OnSystemTrayShow;
// Single Click
/*
trayIcon.MouseClick += delegate(object sender, MouseEventArgs e)
{
trayMenu.Show(trayIcon, new System.Drawing.Point(0, 0));
};
*/
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
NPOI Excel 여러 개를 하나의 Excel로 결합구현 코드 Nuget에서 NPOI 검색 및 설치 NPOI를 사용하여 참조를 추가합니다.HSSF.UserModel;...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.