2015-09-08 59 views
2

我試圖在Zebra S4M打印機上打印一系列標籤,出於某種原因,頁面高度似乎卡在5釐米,我需要它是6.8釐米。Printer.GetPrinter在Delphi XE2中引發異常

我嘗試使用下面的代碼

var 
    FDevice: PChar; 
    FDriver: PChar; 
    FPort: PChar; 
    DeviceMode: THandle; 
    DevMode: PDeviceMode; 
begin 
    {to get a current printer settings} 
    Printer.GetPrinter(FDevice, FDriver, FPort, DeviceMode); 
    {lock a printer device} 
    DevMode := GlobalLock(DeviceMode); 
    DevMode^.dmPaperSize := 0; 
    DevMode^.dmPaperWidth := fBaseSettings.Width; 
    DevMode^.dmPaperLength := fBaseSettings.Height; 
    Printer.SetPrinter(FDevice, FDriver, FPort, DeviceMode); 
    {unlock a device} 
    GlobalUnlock(DeviceMode); 
end; 

其中fBaseSettings包含目標標籤尺寸(除其他事項外)設置紙張尺寸,但我不斷收到錯誤消息 Project SPXLabels.exe raised exception class $C0000005 with message 'access violation at 0x00rred82: write of address 0x59212b17

我看不到我做錯了什麼!任何幫助非常感謝。

+0

請您可以報告的真實錯誤消息。請不要僞造它!問問你自己,爲什麼你沒有檢查錯誤。你是否100%確定'GlobalLock'總是返回一個有效的指針?文檔是否可以保證?或者'DevMode'可能是'nil'?爲什麼人們不檢查錯誤?這是複製/粘貼文化,先運行,稍後再想。 –

+1

這是真正的錯誤信息!至於GlobalLock/Unlock,它不會那麼快,在Printer.GetPrinter語句失敗! – Paul

+0

'0x00rred82'看起來不正確。如果那真的是錯誤信息,那麼很奇怪的事情正在發生! –

回答

4

FDevice,FDriver和FPort是指向您傳入以獲取數據的字符串的指針。因此,您必須首先爲此留出內存。

試試這個

var 
    FDevice, FDriver, FPort: string; 
begin 
    SetLength(FDevice, 200); 
    SetLength(FDriver, 200); 
    SetLength(FPort, 200); 
    {to get a current printer settings} 
    Printer.GetPrinter(PChar(FDevice), PChar(FDriver), PChar(FPort), DeviceMode); 
+0

如果您使用的是字符串,則需要對PChar進行類型轉換......或者您可以使用' FDevice,FDriver,FPort:字符數組[0..255] ...不需要'SetLength'這種方式。 – GabrielF

+0

謝謝Larsdk,它總是很明顯,咬你在屁股! – Paul

+0

嘎,不敢相信我沒有發現!當然你需要找到一個更好的方法來計算出所需的長度。而不是靜態緩衝區更簡單? –