【发布时间】:2015-09-17 14:35:40
【问题描述】:
我有一个程序可以截取所选区域的屏幕截图(我用鼠标选择)并将其保存到剪贴板。问题是它只有在我从上到下进行选择时才有效。如果我尝试在任何其他方向(从下到上、从右到左、从左到右)进行选择,程序就会崩溃。这是鼠标移动的代码:
public void Window_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (this.isMouseDown)
{
double curx = e.GetPosition(null).X;
double cury = e.GetPosition(null).Y;
System.Windows.Shapes.Rectangle r = new System.Windows.Shapes.Rectangle();
SolidColorBrush brush = new SolidColorBrush(Colors.White);
r.Stroke = brush;
r.Fill = brush;
r.StrokeThickness = 1;
r.Width = Math.Abs(curx - x);
r.Height = Math.Abs(cury - y);
selekt.Children.Clear();
selekt.Children.Add(r);
Canvas.SetLeft(r, x);
Canvas.SetTop(r, y);
if (e.LeftButton == MouseButtonState.Released)
{
selekt.Children.Clear();
width = e.GetPosition(null).X - x;
height = e.GetPosition(null).Y - y;
this.CaptureScreen(x, y, width, height);
this.x = this.y = 0;
this.isMouseDown = false;
this.Close();
}
}
}
这是为 CaptureScreen 准备的:
public void CaptureScreen(double x, double y, double width, double height)
{
int ix, iy, iw, ih;
ix = Convert.ToInt32(x);
iy = Convert.ToInt32(y);
iw = Convert.ToInt32(width);
ih = Convert.ToInt32(height);
Bitmap slika = new Bitmap(iw, ih, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(slika);
g.CopyFromScreen(ix, iy, 0, 0,new System.Drawing.Size(iw, ih),CopyPixelOperation.SourceCopy);
System.Windows.Forms.Clipboard.SetImage(slika);
【问题讨论】:
-
抛出什么错误?什么线路?
-
TL;DR - 我没有看到可以标准化坐标的调用(如
Math.Min)...确保您发布了完整的示例(并包含确切的错误)。 -
异常消息和堆栈跟踪是什么?应用程序在哪里失败?
-
它没有显示错误,只是崩溃了。如果我写了 catch 块(Exception ex),它不会崩溃,但它会挂起一段时间,然后“解冻”但没有做出选择,我必须做一个新的。有趣的是,如果我在任何其他方向上进行选择,它仍然会从上到下绘制选择(矩形),然后挂起并继续(如果我添加 catch 块)。但我没有从异常中得到任何消息。
-
这很奇怪。堆栈跟踪说什么?请分享您的堆栈跟踪