使实时创建的按钮移动 [英] Make real-time created button move
本文介绍了使实时创建的按钮移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗯,我已经实现了动态创建按钮控件的功能.
Well,i have implement a function to create button control dynamically.
private void CreateDynamicButton ()
{
// Create a Button object
Button dynamicButton = new Button();
// Set Button properties
dynamicButton.Height = 40;
dynamicButton.Width = 300;
dynamicButton.BackColor = Color.Red;
dynamicButton.ForeColor = Color.Blue;
dynamicButton.Location = new Point( 20 , 150 );
dynamicButton.Text = "I am Dynamic Button";
dynamicButton.Name = "DynamicButton";
dynamicButton.Font = new Font( "Georgia" , 16 );
// Add Event handler
dynamicButton.Click += new EventHandler( DynamicButton_Click );
dynamicButton.MouseDown += new EventHandler( DynamicButton_MouseDown );
dynamicButton.MouseMove += new EventHandler( DynamicButton_MouseMove );
// Add Button to the Form. Placement of the Button
// will be based on the Location and Size of button
Controls.Add( dynamicButton );
}
现在我要移动它,我决定实现以下内容:
Now i want to move it , i decide to implement the following:
private void DynamicButton_MouseDown ( object sender , MouseEventArgs e )
{
x = e.X;
y = e.Y;
}
在这里我有一个问题,因为发件人不能使用像Button1.Left这样的发件人...
Here i had a problem as sender cant use like Button1.Left etc...
private void DynamicButton_MouseMove ( object sender , MouseEventArgs e )
{
if ( e.Button == MouseButtons.Left)
{
sender.Left = (sender.Left + e.X ) - x;
sender.Top = (sender.Top + e.Y ) - y;
}
}
我如何才能使上述代码正常工作?我需要动态创建未知数量的控件,并且需要使它们全部可移动.
How can i make the above code work?I need to dynamic create unknown numbers of control and i need to make them all moveable.
推荐答案
private void DynamicButton_MouseMove ( object sender , MouseEventArgs e )
{
Button b = sender as Button;
if (b != null)
{
if ( e.Button == MouseButtons.Left)
{
b.Left = (b.Left + e.X ) - x;
b.Top = (b.Top + e.Y ) - y;
}
}
}
您犯了一些错误,这就是为什么您无法移动创建鼠标的原因.
1)
You have did some error that''s why you are not able to move your create mouse.
1)
// when your are using Move, Down Event handler given code syntax is not valid
// Use MouseEventHandler instead EventHandler
dynamicButton.MouseDown += new EventHandler( DynamicButton_MouseDown );
dynamicButton.MouseMove += new EventHandler( DynamicButton_MouseMove )
2)
2)
// user dynamicButton.Left and dynamicButton.Top instead sender.Left or sender.Top
sender.Left = (sender.Left + e.X ) - x;
sender.Top = (sender.Top + e.Y ) - y;
您可以通过给定的方式恢复两个错误
要恢复第一个错误,请使用
you can recover your both error by given way
To Recover 1st error use
dynamicButton.MouseDown += new MouseEventHandler(dynamicButton_MouseDown);
dynamicButton.MouseClick += new MouseEventHandler(dynamicButton_MouseClick);
对于第二个错误
and for 2nd Error
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right)
{
dynamicButton.Left += e.Location.X - lp.X;
dynamicButton.Top += e.Location.Y - lp.Y;
}
:):)
:) :)
这篇关于使实时创建的按钮移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文