![](/img/trans.png)
[英]C# - Winforms - Custom Drag Image is Not Displayed When Dragging by Touch
[英]Compare WinForms control positions when dragging
我有一個小程序,其中包含一個名為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
}
試試下面的代碼:
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
控件,否則如果按鈕越過面板,則該按鈕將不可見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.