You are on page 1of 3

'通常使用するプリンタに設定

#Region "SetDefaultPrinter"

Public Function SetDefaultPrinter1(ByVal printerName As String, ByVal


sectionName As String, ByRef strDefaultPrinter As String) As Boolean
Dim strPrinterName As String
Dim WshNetwork As Object =
Microsoft.VisualBasic.CreateObject("WScript.Network")
Dim pd As New Drawing.Printing.PrintDocument

'現在の通常使うプリンタ名取得
strDefaultPrinter = pd.PrinterSettings.PrinterName
If printerName = strDefaultPrinter Then Return True

For Each strPrinterName In pd.PrinterSettings.InstalledPrinters


If strPrinterName = printerName Then
'通常使うプリンタに設定
WshNetwork.SetDefaultPrinter(printerName)

'通常使うプリンタに設定に成功
If pd.PrinterSettings.IsValid Then
strDefaultPrinter = printerName
Return True
End If
End If
Next

'通常使うプリンタに設定に失敗
Dim strLogMsg As String =
String.Format(_DataAccess.GetMessage("HAID000037"), printerName)
_Logger.Write(Common.LogLevels.Warn, sectionName, strLogMsg)

'メッセージ表示

Dim msg As String 'メッセージ領域

Dim title As String 'メッセージタイトル領

Dim style As MsgBoxStyle 'メッセージスタイル領

Dim response As MsgBoxResult 'メッセージ

'メッセージスタイル設定
style = MsgBoxStyle.DefaultButton1 Or _
MsgBoxStyle.Exclamation Or MsgBoxStyle.YesNo
title = "通常使うプリンタに設定"
msg = String.Format(_DataAccess.GetMessage("HAID000038"), printerName,
strDefaultPrinter)
msg = msg.Replace("\n", vbNewLine)
response = MsgBox(msg, style, title)
If response = MsgBoxResult.Yes Then
'現在の通常使うプリンタで印刷
Return True
End If

'印刷続行しない
Return False
End Function

Public Function SetDefaultPrinter2(ByVal printerName As String, ByVal


sectionName As String, ByRef strDefaultPrinter As String) As Boolean
Dim strLogMsg As String =
String.Format(_DataAccess.GetMessage("HAID000037"), printerName)
Dim mos As New ManagementObjectSearcher("Select * from Win32_Printer")
Dim moc As ManagementObjectCollection = mos.Get()
Dim bFound As Boolean = False

'プリンタを列挙する
Dim mo As New ManagementObject
For Each mo In moc
If CBool(mo("Default")) Then
strDefaultPrinter = CStr(mo("Name"))
End If
If CStr(mo("Name")) = printerName Then
'名前を見つけたとき、デフォルトプリンタに設定する
Dim mbo As ManagementBaseObject =
mo.InvokeMethod("SetDefaultPrinter", Nothing, Nothing)
Dim ret As Long = Convert.ToInt64(mbo("returnValue"))
If ret = 0 Then
'通常使用するプリンタ設定に成功、処理終了
strDefaultPrinter = printerName
bFound = True
End If
End If
Next mo
Dim msg As String 'メッセージ領域

Dim title As String 'メッセージタイトル領

Dim style As MsgBoxStyle 'メッセージスタイル領

Dim response As MsgBoxResult 'メッセージ

'メッセージ表示
If Not bFound Then
'通常使用するプリンタ設定に失敗
_Logger.Write(Common.LogLevels.Warn, sectionName, strLogMsg)
'メッセージスタイル設定
style = MsgBoxStyle.DefaultButton1 Or _
MsgBoxStyle.Exclamation Or MsgBoxStyle.YesNo
title = "通常使うプリンタに設定"
msg = String.Format(_DataAccess.GetMessage("HAID000038"), printerName,
strDefaultPrinter)
msg = msg.Replace("\n", vbNewLine)

response = MsgBox(msg, style, title)


If response = MsgBoxResult.Yes Then
Return True
End If
Return False
End If
Return True
End Function
#End Region

You might also like