Hi all I have a simple problem in Drawing with GDI I made a button control and wote this code lines in its event handler

Graphics d = Form1.ActiveForm.CreateGraphics();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    d.DrawImage(Bitmap.FromFile(openFileDialog1.FileName), new Point(0, 0));
                    
                }
                catch
                {
                    MessageBox.Show("Sorry there is an error");
                }

            }

and the code worked but there is a simple problem in cases which the form have to be redrawn like when I minimize it so the image that I drew disappeared please I want to have a solution

Recommended Answers

All 2 Replies

The problem is simple, the solution a little more involved, but first you should understand that when the form repaints it goes through its list of componets and repaints them.
The image you lay on the form is not a part of the form's collection therefore, when the component it is sitting on top of gets painted, it gets rid of your bitmap.

The solution is to force your bitmap to be repainted anytime the form (or more specifically the container) that your bitmap will be hovering over.

To do it without killing your system, you should not read the bitmap file everytime there is a repaint. Instead, keep a variable to hold the bitmap at the form level, or build a collection of GDI objects you want to have repainted when the time comes.

In the form's Paint event, have it paint your GDI object.

Example:

BtiMap _bitmap = null;
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _bitmap = new Bitmap(openFileDialog1.FileName);
                    Invalidate(); // cause the form to repaint.
                }
                catch
                {
                    MessageBox.Show("Sorry there is an error");
                }
            }
        }


        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if(_bitmap != null)
                e.Graphics.DrawImage(_bitmap, new Point(0, 0));
        }

If this solves your issue, please mark it as solved.
//Jerry

Thank u so much ,it worked with me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.