2015-04-17 62 views
0
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace UTUResultWithCoordinates 
{ 
    public partial class GetCoordinates : Form 
    { 
     private string sem; 
     private string branch; 
     private int mouseisdown = 0; 
     private int recx = 0; 
     private int recy = 0; 
     private int mousemovingwhilepressed = 0; 

     public GetCoordinates() 
     { 
      InitializeComponent(); 

     } 

     public GetCoordinates(string p, string p_2) 
     { 
      // TODO: Complete member initialization 
      InitializeComponent(); 
      branch = p; 
      sem = p_2; 
      pictureBox1.Controls.Add(pictureBox2); 
      pictureBox2.Location = new Point(0, 0); 
      pictureBox2.BackColor = Color.Transparent; 
      pictureBox2.Width = 1191; 
      pictureBox2.Height = 842; 

     } 

     private void GetCoordinates_Load(object sender, EventArgs e) 
     { 

      pictureBox1.ImageLocation =  @"D:\DotNet\UTUResultWithCoordinates\UTUResultWithCoordinates\bin\Debug\ComputerScience6.jpg"; 
     } 






     private void pictureBox2_Paint(object sender, PaintEventArgs e) 
     { 
      if (mouseisdown == 1 && mousemovingwhilepressed==1) 
      { 
      System.Drawing.Graphics graphicsObj; 
      graphicsObj = this.CreateGraphics(); 
      Pen myPen = new Pen(System.Drawing.Color.Blue, 100); 
      Rectangle myRectangle = new Rectangle(recx, recy, 20, 20); 
      e.Graphics.DrawRectangle(myPen, myRectangle); 
     } 

    } 

    private void pictureBox2_MouseDown(object sender, MouseEventArgs e) 
    { 
     mouseisdown = 1; 
     recx = e.X; 
     recy = e.Y; 
     pictureBox2.CreateGraphics(); 

    } 

    private void pictureBox2_MouseMove(object sender, MouseEventArgs e) 
    { 
     label1.Text = e.X + "," + e.Y; 
     mousemovingwhilepressed = 1; 
     recx = e.X; 
     recy = e.Y; 
     pictureBox2.CreateGraphics(); 
    } 

    private void pictureBox2_MouseUp(object sender, MouseEventArgs e) 
    { 
     mousemovingwhilepressed = 0; 
     mouseisdown = 0; 
     pictureBox2.CreateGraphics(); 
    } 
} 

}爲什麼我不能用pictureBox中的這段代碼繪製一個矩形?

我已經創建在其上顯示圖像的pictureBox1。然後我在裏面創建了一個pictureBox2,這樣我就可以通過拖動鼠標在該圖像上畫一個矩形。但點擊鼠標時沒有任何事情發生。什麼是錯誤?

+0

該代碼甚至不應該編譯... –

回答

2

調用CreateGraphics不會觸發PictureBox的繪製。

使用無效導致重繪。

對於一個完整的例子參見:How to select an area on a PictureBox.Image with mouse in C#

旁註:

  • 比構造之外的方法調用InitializeControl是不是一個好主意。
  • 當你需要一個布爾值時使用布爾值而不是整數。
  • 實現IDisposable的對象(例如Pen)應儘可能少地創建並在不再需要/使用時處理。
相關問題