Reputation: 523
So I am just experimenting with drawing images and other things, however it seems that my code only works in the load form event?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Interface_Editing_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//This works perfectly
/*Image i = Image.FromFile(@"C:\Users\Simon\Pictures\clickedbutton.jpg");
Bitmap b = (Bitmap)panel1.BackgroundImage;
using (Graphics g = Graphics.FromImage(b))
{
g.DrawImage(i, 0, 0, i.Size.Width, i.Size.Height);
}*/
}
private void panel1_Click(object sender, EventArgs e)
{
//Doesnt draw anything, but will show the message box
Image i = Image.FromFile(@"C:\Users\Simon\Pictures\clickedbutton.jpg");
Bitmap b = (Bitmap)panel1.BackgroundImage;
using (Graphics g = Graphics.FromImage(b))
{
//MessageBox.Show(" ");
g.DrawImage(i, 0, 0, i.Size.Width, i.Size.Height);
}
}
}
}
I know it is most likely something simple that I am overlooking but I would appreciate if someone could give me some insight in to whats happening. Thanks
Upvotes: 2
Views: 2843
Reputation: 942255
Windows doesn't know that you changed the image. The Image class doesn't have any events that anybody could listen to so it knows that the image was changed. It works in the Load event because the window isn't visible yet, it will get painted right after that. So you can see the changed image. It doesn't work in the Click event handler since the panel is already displayed and has no reason to repaint itself.
Simply let it know that repainting is required. Add this line of code to the bottom of the method:
panel1.Invalidate();
Upvotes: 2
Reputation: 9074
It seems that this is probl;em related to handling click event inside a panel due to different controls inside it.
Make sure that your application handles panel1_click event. (May be through debugger you will come to know it).
Application may not handle this event due to different reasons such as different controls presence on panels,etc.
You can refer Following question having the same issue as you:
Handling a click event anywhere inside a panel in C#
This working example might guid you:
private Bitmap _bmp = new Bitmap(250, 250);
public Form1()
{
InitializeComponent();
panel1.Click += new MouseEventHandler(panel1_Click);
panel1.Paint += new PaintEventHandler(panel1_Paint);
using (Graphics g = Graphics.FromImage(_bmp))
g.Clear(SystemColors.Window);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(_bmp, new Point(0, 0));
}
private void panel1_Click(object sender, MouseEventArgs e)
{
using (Graphics g = Graphics.FromImage(_bmp))
{
g.DrawString("Mouse Clicked Here!", panel1.Font, Brushes.Black, e.Location);
}
panel1.Invalidate();
}
Upvotes: 1