views:

115

answers:

3

I want to (programmatically) print documents of various types, by asking Windows to do it (using the default associated application). How can I do this (in .NET or C++/Win32 API)?

For example, if I have MS Office and Acrobat Reader installed on the machine, PDF files should be printed by Acrobat Reader, and DOC files should be printed by MS Word. But if I don't have MS Office installed, DOC files should be printed using Wordpad, or OpenOffice.org Writer if the latter is installed, or whatever application is currently the default association for that type of files.

+5  A: 

Call ShellExecute. Use "print" for the lpOperation parameter.

Rob Kennedy
Not all files can be printed this way. The claim is that it typically works for files that have a "print" context menu in Windows Explorer. On my system, that excludes HTML and DOC - I don't have MS Office, but I do have Open Office *and* MS Word Reader. Still, it's probably as good as you can do, short of writing something that "scripts" apps by sending fake keyboard and mouse messages.
Steve314
Thank you for the information.
Hosam Aly
Steve, if Open Office and Word Reader don't register themselves as able to handle the "print" verb, then that's a shortcoming of *those* programs. We cannot be expected to write application-specific ways to print documents, especially formats as complex as HTML or Word.
Rob Kennedy
+4  A: 

Try using the ShellExecute function.

For example, in C:

 ShellExecute(my_window_handle, "print", path_to_file, NULL, NULL, SW_SHOW);
Josh Kelley
Thank you for the example.
Hosam Aly
+2  A: 

Here is some code for C#:

    public void ShellExecute(string filename, string verb)
    {
        System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo();
        si.UseShellExecute = true;
        si.FileName = filename;
        si.Verb = verb;
        System.Diagnostics.Process.Start(si);
    }
Arthur
Thank you for the C# example.
Hosam Aly