选择屏幕截图使程序崩溃C#

时间:2015-09-17 14:35:40

标签: c# .net wpf winforms

我有一个程序,它拍摄所选区域的屏幕截图(我用鼠标选择)并将其保存到剪贴板。问题是它只有在我从上到下进行选择时才有效。如果我尝试在任何其他方向(从下到上,从右到左,从左到右)进行选择,程序将崩溃。这是MouseMove的代码:

 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);

enter image description here

1 个答案:

答案 0 :(得分:0)

你得到的错误是下面提到的代码吗?这似乎是你得到一个的地方。

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

如果是,那就是因为SetLeft采用UIElement和双值

public static void SetLeft(
UIElement element,
double length)

而且,我猜测x和y是双重的并且被宣布为公开。