简体   繁体   中英

How do I add a picture to a form in runtime using a click from computer mouse in C#?

I want to be ale to add an image to a form in runtime using a click from the left mouse button. When I tried the code below, nothing happens. I don't get an error message and the picture doesn't appear where I click. I'm not sure if I'm on the right track or not. I don't know how to start if this isn't how I go about doing this operations.

private void button7_Click(object sender, EventArgs e)
{
       Floors floors = new Floors();
       floors.ShowDialog();

       if(Mouse.LeftButton == MouseButtonState.Pressed)
       {
           var picture = new PictureBox
           {
               Name = "pictureBox",
               Size = new Size(16, 16),
               Location = new Point(100, 100),
               Image = Final_Project_1_.Properties.Resources.fire_icon,
           };

           this.Controls.Add(picture);
       }
}

So I tried the following code:

 private void button1_Click(object sender, EventArgs e)
    {
        var picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(16, 16),
            Location = new Point(100, 100),
            Image = WinFormsTestApp.Properties.Resources.Copy,
            SizeMode = PictureBoxSizeMode.StretchImage
        };
        this.Controls.Add(picture);
    }

and this worked perfectly fine. If this doesn't work on your machine, your image link may be corrupted or something else is overlapping the image.

However, if this works, I guess it's currently not working because of the if statement with the mouse button. It could be, that the click event will only be raised, if the mouse button is up again so the if statement can never be true. If you want to achieve, that the image is created the moment the mouse button goes down, you should be able to do so with the MouseDown Event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM