2013-10-16 169 views
-1

我遇到了我的代碼問題。我試圖在表單上拖放一張圖片,但是當我移動選定的圖片框時,當我離開組框時它會丟失。它只是消失。拖放圖片框消失

public partial class Form1 : Form 
{ 
    int x_offset = 0; // any better to do this without having a global variable? 
    int y_offset = 0; 

    PictureBox dpb = new PictureBox(); 
    public Form1() 
    { 
     InitializeComponent(); 

     this.WindowState = FormWindowState.Maximized; 
     this.AllowDrop = true; 
     this.pictureBox1.MouseDown += pictureBox1_MouseDown; 
     this.pictureBox2.MouseDown += pictureBox2_MouseDown; 
    } 

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
    { 
     PictureBox me = (PictureBox)sender; 
     x_offset = e.X; 
     y_offset = e.Y; 

    } 

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      PictureBox me = (PictureBox)sender; 
      me.Left = e.X + me.Left - x_offset; 
      me.Top = e.Y + me.Top - y_offset; 
     } 
    } 

回答

1

您的PictureBox正在被父母(即GroupBox)剪裁。您可以修復層次結構(查看 - >其他窗口 - >文檔大綱)。

此外,通常最好使用標準的拖放功能,如下所述:http://social.msdn.microsoft.com/Forums/en-US/92cad3ba-dd05-4aa9-ad44-411051407d57/drag-and-drop-picturebox-to-picturebox-in-c?forum=csharplanguage。這將處理所有拖放特殊情況。爲了更改標準遊標,將Cursor.Current設置爲由CreateCursor(myBitmap)返回的遊標。注意:在某些情況下,CreateCursor可能會失敗,因此請確保爲標準遊標提供回退。

+0

歡迎來到Stack Overflow!最好總結回答中的鏈接背後的內容,如果鏈接過時,它不會丟失。否則,你的第一個答案很棒。 – michaelb958

0

你的PictureBox有一個GroupBox作爲它的父,在winforms和許多其他的UI技術,你不能在其父控制之外呈現子控件。您可能需要使用您的代碼之前做這樣的事情:

pictureBox1.Parent = this;//set your Form as Parent of the pictureBox1 
pictureBox1.BringToFront();//Ensure your pictureBox1 is on top. 

如果你的要求是拖正放下你的pictureBox1GroupBox到另一個控制,使其爲您pictureBox1的新Parent,你可以試試下面的代碼:

Point downPoint; 
    //MouseDown event handler for your pictureBox1 
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e){ 
     downPoint = e.Location; 
     pictureBox1.Parent = this; 
     pictureBox1.BringToFront(); 
    } 
    //MouseMove event handler for your pictureBox1 
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e){ 
     if (e.Button == MouseButtons.Left) { 
      pictureBox1.Left += e.X - downPoint.X; 
      pictureBox1.Top += e.Y - downPoint.Y; 
     } 
    } 
    //MouseUp event handler for your pictureBox1 
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { 
     Control c = GetChildAtPoint(new Point(pictureBox1.Left - 1, pictureBox1.Top)); 
     if (c == null) c = this; 
     Point newLoc = c.PointToClient(pictureBox1.Parent.PointToScreen(pictureBox1.Location)); 
     pictureBox1.Parent = c; 
     pictureBox1.Location = newLoc; 
    } 
+0

thanx很多ur信息,但我需要離開選定的圖片框在其位置,只需拖放圖像的副本。所以我的問題是我怎麼能離開原來的picturebox,只拿一個它的副本,我會拖。親切的問候:) –

+0

@ToshkoKosev你的問題和你的代碼**顯示**,你想移動你的'pictureBox',你甚至沒有提到任何與你在評論中說的相關的東西。 –