2009-06-02 86 views

回答

2

要顯示PrinterSettings對話框使用

[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, 
    CallingConvention = CallingConvention.StdCall)] 
static extern int DocumentProperties(
    IntPtr hwnd, 
    IntPtr hPrinter, 
    [MarshalAs(UnmanagedType.LPWStr)] string pDeviceName, 
    IntPtr pDevModeOutput, 
    ref IntPtr pDevModeInput, 
    int fMode); 

[DllImport("kernel32.dll")] 
static extern IntPtr GlobalLock(IntPtr hMem); 

[DllImport("kernel32.dll")] 
static extern bool GlobalUnlock(IntPtr hMem); 

[DllImport("kernel32.dll")] 
static extern bool GlobalFree(IntPtr hMem); 

private void OpenPrinterPropertiesDialog(PrinterSettings printerSettings) { 
    var handle = (new System.Windows.Interop.WindowInteropHelper(this)).Handle; 
    var hDevMode = printerSettings.GetHdevmode(printerSettings.DefaultPageSettings); 
    var pDevMode = GlobalLock(hDevMode); 
    var sizeNeeded = DocumentProperties(handle, IntPtr.Zero, printerSettings.PrinterName, pDevMode, ref pDevMode, 0); 
    var devModeData = Marshal.AllocHGlobal(sizeNeeded); 
    DocumentProperties(handle, IntPtr.Zero, printerSettings.PrinterName, devModeData, ref pDevMode, 14); 
    GlobalUnlock(hDevMode); 
    printerSettings.SetHdevmode(devModeData); 
    printerSettings.DefaultPageSettings.SetHdevmode(devModeData); 
    GlobalFree(hDevMode); 
    Marshal.FreeHGlobal(devModeData); 
} 

// Show this dialog. 
var printQueue = LocalPrintServer.GetDefaultPrintQueue(); 
var settings = new PrinterSettings { PrinterName = printQueue.FullName }; 
OpenPrinterPropertiesDialog(settings); 
3

因爲我沒有足夠的守信編輯接受的答案,我會發布,而不是第二個答案...

接受的答案工作正常顯示本地打印機對話框並從該對話框中獲取更改。但是,它不會正確地在對話框中設置屬性。

爲了將設置推送到本地對話框,必須按如下方式更改DocumentProperties的簽名。新簽名不使用ref參數作爲輸入。

Here is the page這表明了這個小而顯着的差異。

[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, 
    CallingConvention = CallingConvention.StdCall)] 
static extern int DocumentProperties(
    IntPtr hwnd, 
    IntPtr hPrinter, 
    [MarshalAs(UnmanagedType.LPWStr)] string pDeviceName, 
    IntPtr pDevModeOutput, 
    IntPtr pDevModeInput, //removed ref 
    int fMode); 
相關問題