【问题标题】:Selection of the screen shot makes program crash C#选择屏幕截图使程序崩溃 C#
【发布时间】: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 块)。但我没有从异常中得到任何消息。
  • 这很奇怪。堆栈跟踪说什么?请分享您的堆栈跟踪

标签: c# .net wpf winforms


【解决方案1】:

您在下面提到的代码中遇到错误吗?那里似乎是你会得到一个的地方。

 Canvas.SetLeft(r, x);
        Canvas.SetTop(r, y);

如果是,那是因为 SetLeft 采用 UIElement 和一个双精度值

public static void SetLeft(
UIElement element,
double length)

而且,我猜 x 和 y 是 double 并被宣布为 public。

【讨论】:

  • 我没有收到错误消息。它只是崩溃(请参阅上面我写的评论)。 x 和 y 是 double 和 public
  • 如果它崩溃了,那是因为有一个异常。共享您的堆栈跟踪。这将有助于了解导致崩溃的原因。
  • 我看到系统参数异常错误。基本上,您传递给其中一种方法的参数不是它所期望的。查看您传递的参数。
  • 是的,我知道,但我不知道如何改正。我尝试使用 MousePosition(),但选择更不准确,我仍然无法选择其他方向。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多