It is necessary that when clicking in the workspace of the application (Form1) a button is created in the current coordinates of the mouse pointer. Is it possible to do this and how to do it?

It is necessary to add an event programmatically, after pressing a certain button!

    1 answer 1

    Subscribe to the Form.MouseClick event or override the OnMouseClick method.
    Example override:

     public class MyForm : Form { protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); Button btn = new Button { Location = e.Location, // e.Location - координаты мыши Visible = true, Text = "Some text" }; Controls.Add(btn); } } 

    Either event. Subscribe to it anywhere in the form:

     MouseClick += MyForm_MouseClick; 

    Handler itself:

     private void MyForm_MouseClick(object sender, MouseEventArgs e) { Button btn = new Button { Location = e.Location, // e.Location - координаты мыши Visible = true, Text = "Some text" }; Controls.Add(btn); } 
    • It's awesome it works, even to understand how, but I already, thank you very much! - Vyacheslav
    • How to save the buttons on the form, so that when you next start it, they remain in the same state? - Vyacheslav
    • @Vyacheslav This is a completely different question. I would recommend when creating the buttons to save to the file (or in Settings ) all pairs of coordinates, so that when you next start the program, read them and recreate the buttons in these places. - Dmitry D.
    • @Vyacheslav quite pulls on an independent question, though I'm afraid there may be too many options for solutions and, most likely, not a single “true” right =) - rdorn