As a rule of thumb, you call it from the handler of the event
Paint
of some control, or its overridden virtual protected method
OnPaint
. In this case, you pass a event arguments parameter passed to you as the event handler or
OnPaint
method parameters. Better yes, change the parameter type of
DrawImagePoint
and add a file name parameter, don't hard-code it:
void DrawImagePoint(System.Drawing.Graphics graphics, string fileName)
{
Image newImage = Image.FromFile(fileName);
Point ulCorner = new Point(100, 100);
graphics.DrawImage(newImage, ulCorner);
}
virtual protected OnPaint(PaintEventArgs e) {
string fileName =
if (System.IO.File.Exists(fileName)
DrawImagePoint(e.Graphics, fileName);
}
Also, consider loading image not from a file (you will have to find it, process cases when it is not found, etc.), but from .resx resources. Have a file in your source code. Create a resource, use "Add existing file" (better don't embed the file in the resource using Visual Studio; this way is bad for maintenance. The resource node will make an auto-generated C# file for you (as a child node of the resource file node). When this is done, look inside this file: you will find a static class with a static property with a name close to the name of your file. For example, if your file was .PNG, the type if this variable will be
Bitmap
. Use it immediately; you won't need to use resource stream, create or read a bitmap — nothing like that; instead you can use the static property as the file is already read.
—SA