I'm trying to make a table system for a restaurant, but things are getting difficult. What I want to do is a button that when clicked creates new buttons (at runtime/dynamic - or new restaurant tables) and then be able to move those same buttons (tables) and position them inside the Main Form.
My main form has these 4 variables:
int posMouseFormX, posMouseFormY, posMouseBotonX, posMouseBotonY,
posActBotonX, posActBotonY
I have this code that creates the button for me when I start the form:
private void crearNuevaMesa()
{
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Name = "btn" + i;
btn.Height = 40;
btn.Width = 300;
btn.BackColor = Color.Red;
btn.Location = new Point(200, 200);
btn.Text = "SOY UNA NUEVA MESA";
btn.Font = new Font("Georgia", 16);
btn.MouseMove += new MouseEventHandler(btn_MouseMove);
Controls.Add(btn);
}
}
And then I invoke this other method to set the coordinates:
private void btn_MouseMove(object sender, EventArgs e)
{
posMouseFormX = posActBotonX + e.Location.X;
posMouseFormY = posActBotonY + e.Location.Y;
if (botonPresionado == true)
{
moverBoton();
}
}
But it breaks me in the e.Location.X of the btn_MouseMove method and I don't know why !!!! Someone help me ??
Gerardo is right, the event handler signature
MouseMove
expects oneMouseEventArgs
that does have theLocation
. But you have some other problem.e.Location
in theMouseMove
button event it will return the mouse position relative to the button . This obviously isn't going to allow you to move it as you expect.I leave you a simple solution to move a button when you click on it and while you do not release the mouse button. First, I add a variable to store the button that was clicked on the form:
Then we add the necessary events in the creation of the button:
As you can see, I add the events
MouseDown
andMouseUp
. Now these would be the handlers:As you can see, when a button is pressed, its name is stored in the variable that controls which button is moving, and when it is released, that variable is deleted. Then,
MouseMove
the position of the cursor is taken usingPointToClient
to obtain said position with respect to the form, and if the button is the one we are moving, we put its position in the location of the cursor.very good,
I think you have the problem in the implementation of the btn_MouseMove method since you define the e parameter as EventArgs and you should declare it as MouseEventArgs , since otherwise it doesn't recognize the Location property .
I leave you the corrected method:
Greetings and I hope it helps you.