@@ -4,41 +4,91 @@ namespace BatchPrinting
44{
55 public partial class Form1 : Form
66 {
7-
8- private System . Windows . Forms . Timer batchTimer ;
97 private string pdfFolder = @"../../../Data" ;
10- private int intervalMinutes = 2 ;
8+ PdfViewerControl viewer ;
9+
10+ private string [ ] files = [ ] ;
11+ private int currentIndex = 0 ;
12+
1113 public Form1 ( )
1214 {
1315 InitializeComponent ( ) ;
14- InitializeBatchProcess ( ) ;
15- }
1616
17- private void InitializeBatchProcess ( )
17+ viewer = new PdfViewerControl ( ) ;
18+ viewer . EndPrint += Viewer_EndPrint ;
19+
20+ this . Shown += Form1_Shown ;
21+ }
22+ private void Form1_Shown ( object ? sender , EventArgs e )
1823 {
19- batchTimer = new System . Windows . Forms . Timer ( ) ;
20- batchTimer . Interval = intervalMinutes * 60 * 1000 ; // Convert minutes to ms
21- batchTimer . Tick += BatchTimer_Tick ;
22- batchTimer . Start ( ) ;
24+ LoadFilesAndStartPrinting ( ) ;
2325 }
24- private async void BatchTimer_Tick ( object sender , EventArgs e )
26+ private void LoadFilesAndStartPrinting ( )
2527 {
26- batchTimer . Stop ( ) ;
27- await Task . Run ( ( ) => PrintAllPdfFiles ( ) ) ;
28- batchTimer . Start ( ) ;
28+ try
29+ {
30+ if ( ! Directory . Exists ( pdfFolder ) )
31+ {
32+ return ;
33+ }
34+
35+ files = Directory
36+ . GetFiles ( pdfFolder , "*.pdf" )
37+ . ToArray ( ) ;
38+
39+ if ( files . Length == 0 )
40+ {
41+ return ;
42+ }
43+
44+ currentIndex = 0 ;
45+ PrintCurrentFile ( ) ;
46+ }
47+ catch ( Exception ex )
48+ {
49+ MessageBox . Show (
50+ $ "Failed to load PDF files.\n \n { ex . Message } ",
51+ "Error" ,
52+ MessageBoxButtons . OK ,
53+ MessageBoxIcon . Error ) ;
54+ }
2955 }
30- private void PrintAllPdfFiles ( )
56+
57+ private void PrintCurrentFile ( )
3158 {
32- if ( ! Directory . Exists ( pdfFolder ) )
59+ if ( currentIndex >= files . Length )
60+ {
61+ MessageBox . Show (
62+ "Batch printing completed." ,
63+ "Completed" ,
64+ MessageBoxButtons . OK ,
65+ MessageBoxIcon . Information ) ;
66+
3367 return ;
68+ }
3469
35- var files = Directory . GetFiles ( pdfFolder , "*.pdf" ) ;
36- PdfViewerControl viewer = new PdfViewerControl ( ) ;
37- foreach ( string file in files )
70+ try
3871 {
72+ string file = files [ currentIndex ] ;
73+
3974 viewer . Load ( file ) ;
4075 viewer . Print ( false ) ;
4176 }
77+ catch ( Exception ex )
78+ {
79+ // Log error and continue with next file
80+ MessageBox . Show (
81+ $ "Failed to print:\n { files [ currentIndex ] } \n \n { ex . Message } ",
82+ "Print Error" ,
83+ MessageBoxButtons . OK ,
84+ MessageBoxIcon . Warning ) ;
85+ }
86+ }
87+
88+ private void Viewer_EndPrint ( object ? sender , EndPrintEventArgs e )
89+ {
90+ currentIndex ++ ;
91+ BeginInvoke ( PrintCurrentFile ) ;
4292 }
4393 }
4494}
0 commit comments