0

I am facing a problem - I want to set a default printer. The printers that are installed are working fine, but the shared printer is not getting set as the default. Below is my code:

public class DefaultPrinter
{
    [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool SetDefaultPrinter(string Name);
}

DefaultPrinter.SetDefaultPrinter("WH");
RickL
  • 3,318
  • 10
  • 38
  • 39
Nadeem Aamir
  • 55
  • 1
  • 9
  • 1
    First, you don't even check the return value, so you have no idea if it worked or not. Second, setting the default printer works per user. Web applications though run under restricted accounts. The account may not have that permission or it the change worked but no other account will notice – Panagiotis Kanavos May 17 '17 at 07:51
  • *Why* are you trying to do this from a web app anyway? You can manage printers remotely already, eg through Powershell. You can manage printers locally or remotely with the [System.Printing](https://msdn.microsoft.com/en-us/library/system.printing(v=vs.110).aspx) classes. If you want to print to a specific printer, you'll have to post the code you use. – Panagiotis Kanavos May 17 '17 at 07:53
  • It is a web application but use locally so that's why I am using Crystal Report to print ReportDocument rd = new ReportDocument(); rd.Load(path); rd.SetDataSource(dtReport); rd.PrintToPrinter(2, true, 1, 1); rd.Refresh(); rd.Close(); – Nadeem Aamir May 17 '17 at 08:48
  • Why don't you set the PrintOptions.PrinterName then? If that doesn't work, setting the default printer won't work either – Panagiotis Kanavos May 17 '17 at 09:13
  • Anyway, from the [documentation of SetDefaultPrinter](https://msdn.microsoft.com/en-us/library/windows/desktop/dd162971(v=vs.85).aspx) `For a remote printer connection, the name format is \\server\printername`. What you passed is a local name – Panagiotis Kanavos May 17 '17 at 09:15
  • I have tried this but this is still not working. – Nadeem Aamir May 18 '17 at 10:10
  • Tried what? Post the actual code. Did you set the `PrintOptions.PrinterName` ? The original code would never work since it was using an invalid local name. What does your current code do? – Panagiotis Kanavos May 18 '17 at 10:11
  • Thanks a lot it is working now. – Nadeem Aamir May 18 '17 at 12:48
  • string printername = @"\\192.168.12.62\WH"; bool isset = DefaultPrinter.SetDefaultPrinter(printername); – Nadeem Aamir May 18 '17 at 12:48

0 Answers0