Setting the default Printer for windows using c#
Solution 1
Try SetDefaultPrinter
Windows API function
using System.Runtime.InteropServices;
...
[DllImport("winspool.drv",
CharSet = CharSet.Auto,
SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean SetDefaultPrinter(String name);
...
SetDefaultPrinter(PrinterName);
see
http://msdn.microsoft.com/en-us/library/windows/desktop/dd162971(v=vs.85).aspx http://www.pinvoke.net/default.aspx/winspool/SetDefaultPrinter.html?diff=y
Solution 2
Right click on the project in Solution Explorer, choose Properties. Select the Settings tab, add PrinterName setting.
In the code use the setting:
string PrinterName
{
get { return (string)Properties.Settings.Default["PrinterName"]; }
set
{
Properties.Settings.Default["PrinterName"] = value;
Properties.Settings.Default.Save();
}
}
private void print_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
if (PrinterName != "")
pd.PrinterSettings.PrinterName = PrinterName;
if (pd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Print
PrinterName = pd.PrinterSettings.PrinterName;
}
}
Nosheen Javed
Junior C# Developer At Kophes https://www.kophes.com
Updated on June 04, 2022Comments
-
Nosheen Javed about 2 years
I want to set a default printer for windows/ system setting on a button click. I want to click on a button and want that a windows dialogue should appear asking user to set a default printer. Right now I am using the PrintDialog for this but it changes the printer every time I click on the button. I want to set the selected printer as a default one that should remain the same even if I close the application as well.
private void PrintSettingsBtn_Click(object sender, EventArgs e) { PrintDialog PrintDialog = new PrintDialog(); PrintDialog.ShowDialog(); PrinterName = PrintDialog.PrinterSettings.PrinterName; }
-
Nosheen Javed over 10 yearsIts giving me the exception The settings property 'PrinterName' was not found.
-
Nosheen Javed over 10 yearsWhen I Right click on the Solution in SolutionExplorer its not giving me any kind of Settings. But when I click on one of my Project's folder then its opening the settings
-
Nosheen Javed over 10 yearsCan you please tell me which library I have to include?
-
Dmitry Bychenko over 10 yearsYou don't have to lnclude any library: DllImport as well as MarshaAs are in mscorlib; winspool.drv is a part of Windows so you've had already.
-
AlexS over 10 yearsYou need the Project settings (WindowsFormsApplication1 or something like this), not the Solution settings. Take a look social.msdn.microsoft.com/Forums/getfile/193805