因此,我正在尝试重新创建Windows附带的Snipping Tool。 但是,我设法将其从左上角绘制一个矩形,然后将光标移至右下角。
但是,如果我尝试将光标从屏幕中间移动到左上角,则它不会绘制矩形。 为什么是这样? 这是一个GIF,显示发生了什么
https://i.imgur.com/0Y7xXnS.gifv
//These variables control the mouse position
int selectX;
int selectY;
int selectWidth;
int selectHeight;
public Pen selectPen;
//This variable control when you start the right click
bool start;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Hide the Form
this.Hide();
//Create the Bitmap (This is an a black bitmap holding just the size.) (Bitmap is mutable)
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
//Create a graphics object that's ready for alteration. `printscreen` is now a graphics Object
Graphics graphics = Graphics.FromImage(printscreen);
//Alter the graphics object which again is the printscreen
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
//Create a temporary memory stream for the image
using (MemoryStream s = new MemoryStream())
{
//save graphic variable into memory
printscreen.Save(s, ImageFormat.Bmp);
//Set the size of the picturebox
pictureBox1.Size = new Size(Width, Height);
//set the value of the picturebox.Image to an Image.FromStream and load the temp stream
pictureBox1.Image = Image.FromStream(s);
}
//Show Form
this.Show();
//Cross Cursor
Cursor = Cursors.Cross;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
selectX = e.X;
selectY = e.Y;
selectPen = new Pen(Color.DimGray, 1);
selectPen.DashStyle = DashStyle.Solid;
pictureBox1.Refresh();
start = true;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (start)
{
selectWidth = e.X - selectX;
selectHeight = e.Y - selectY;
pictureBox1.Refresh();
pictureBox1.CreateGraphics().DrawRectangle(selectPen,
selectX, selectY, selectWidth, selectHeight);
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Stream sound = Resources.SnapshotSound;
SoundPlayer player = new SoundPlayer(sound);
player.PlaySync();
Application.Exit();
}
}
答案 0 :(得分:2)
所以最终得到的基本上是一个宽度和高度为负的矩形。
您可能需要使用Math.Abs来确保在差异变为负数的情况下获得正确的宽度和高度。
这样,您可能还希望根据光标相对于所选点的位置从不同位置进行绘制。像
selectWidth = e.X - selectX;
selectHeight = e.Y - selectY;
// If width is less than 0, draw from pointer, otherwise from select X
var drawFromX = selectWidth < 0 ? e.X : selectX;
// If height is less than 0, draw from pointer, otherwise from select Y
var drawFromY = selectHeight < 0 ? e.Y : selectY;
pictureBox1.Refresh();
pictureBox1.CreateGraphics().DrawRectangle(selectPen,
drawFromX,
drawFromY,
Math.Abs(selectWidth), // Make sure the rectangle width is positive
Math.Abs(selectHeight)); // Make sure the rectangle height is positive