Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Delphi: Общие вопросы > Принтер(вкл/выкл)


Автор: bip 6.4.2010, 22:21
Добрый Вечер! 

Подскажите как проверить включен принтер или нет... 

Задумка вообще такая - если включен то ничего не происходит, а если выключен, то в динамиках некий голос вещает-"ВКЛЮЧИ ПРИНТЕР ЮЗЕР!!!"

СОБСТВЕННО НЕ ЗНАЮ С ЧЕГО НАЧАТЬ И ГДЕ КОПАТЬ.

я предполагаю, что сие есть взаимодействие с драйвером принтера.... т.е. он должен возвращать состояние..

Автор: CompWorm 6.4.2010, 23:21
инициализацию принтера в блок try . если ошибка -> проиграть звук...

Автор: bip 6.4.2010, 23:42
нееее.... это банально-"инициализацию принтера в блок try . если ошибка -> проиграть звук... "

вот  содрал и собрал smile) кое-чего.... ЗАРАЗА!!!! RESULT всегда 0!(принтер HP DeskJet F2280)

Код

procedure TForm1.Button3Click(Sender: TObject);
var

   PrinterInfo : TPrinterInfo2 ;
   Result:Boolean;
   pDevice : pChar;
  pDriver : pChar;
  pPort   : pChar;
  hDMode : THandle;
  hDeviceMode:THandle;
begin
  if PrintDialog1.Execute then begin
    GetMem(pDevice, cchDeviceName);
    GetMem(pDriver, MAX_PATH);
    GetMem(pPort, MAX_PATH);
    Printer.GetPrinter(pDevice, pDriver, pPort, hDMode);
     if lStrLen(pPort) = 0 then begin
      GetProfileString('Devices', pDevice, '', pPort, MAX_PATH);
      lStrCpy(pPort,  @pPort[lStrLen(pPort)+2]);
    end;
    end;
     Result:= GetPrinterData(StrPas(pDevice),PrinterInfo) ;
     if not Result then Exit ;

   [color=red]  Result:[/color]= (PrinterInfo.Status and  (PRINTER_STATUS_ERROR
                      or PRINTER_STATUS_PAPER_PROBLEM
                      or PRINTER_STATUS_OFFLINE
                      or PRINTER_STATUS_NOT_AVAILABLE
                      or PRINTER_STATUS_NO_TONER
                      or PRINTER_STATUS_PAUSED)
                > 0);
     Memo2.Lines.Add(BoolToStr(Result));
end;

Автор: Keeper89 7.4.2010, 00:09
Код

// NOTE : include Printers and WinSpool units

procedure TForm1.Button6Click(Sender: TObject);
var
    pcbNeeded: DWord;
    prn: THandle;
    x: array[0..255] of char;
    stat: Pprinterinfo2;
begin
    getmem(stat, 1000);
    try
        StrPCopy(x, printer.printers[0]);
        if OpenPrinter(x, prn, nil) then
            if GetPrinter(
                prn,
                2,      // version of printer info data structure
                stat,      // pointer to array of bytes that receives printer info. structure
                1000,      // size, in bytes, of array of bytes
                @pcbNeeded// pointer to variable with count of bytes retrieved (or required)
                ) then
                case stat.status of
                    PRINTER_STATUS_BUSY:
                        ShowMessage('The printer is busy.');
                    PRINTER_STATUS_DOOR_OPEN:
                        ShowMessage('The printer door is open.');
                    PRINTER_STATUS_ERROR:
                        ShowMessage('The printer is in an error state.');
                    PRINTER_STATUS_INITIALIZING:
                        ShowMessage('The printer is initializing.');
                    PRINTER_STATUS_IO_ACTIVE:
                        ShowMessage('The printer is in an active input/output state.');
                    PRINTER_STATUS_MANUAL_FEED:
                        ShowMessage('The printer is in a manual feed state.');
                    PRINTER_STATUS_NO_TONER:
                        ShowMessage('The printer is out of toner.');
                    PRINTER_STATUS_NOT_AVAILABLE:
                        ShowMessage('The printer is not available for printing.');
                    PRINTER_STATUS_OFFLINE:
                        ShowMessage('The printer is offline.');
                    PRINTER_STATUS_OUT_OF_MEMORY:
                        ShowMessage('The printer has run out of memory.');
                    PRINTER_STATUS_OUTPUT_BIN_FULL:
                        ShowMessage('The printers output bin is full.');
                    PRINTER_STATUS_PAGE_PUNT:
                        ShowMessage('The printer cannot print the current page.');
                    PRINTER_STATUS_PAPER_JAM:
                        ShowMessage('Paper is jammed in the printer');
                    PRINTER_STATUS_PAPER_OUT:
                        ShowMessage('The printer is out of paper.');
                    PRINTER_STATUS_PAPER_PROBLEM:
                        ShowMessage('The printer has a paper problem.');
                    PRINTER_STATUS_PAUSED:
                        ShowMessage('The printer is paused.');
                    PRINTER_STATUS_PENDING_DELETION:
                        ShowMessage('The printer is deleting a print job.');
                    PRINTER_STATUS_PRINTING:
                        ShowMessage('The printer is printing.');
                    PRINTER_STATUS_PROCESSING:
                        ShowMessage('The printer is processing a print job.');
                    PRINTER_STATUS_TONER_LOW:
                        ShowMessage('The printer is low on toner.');
                    PRINTER_STATUS_USER_INTERVENTION:
                        ShowMessage('The user needs to do something to the printer.');
                    PRINTER_STATUS_WAITING:
                        ShowMessage('The printer is waiting.');
                    PRINTER_STATUS_WARMING_UP:
                        ShowMessage('The printer is warming up.');
                    end
                    else
                        caption := inttostr(getlasterror);
        ClosePrinter(prn);
    finally
        if stat <> nil then
            freemem(stat, 1000);
    end;
end;

http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_10038375.html

Автор: CompWorm 7.4.2010, 00:17
Keeper89, шикаррно!  smile 

Автор: bip 7.4.2010, 00:35
Keeper89, да круто, СПАСИБО!!! буду разбираться...

Автор: bip 7.4.2010, 19:32
Нашёл за что можно зацепиться.... Вот это поле меняется - ((TPrinterInfo2A(Buffer^).Attributes) при включении и отключении принтера.  2624/3648 - это под вистой(соответственно вкл/выкл)
2632/3656 -под Хр.... А статус всегда 0 - вроде, как оказалось так и должно быть smile...

если есть ещё варианты, напишите плиз...
Код

if ((TPrinterInfo2A(Buffer^).Attributes)=2624  )then begin MG/C?essageDlg('Включен!!!',mtWarning, mbOKCancel,MB_OK);
 PlaySound('SND1', 0, SND_RESOURCE or SND_ASYNC);
  end;
  if ((TPrinterInfo2A(Buffer^).Attributes)=3648 ) then begin MessageDlg('Отключен!!!',mtError, mbOKCancel,MB_OK);
 PlaySound('SND2', 0, SND_RESOURCE or SND_ASYNC);
    end;
    if ((TPrinterInfo2A(Buffer^).Attributes)=2632) then begin MessageDlg('Включен!!!',mtWarning, mbOKCancel,MB_OK);
 PlaySound('SND1', 0, SND_RESOURCE or SND_ASYNC);
  end;
     if ((TPrinterInfo2A(Buffer^).Attributes)=3656)  then begin MessageDlg('Отключен!!!',mtError, mbOKCancel,MB_OK);
 PlaySound('SND2', 0, SND_RESOURCE or SND_ASYNC);
 end;



Автор: Keeper89 7.4.2010, 22:43
А зачем смотреть Attributes если нам нужен Status?

Автор: bip 8.4.2010, 00:14
Цитата(Keeper89 @ 7.4.2010,  22:43)
А зачем смотреть Attributes если нам нужен Status?

Как я уже писал - status всегда в нуле и не меняется при смене состояния принтера, в отличии от atributes.
Вот я и решил привязать к atributes проверку собственно... проверил на хр, висте и семёрке - работает, но.....


1. КТО ДАСТ ОТВЕТ ПОЧЕМУ НЕ МЕНЯЕТСЯ STATUS?
2. Есть ли другие варианты проверки?
3. Где про это толком написано?
 п.с. естественно принтер не лпт, а усб smile

Автор: Keeper89 8.4.2010, 12:38
Вот http://support.microsoft.com/kb/q160129/ все написано ;)

Автор: bip 8.4.2010, 20:43
так... ещё раз спасибо Keeper89!
тема закрыта.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)