Add event for PictureBox mouse down

社会主义新天地 提交于 2019-12-21 22:02:25

问题


I want to make this event to work:

private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    //code
}

I know I have to add an event for this to work but I wasn't able to find the syntax anywhere. How can I add this event?


回答1:


You have to assign event handler to the event, usually in the form's constructor:

class MyForm 
{ 
    PictureBox pictureBox1;

    public MyForm()
    {
        ...
        InitializeComponent(); 
        ...
        pictureBox1.MouseDown += new MouseEventHandler(pictureBox1_MouseDown);
        ... 
    }
}

If you added your control through Form Designer in Visual Studio, it will automatically generate InitializeComponent() method which creates controls (calls their constructors) so make sure you're accessing controls after the call to InitializeComponent().

You can also assign event handler to the event through Form Designer: select control, right click it, select Properties, click on flash icon (Events), find desired event (MouseDown) and double click it - event handler method will be assigned to that event (you can check the code in InitializeComponent()). Now you just have to write the code in the body of the event handler.



来源:https://stackoverflow.com/questions/14580560/add-event-for-picturebox-mouse-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!