I have an application what writes commands to some specialized printers directly on LPT1 port. The code looks like this:
AssignFile(t, 'LPT1');
Rewrite(t);
Write(t,#27 + '@'); // initialize
Sleep(50); // avoid buffer fill
Write(t,#27#32 + Chr(0)); // set default font
...
The problem is that when the printer is not connected to the port, the first Write instruction doesn't do anything, it just hangs up and the entire thread is locked.
Is there a way to define a timeout for these instructions, or can you recommend another library that could do this job? It would be great if it had a Write function similar to the one in Delphi, because the amount of code using this approach is very large, and it would be very hard to change all of it.
Move your printing code to a separate thread. The built-in text-file functions don't have any timeout mechanism, but you can tell the OS to cancel any pending I/O operations whenever you decide that too much time has passed.
I'd start with CancelSynchronousIo
, which cancels all I/O on a given thread. It should allow you to keep all your existing Write
calls. Be prepared to handle when they fail upon being cancelled.
That function requires Windows Vista or higher, which shouldn't be a problem nowadays, but won't work if you still need support for Windows XP. In that case, you'll need to use CreateFile
to open the port for overlapped I/O. Then you can use CancelIo
or CancelIoEx
. You'll need to replace all your Write
calls since the built-in Delphi functions don't support overlapped operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With