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



我正在使用下面的代码打印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);
    }

最简单的方法是使用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();

最简单的方法是使用匿名函数作为事件处理程序。这将允许您直接通过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) {
  ...
}

相关内容

  • 没有找到相关文章

最新更新