我的代码有问题。我试图在我的表单上拖放一张图片,但当我移动所选的图片框时,当我离开组框时它会丢失。它就消失了。
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;
}
}
答案 0 :(得分:1)
您的PictureBoxes正被父级(GroupBox)裁剪。您可以修复层次结构(View-> Other windows-> Document Outline)。
此外,通常最好使用标准的拖放功能,如下所述: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可能会失败,因此请确保提供标准游标的后备。
答案 1 :(得分:0)
您的PictureBox
作为其父级GroupBox
,在winforms
以及许多其他UI技术中,您无法在其父控件之外渲染子控件。在使用代码之前,您可能希望执行类似的操作:
pictureBox1.Parent = this;//set your Form as Parent of the pictureBox1
pictureBox1.BringToFront();//Ensure your pictureBox1 is on top.
如果您的要求是将pictureBox1
从GroupBox
拖放到另一个控件上,使其成为Parent
的新pictureBox1
,则可以尝试以下代码:
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;
}