2012-03-30 26 views
9

Tôi đang sử dụng mã bên dưới để in hình ảnh từ mã C# của tôi. Có thể một số cơ thể cho tôi biết làm thế nào để vượt qua filePath như một đối số khi tôi gán xử lý sự kiện của tôi?Cách chuyển thông số vào mã xử lý sự kiện của tôi để in hình ảnh

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

Trả lời

21

Cách đơn giản nhất là sử dụng một biểu thức lambda:

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

... 

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

Hoặc nếu bạn đã không có nhiều việc phải làm, bạn có thể thậm chí inline toàn bộ điều:

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

cảm ơn. Nó đã làm việc. – Happy

2

Cách dễ nhất để thực hiện việc này là sử dụng hàm ẩn danh làm trình xử lý sự kiện. Điều này sẽ cho phép bạn để vượt qua filePath trực tiếp

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

Cảm ơn Jared. Nhưng như bạn thấy, phương thức printPage của tôi sử dụng đối số e. Làm thế nào để xử lý điều đó? – Happy

+0

@Happy hoàn toàn bỏ lỡ điều đó. cập nhật câu trả lời của tôi để vượt qua nó cũng như – JaredPar

+0

nơi 'người gửi' đến từ đâu? – Happy

Các vấn đề liên quan