Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to my event handling code for printing image

I am using the below code to print an image from my C# code. Can some body tell me how to pass the filePath as an argument when i assign my event handler ?

  public static bool PrintImage(string filePath)
    {
        PrintDocument pd = new PrintDocument();
        pd.PrintPage += new PrintPageEventHandler(printPage);
        pd.Print();
        return true;

    }
    private static void printPage(object o, PrintPageEventArgs e)
    {
        //i want to receive the file path as a paramter here.

        Image i = Image.FromFile("C:\\Zapotec.bmp");
        Point p = new Point(100, 100);
        e.Graphics.DrawImage(i, p);
    }
like image 359
Happy Avatar asked Mar 30 '12 16:03

Happy


2 Answers

The simplest way is to use a lambda expression:

PrintDocument pd = new PrintDocument();
pd.PrintPage += (sender, args) => DrawImage(filePath, args.Graphics);
pd.Print();

...

private static void DrawImage(string filePath, Graphics graphics)
{
    ...
}

Or if you've not got a lot to do, you could even inline the whole thing:

PrintDocument pd = new PrintDocument();
pd.PrintPage += (sender, args) => 
{
    Image i = Image.FromFile(filePath);
    Point p = new Point(100, 100);
    args.Graphics.DrawImage(i, p);
};
pd.Print();
like image 162
Jon Skeet Avatar answered Sep 20 '22 23:09

Jon Skeet


The easiest way to do this is use an anonymous function as the event handler. This will allow you to pass the filePath directly

public static bool PrintImage(string filePath) {
  PrintDocument pd = new PrintDocument();
  pd.PrintPage += delegate (sender, e) { printPage(filePath, e); };
  pd.Print();
  return true;
}

private static void printPage(string filePath, PrintPageEventArgs e) {
  ...
}
like image 26
JaredPar Avatar answered Sep 23 '22 23:09

JaredPar