gpt4 book ai didi

c# - 拖动时比较 WinForms 控件位置

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:36 26 4
gpt4 key购买 nike

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

形式:

enter image description here

到目前为止的代码:

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
}

最佳答案

试试下面的代码:

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 控件“发送到后面”,否则如果按钮越过面板,该按钮将不可见。

关于c# - 拖动时比较 WinForms 控件位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13294955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com