【问题标题】:Compare WinForms control positions when dragging拖动时比较 WinForms 控件位置
【发布时间】:2012-11-08 17:59:43
【问题描述】:

我有一个小程序,其中包含一个名为button1 的按钮和一个名为panel1 的面板,其颜色为绿色。到目前为止,该程序允许您在表单周围拖动button1。我正在尝试扩展这个程序,所以当button1 放在面板上时,面板的颜色会变为红色。

形式:

到目前为止的代码:

System.Drawing.Point OldPosition; 

public Form1()
{
    InitializeComponent();
}

private void button1_MouseDown(object sender, MouseEventArgs e)
{
    //Only prepare if the button click down is the left button  
    if (e.Button == MouseButtons.Left)
    {
        //Store the current mouse location  
        OldPosition = e.Location;
        //Change the mouse cursor if you want  
        button1.Cursor = Cursors.Hand;
    }  
}

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    //Only move if the left button still down  
    if (e.Button == MouseButtons.Left)
    {
        button1.Location = new Point(button1.Location.X + (e.X - OldPosition.X), button1.Location.Y + (e.Y - OldPosition.Y));
    } 
}

private void Form1_Load(object sender, EventArgs e)
{
    panel1.BackColor = Color.Green;        
}

private void panel1_MouseEnter(object sender, EventArgs e)
{
    if (button1.Location == panel1.Location)
        panel1.BackColor = Color.Red; //im not sure how to do this part
}

【问题讨论】:

    标签: c# .net winforms visual-studio-2010 drag-and-drop


    【解决方案1】:

    试试下面的代码:

    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        //Only move if the left button still down  
        if (e.Button == MouseButtons.Left)
        {
            button1.Location = new Point(button1.Location.X + (e.X - OldPosition.X), button1.Location.Y + (e.Y - OldPosition.Y));
    
            //CHECK IF NEW LOCATION IS WITHIN PANEL BOUNDS
            if (panel1.Bounds.Contains(button1.Location))
               panel1.BackColor = Color.Red;
            else
               panel1.BackColor = Color.Green;
        }
    }
    

    同样在设计器中,您可能需要“发送回”panel1 控件,否则如果按钮越过面板,按钮将不可见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 2011-06-22
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      相关资源
      最近更新 更多