Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
KANSoftWare

Копирование большого файла в буфер обмена

Delphi , ОС и Железо , Буфер обмена

Копирование большого файла в буфер обмена

Автор: Peter Below

У женщины-программистки есть три пути сделать себе карьеру: два спереди и один сзади!

Вот общее решение, которое будет работать, даже если у вас размер файла превышает 64Кб:


function _hread(FileHandle: word; BufPtr: pointer;
  ByteCount: longint): longint; far;
  external 'KERNEL' index 349;

procedure CopyFileToClipboard(const fname: string);
var
  hmem, hFile: THandle;
  size: LongInt;
  p: Pointer;
begin
  hFile := FileOpen(fname, fmOpenRead);
  try
    size := FileSeek(hFile, 0, 2);
    FileSeek(hfile, 0, 0);
    if size > 0 then
    begin
      hmem := GlobalAlloc(GHND, size);
      if hMem <> 0 then
      begin
        p := GlobalLock(hMem);
        if p <> nil then
        begin
          _hread(hFile, p, size);
          GlobalUnlock(hMem);
          Clipboard.SetAsHandle(CF_TEXT, hMem);
        end
        else
          GlobalFree(hMem);
      end;
    end;
  finally
    FileClose(hFile);
  end;
end;

procedure TForm1.SpeedButton2Click(Sender: TObject);
var
  fname: string[128];
begin
  if OpenDialog1.Execute then
  begin
    fname := OpenDialog1.Filename;
    CopyFileToClipboard(fname);
  end;
end;

Программа на Delphi, которая копирует содержимое файла в буфер обмена в виде plain текста. Ограничение размера файла преодолевается с помощью функции _hread, которая читает данные из файлового хендла в буфер.

Разбивка кода:

  1. function _hread(FileHandle: word; BufPtr: pointer; ByteCount: longint): longint; far; external 'KERNEL' index 349;
    • Это внешняя функция из ядра Windows, которая читает данные из файлового хендла в буфер.
  2. procedure CopyFileToClipboard(const fname: string);
    • Эта процедура копирует содержимое файла в буфер обмена в виде plain текста.
  3. var hmem, hFile: THandle; size: LongInt; p: Pointer;
    • Declare variables:
      • hmem: handle to the memory allocated for file data
      • hFile: handle to the file being read
      • size: size of the file in bytes
      • p: pointer to the buffer where file data will be stored
  4. hFile := FileOpen(fname, fmOpenRead);
    • Открывает указанный файл для чтения.
  5. try ... finally block:
    • This block ensures that the file is closed even if an exception occurs during execution.
  6. size := FileSeek(hFile, 0, 2);
    • Gets the size of the file in bytes.
  7. FileSeek(hfile, 0, 0);
    • Moves the file pointer to the beginning of the file.
  8. if size > 0 then ...
    • If the file has data (i.e., its size is greater than zero), proceed with copying the data to the clipboard.
  9. hmem := GlobalAlloc(GHND, size);
    • Allocates a block of memory with the specified size and returns a handle to it.
  10. if hMem <> 0 then ...
    • If the allocation was successful, continue with locking and reading the file data.
  11. _hread(hFile, p, size);
    • Reads the file data into the buffer using the _hread function.
  12. GlobalUnlock(hMem); Clipboard.SetAsHandle(CF_TEXT, hMem);
    • Unlocks the memory block and sets it as the clipboard format CF_TEXT.
  13. procedure TForm1.SpeedButton2Click(Sender: TObject);
    • This is an event handler for a speed button on a form. When clicked, it opens a file dialog to select a file, copies its contents to the clipboard using the CopyFileToClipboard procedure, and then closes the file.

Код seems to be well-written and should work as expected. However, I would suggest adding some error handling to handle cases where the file cannot be opened or read, or if there is an issue with allocating memory. Additionally, it might be a good idea to free the memory block after using it to avoid memory leaks.

Копирование большого файла в буфер обмена позволяет использовать функцию _hread для считывания файлов размером более 64 КБ и записи их в буфер обмена с помощью процедуры CopyFileToClipboard.


Комментарии и вопросы

Получайте свежие новости и обновления по Object Pascal, Delphi и Lazarus прямо в свой смартфон. Подпишитесь на наш Telegram-канал delphi_kansoftware и будьте в курсе последних тенденций в разработке под Linux, Windows, Android и iOS




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.


:: Главная :: Буфер обмена ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-19 13:29:56
2024-10-24 19:54:14/0.0055999755859375/1