⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 unitduphandle.pas

📁 DelphiWin32核心API参考光盘内容.是学习书籍中的源码,便于学习.
💻 PAS
字号:
unit UnitDupHandle;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Gauges, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  ThreadHandle: THandle;         // holds a handle to the current thread
  TargetHandle: THandle;         // holds a duplicated thread handle

implementation

{$R *.DFM}

function ThreadFunc(Info: Pointer): Integer;
var
  ICount: Integer;     // general loop counter
  FormDC: HDC;         // holds the form device context
begin
  {get a handle to the form's device context}
  FormDC := GetDC(Form1.Handle);

  {display something visual}
  for ICount := 1 to 10000 do
    TextOut(FormDC, 10, 50, PChar(IntToStr(ICount)), Length(IntToStr(ICount)));

  {pause the thread until ResumeThread is called, note SuspendThread
   is called with the duplicated handle}
  SuspendThread(TargetHandle);

  {display something visual}
  for ICount := 1 to 10000 do
    TextOut(FormDC, 110, 50, PChar(IntToStr(ICount)), Length(IntToStr(ICount)));

  {release the form's device context}
  ReleaseDC(Form1.Handle, FormDC);

  {end the thread}
  ExitThread(5);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Duplicated: Bool;          // holds the result of handle duplication
  CurrentProcess: THandle;   // holds the current process handle
  CurrentThread: THandle;    // holds the current thread identifier
  ThreadId: DWORD;           // holds the created thread identifier
begin
  {Create The thread and start it immediately}
  ThreadHandle := CreateThread(nil, 0, @ThreadFunc, nil, 0, ThreadId);

  {retrieve the current process and thread}
  CurrentProcess := GetCurrentProcess;
  CurrentThread := GetCurrentThread;

  {duplicate the handle of the created thread into TargetHandle}
  Duplicated := DuplicateHandle(CurrentProcess, ThreadHandle, CurrentProcess,
                                @TargetHandle, 0, FALSE, DUPLICATE_SAME_ACCESS);

  {indicate if there was an error}
  if not(Duplicated) then
  begin
    ShowMessage('The duplication did not work');
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  {Start the thread agian after the pause, note ResumeThread is called with the
  duplicated handle}
  ResumeThread(TargetHandle);
end;

end.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -