子类化窗口辅助类NativeWindow

类别:Delphi 点击:0 评论:0 推荐:

子类化窗口在高级开发中的重要利器。受c#中NativeWindow的启发,实现了下面这样一个简单的类,来帮助更容易地对窗口实现子类化。

unit NativeWindow;

interface

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

Type
  TzwNativeWindow = class
  private
    m_OldWinProc:FARPROC  ;
    m_NewWinProc:FARPROC  ;
    m_Handle:THandle;
  protected
    procedure WndProc(var Message: TMessage); virtual;
  public
    constructor Create;
    destructor Destroy;override;
    procedure AssignHandle(WndHandle:THandle);
    procedure ReleaseHandle;
    property Handle:THandle read m_Handle;
  end;

implementation

{ TzwNativeWindow }

procedure TzwNativeWindow.AssignHandle(WndHandle: THandle);
begin
  if (m_Handle<>WndHandle) then
  begin
    ReleaseHandle;
  end;
  m_Handle := WndHandle;
  m_NewWinProc := MakeObjectInstance (WndProc );
  m_OldWinProc := pointer(GetWindowLong (m_Handle ,GWL_WNDPROC ));
  SetWindowLong(m_Handle , GWL_WNDPROC, LongInt(m_NewWinProc));
end;

constructor TzwNativeWindow.Create;
begin
  m_Handle := INVALID_HANDLE_VALUE;
  m_OldWinProc := nil;
  m_NewWinProc := nil;
end;

destructor TzwNativeWindow.Destroy;
begin
  ReleaseHandle;
  inherited;
end;

procedure TzwNativeWindow.ReleaseHandle;
begin
  if (m_Handle<>INVALID_HANDLE_VALUE) then
  try
    SetWindowLong(m_Handle,GWL_WNDPROC,LongInt(m_OldWinProc));
  finally
    m_Handle := INVALID_HANDLE_VALUE;
    m_OldWinProc := nil;
    m_NewWinProc := nil;
  end;
end;

procedure TzwNativeWindow.WndProc(var Message: TMessage);
begin
  with Message do
  begin
    Result := CallWindowProc(m_OldWinProc , m_Handle , Msg, wParam, lParam);
  end;
end;

end.

本文地址:http://com.8s8s.com/it/it5234.htm