Отправляет email-рассылки с помощью сервиса Sendsay
  Все выпуски  

Часто задаваемые вопросы по программированию в Delphi 30.09.02


Информационный Канал Subscribe.Ru


Частые вопросы по программированию в Delphi

 ВОПРОСЫ:

1. Как перетаскивать форму за ее поле ?

procedure TForm1.MouseDown(Sender: TObject; Button: TMouseButton;
                           Shift: TShiftState; X, Y: Integer);
const
  SC_DragMove = $F012; { a magic number }
begin
  ReleaseCapture;
  perform(WM_SysCommand, SC_DragMove, 0);
end;

2. Копирование файлов ?

Копирование методом TurboPascal


Type
  TCallBack=procedure (Position,Size:Longint); {Для индикации процесса копирования}

procedure FastFileCopy(Const InfileName, OutFileName: String; CallBack: TCallBack);
Const BufSize = 3*4*4096; { 48Kbytes дает прекрасный результат }
Type
  PBuffer = ^TBuffer;
  TBuffer = array [1..BufSize] of Byte;
var
  Size : integer;
  Buffer : PBuffer;
  infile, outfile : File;
  SizeDone,SizeFile: Longint;
begin
  if (InFileName <> OutFileName) then
  begin
   buffer := Nil;
   AssignFile(infile, InFileName);
   System.Reset(infile, 1);
   try
     SizeFile := FileSize(infile);
     AssignFile(outfile, OutFileName);
     System.Rewrite(outfile, 1);
     try
       SizeDone := 0; New(Buffer);
       repeat
         BlockRead(infile, Buffer^, BufSize, Size);
         Inc(SizeDone, Size);
         CallBack(SizeDone, SizeFile);
         BlockWrite(outfile,Buffer^, Size)
       until Size < BufSize;
       FileSetDate(TFileRec(outfile).Handle,
         FileGetDate(TFileRec(infile).Handle));
     finally
      if Buffer <> Nil then Dispose(Buffer);
      System.close(outfile)
     end;
   finally
     System.close(infile);
   end;
 end else
  Raise EInOutError.Create('File cannot be copied into itself');
end;

Копирование методом потока


Procedure FileCopy(Const SourceFileName, TargetFileName: String);
Var
  S,T : TFileStream;
Begin
 S := TFileStream.Create(sourcefilename, fmOpenRead );
 try
  T := TFileStream.Create(targetfilename, fmOpenWrite or fmCreate);
  try
    T.CopyFrom(S, S.Size ) ;
    FileSetDate(T.Handle, FileGetDate(S.Handle));
  finally
   T.Free;
  end;
 finally
  S.Free;
 end;
end;

Копирование методом LZExpand

uses LZExpand;
procedure CopyFile(FromFileName, ToFileName : string);
var
  FromFile, ToFile: File;
begin
  AssignFile(FromFile, FromFileName);
  AssignFile(ToFile, ToFileName);
  Reset(FromFile);
  try
   Rewrite(ToFile);
   try
    if LZCopy(TFileRec(FromFile).Handle, TFileRec(ToFile).Handle)<0 then
     raise Exception.Create('Error using LZCopy')
   finally
    CloseFile(ToFile);
   end;
  finally
   CloseFile(FromFile);
  end;
end;

Копирование методами Windows

uses ShellApi; // !!! важно

function WindowsCopyFile(FromFile, ToDir : string) : boolean;
var F : TShFileOpStruct;
begin
  F.Wnd := 0; F.wFunc := FO_COPY;
  FromFile:=FromFile+#0; F.pFrom:=pchar(FromFile);
  ToDir:=ToDir+#0; F.pTo:=pchar(ToDir);
  F.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION;
  result:=ShFileOperation(F) = 0;
end;
 // пример копирования
procedure TForm1.Button1Click(Sender: TObject);
begin
 if not WindowsCopyFile('C:\UTIL\ARJ.EXE', GetCurrentDir) then
   ShowMessage('Copy Failed');
end;

3. Как узнать число кадров AVI файла, и выяснить как долго будет проигрывться этот файл ?

procedure TForm1.Button1Click(Sender: TObject);
begin
MediaPlayer1.TimeFormat := tfFrames;
ShowMessage('Number of frames = ' + IntToStr(MediaPlayer1.Length));
MediaPlayer1.TimeFormat := tfMilliseconds;
ShowMessage('Number of milliseconds = ' + IntToStr(MediaPlayer1.Length));
end;

4. Как осуществить быстрый поиск в Listbox ?

Можно так:
ListBox1.Perform(LB_SELECTSTRING,-1,longint(Pchar(Edit1.text)));

5. Как определить состояние модема ?

procedure TForm1.Button1Click(Sender: TObject);
var CommPort : string;
    hCommFile : THandle;
    ModemStat : DWord;
begin
 CommPort := 'COM2';
 {Open the comm port}
 hCommFile := CreateFile(PChar(CommPort), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
 if hCommFile = INVALID_HANDLE_VALUE
  then
   begin
    ShowMessage('Unable to open '+ CommPort);
    exit;
   end;
 {Get the Modem Status}
 if GetCommModemStatus(hCommFile, ModemStat) <> false
  then
   begin
    if ModemStat and MS_CTS_ON <> 0
     then ShowMessage('The CTS (clear-to-send) is on.');
    if ModemStat and MS_DSR_O! N <> 0
     then showMessage('The DSR (data-set-ready) is on.');
    if ModemStat and MS_RING_ON <> 0
     then ShowMessage('The ring indicator is on.');
    if ModemStat and MS_RLSD_ON <> 0
     then ShowMessage('The RLSD (receive-line-signal-detect) is on.');
   end;
 {Close the comm port}
 CloseHandle(hCommFile);
end;

 КРАТКОЕ СОДЕРЖАНИЕ СТАТЕЙ:

Команды RunDll32 

...Команды rundll32 можно использовать из приложения Дельфи с помощью следующей конструкции: например, выход из Windows без любых сообщений и вопросов - ShellExecute (Application.Handle, Pchar('Open'), Pchar(' C:WindowsRundll32.exe '), Pchar('krnl386.exe, exitkernel'), Pchar('C:Windows'), SW_SHOWNORMAL)...

 КОМПОНЕНТЫ:

NWLib v5.0 

...Эта библиотека предоставит вам лучшую RAD технологию, возможность «перенести и бросить» визуальные компоненты, а также сетевую мощь более чем 200 функций. Это лучшая библиотека для создания сетевых приложений. Библиотека поставляется вместе со всеми исходниками. Кроме того эта новая версия поддерживает Delphi 5...

Вопросы по программированию в Delphi - www.mydelphi.hoha.ru

С уважением, Сергей
mydelphi@hoha.ru
Здесь может быть и Ваш баннер тоже

http://subscribe.ru/
E-mail: ask@subscribe.ru
Отписаться
Убрать рекламу

В избранное