2016-10-17 3 views
0

Мне сложно с этим приложением C#, которое я пытаюсь изменить. Код происходит от: http://www.codeproject.com/Articles/485883/Create-your-own-Snipping-ToolНевозможно сделать снимок экрана с помощью C#

Когда я запускаю код он выполняет хорошо, вы видите маркер, который должен позволить вам отметить сектор экрана, который вы хотите сделать снимок, но я не в состоянии отметьте любой сектор экрана.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO; 
using System.Drawing.Imaging; 
using System.Drawing.Drawing2D; 

namespace copy 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      //Hide the Form 
      this.Hide(); 
      //Create the Bitmap 
      Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
            Screen.PrimaryScreen.Bounds.Height); 
      //Create the Graphic Variable with screen Dimensions 
      Graphics graphics = Graphics.FromImage(printscreen as Image); 
      //Copy Image from the screen 
      graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size); 
      //Create a temporal memory stream for the image 
      using (MemoryStream s = new MemoryStream()) 
      { 
       //save graphic variable into memory 
       printscreen.Save(s, ImageFormat.Bmp); 
       pictureBox1.Size = new System.Drawing.Size(this.Width, this.Height); 
       //set the picture box with temporary stream 
       pictureBox1.Image = Image.FromStream(s); 
      } 
      //Show Form 
      this.Show(); 
      //Cross Cursor 
      Cursor = Cursors.Cross; 

     } 
      //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 = false; 



     private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
{ 
    //validate if there is an image 
    if (pictureBox1.Image == null) 
     return;    
    //validate if right-click was trigger 
    if(start) 
    { 
     //refresh picture box 
     pictureBox1.Refresh(); 
     //set corner square to mouse coordinates 
     selectWidth = e.X - selectX; 
     selectHeight = e.Y - selectY; 
     //draw dotted rectangle 
     pictureBox1.CreateGraphics().DrawRectangle(selectPen, 
        selectX, selectY, selectWidth, selectHeight); 
    } 
} 


    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
{ 
    //validate when user right-click 
    if (!start) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      //starts coordinates for rectangle 
      selectX = e.X; 
      selectY = e.Y; 
      selectPen = new Pen(Color.Red, 1); 
      selectPen.DashStyle = DashStyle.DashDotDot; 
     } 
     //refresh picture box 
     pictureBox1.Refresh(); 
     //start control variable for draw rectangle 
     start = true; 
    } 
    else 
    { 
     //validate if there is image 
     if (pictureBox1.Image == null) 
      return; 
     //same functionality when mouse is over 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      pictureBox1.Refresh(); 
      selectWidth = e.X - selectX; 
      selectHeight = e.Y - selectY; 
      pictureBox1.CreateGraphics().DrawRectangle(selectPen, selectX, 
        selectY, selectWidth, selectHeight); 

     } 
     start = false; 
     //function save image to clipboard 
     SaveToClipboard();    
    } 
} 

private void SaveToClipboard() 
{ 
    //validate if something selected 
    if (selectWidth > 0) 
    { 

     Rectangle rect = new Rectangle(selectX, selectY, selectWidth, selectHeight); 
     //create bitmap with original dimensions 
     Bitmap OriginalImage = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height); 
     //create bitmap with selected dimensions 
     Bitmap _img = new Bitmap(selectWidth, selectHeight); 
     //create graphic variable 
     Graphics g = Graphics.FromImage(_img); 
     //set graphic attributes 
     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
     g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; 
     g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; 
     g.DrawImage(OriginalImage, 0, 0, rect, GraphicsUnit.Pixel);     
     //insert image stream into clipboard 
     Clipboard.SetImage(_img); 
    } 
    //End application 
    Application.Exit(); 
} 

    } 
} 
+1

Хотя комментарий говорит правая кнопка код проверяет на левую кнопку. Это может быть проблема? – Dawnkeeper

ответ

1

Как comments on the linked page уже предполагает, что вам нужно включить обработчик событий, которые вы создали:

public Form1() 
{ 
    InitializeComponent(); 
    pictureBox1.MouseDown += new MouseEventHandler(pictureBox1_MouseDown); 
    pictureBox1.MouseMove += new MouseEventHandler(pictureBox1_MouseMove); 
} 
+0

Это решило эту проблему, спасибо! Не жалуется, что ArgumentNullException был необработанным. В: pictureBox1.CreateGraphics(). DrawRectangle (selectPen, selectX, selectY, selectWidth, selectHeight) – TheLunchingCoder

+0

Если бы ответ помог вам, было бы неплохо принять его, отметив галочку рядом с ним. ArgumentNullException, скорее всего, вызвано 'selectPen', равным нулю. См. [Здесь] (https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it?noredirect11&lq=1) – Dawnkeeper

+0

Сделал мой друг! Да, это действительно SelectPen. Я подумал: «public Pen selectPen»; достаточно, так как Pen = System.Drawing.Pen? Hmm ... – TheLunchingCoder

Смежные вопросы