2012-03-30 12 views
9

Estoy usando el siguiente código para imprimir una imagen desde mi código C#. ¿Puede algún organismo decirme cómo pasar el filePath como argumento cuando asigno mi controlador de eventos?Cómo pasar el parámetro a mi código de manejo de eventos para imprimir la imagen

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

Respuesta

21

La forma más sencilla es utilizar una expresión lambda:

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

... 

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

O si usted no tiene mucho que ver, incluso se podría Inline la Todo:

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

gracias. Funcionó. – Happy

2

La forma más fácil de hacerlo es utilizar una función anónima como el controlador de eventos. Esto le permitirá pasar el filePath directamente

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

Gracias Jared. Pero como ve, mi método printPage hace uso del argumento e. ¿Cómo manejar eso? – Happy

+0

@Happy se perdió completamente eso. actualicé mi respuesta para pasarla también – JaredPar

+0

¿de dónde viene 'remitente'? – Happy

Cuestiones relacionadas