I can't be here all the time, unfortunately, I do have other things to do...
I don't quite see why you are having a problem here, so I have started a new solution to explain it step by step.
What I did:
Create a new project from scratch: Winforms, C#.
Add a class to the project: MyPanel, which is derived from Panel.
The sole purpose of the class is to allow me to prevent the panel background from being erased.
public class MyPanel : Panel
{
protected override void OnPaintBackground(PaintEventArgs e)
{
}
}
Build the project, and MyPanel should appear my magic in your toolbox.
Add MyPanel to your Form in the designer, and also add your two buttons. Call the MyPanel "myPanel" and the buttons "butLoadBackImage" and "butLoadFrontImage".
Add a line to the
using
statements at the top of the file:
using System.Drawing.Drawing2D;
Add three class level variables to the form:
private Image myBackImage;
private Image myFrontImage;
private Region myClearBit = new Region();
Your form should handle the Load event (double click the form background in the desginer):
private void Form1_Load(object sender, EventArgs e)
{
myBackImage = new Bitmap(10, 10);
myFrontImage = new Bitmap(10,10);
myClearBit.MakeEmpty();
}
Double click each button in the designer, to add a handler:
private void butLoadBackImage_Click(object sender, EventArgs e)
{
myBackImage = Image.FromFile(@"D:\Temp\MyPic.jpg");
myClearBit.MakeEmpty();
myPanel.Invalidate();
}
private void butLoadFrontImage_Click(object sender, EventArgs e)
{
myFrontImage = Image.FromFile(@"D:\Temp\MyOtherPic.jpg");
myClearBit.MakeEmpty();
myPanel.Invalidate();
}
Go back to the designer. single click the panel, and look at the Properties Pane. Click the Events button (it looks like a lightning bolt). Double click on the MouseDown event to add a handler, then do the same for the MouseMove and Paint events.
private void myPanel_MouseDown(object sender, MouseEventArgs e)
{
myClearBit.Union(new Rectangle(e.X - 5, e.Y - 5, 10, 10));
myPanel.Invalidate();
}
private void myPanel_MouseMove(object sender, MouseEventArgs e)
{
myClearBit.Union(new Rectangle(e.X - 5, e.Y - 5, 10, 10));
myPanel.Invalidate();
}
private void myPanel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.ExcludeClip(myClearBit);
e.Graphics.DrawImage(myFrontImage, new Point(0, 0));
e.Graphics.SetClip(myClearBit, CombineMode.Replace);
e.Graphics.DrawImage(myBackImage, new Point(0, 0));
}
Run the application.
You should find it works for you as well.