如何将参数传递给我的事件处理代码以打印图像

时间:2012-03-30 16:06:56

标签: c# printing event-handling

我使用以下代码从我的C#代码中打印图像。当我指定我的事件处理程序时,某些正文可以告诉我如何将filePath作为参数传递吗?

  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);
    }

2 个答案:

答案 0 :(得分:21)

最简单的方法是使用lambda表达式:

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

...

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

或者,如果你没有很多工作要做,你甚至可以内联整个事情:

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();

答案 1 :(得分:2)

最简单的方法是使用匿名函数作为事件处理程序。这样您就可以直接传递filePath

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) {
  ...
}