Hi,
I just had to do exactly this in C# today ;). In my code i had to print a bundle of documents in all kind of formats, I've added below the relevant bits.
I could not find anyway to do this without changing the default printer. I just made sure I changes the default for as little time as necessary.
Here is my code:
I have derived the WebBrowser control and added my own Print method.
public partial class MyWebBrowser : WebBrowser
public void Print(PrinterSettings ps)
{
PrinterSettings p = new PrinterSettings();
string oldPrinter = p.PrinterName;
SetAsDefaultPrinter(ps.PrinterName);
this.axIWebBrowser2.ExecWB(OLECMDID.OLECMDID_PRINT,
OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,
null, IntPtr.Zero);
SetAsDefaultPrinter(oldPrinter);
}
static int SetAsDefaultPrinter(string printerDevice)
{
int ret = 0;
string path = "win32_printer.DeviceId='" + printerDevice + "'";
using (ManagementObject printer = new ManagementObject(path))
{
ManagementBaseObject outParams =
printer.InvokeMethod("SetDefaultPrinter",null, null);
ret = (int)(uint)outParams.Properties["ReturnValue"].Value;
}
return ret;
}
and I call it this way:
PrinterSettings ps = new PrinterSettings();
PrintDialog p = new PrintDialog();
if (p.ShowDialog() == DialogResult.OK)
{
ps = p.PrinterSettings;
MyWebBrowser browser = new MyWebBrowser();
browser.Url = new Uri(document);
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Print(ps);
}
hope it helps.
Valery.