var
Form1: TForm1;
h: HWND;
proc: LongInt;
function WndProc2(hwnd: HWnd; Msg: UINT; wParam: wParam; lParam: LPARAM): Integer; stdcall;
implementation
{$R *.dfm}
function WndProc2(hwnd: HWnd; Msg: UINT; wParam: wParam;
lParam: LPARAM): Integer;
var
i: Integer;
begin
case Msg of
WM_LBUTTONUP: begin
MessageBeep(MB_ICONASTERISK);
end
end;
Result := CallWindowProc(TFNWndProc(proc), hwnd, Msg, wParam, lParam);
end;
// AParentHandle: 被插入按钮的窗口句柄
// AWidth: 被插入的按钮的宽度
procedure TForm1.InsertButton(const AParentHandle: THandle;
const AWidth: Integer);
var
l: LongInt;
r: TRect;
x,iHeight: Integer;
begin
//获得坐标
GetWindowRect(AParentHandle,r);
//计算插入坐标
x := r.Right - r.Left - AWidth;
iHeight := r.Bottom - r.Top - 2;
h := CreateWindow('BUTTON', 'Hello',
WS_VISIBLE + WS_CHILD, x, 1, AWidth, iHeight, AParentHandle, 0, 0, nil);
proc := GetWindowLong(h, GWL_WNDPROC);
l := LongInt(@WndProc2);
SetWindowLong(h, GWL_WNDPROC, l);
end;
有时候控制别的程序时候, 要加上自己的按钮, 并响应.
代码是在这个论坛搜到的, 感谢提供方法的前辈 liyinwei
http://www.delphixebbs.com/read-htm-tid-97795.html
又找到个代码, 可以有背景图的, 还没测试, 感谢刘麻子
http://www.delphixebbs.com/read-htm-tid-1093490-page-2.html
program ButtonBMP;
{$R 'Resource.res' 'Resource.rc'}
uses
Windows, Messages;
// 标准过程
var
DefButtonProc: function (hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
// 窗口过程
function ButtonProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
ButtonDC: HDC;
ButtonRect: TRect;
ButtonText: array [0..50] of Char;
begin
Result := DefButtonProc(hWnd, Msg, wParam, lParam);
if (Msg = WM_PAINT) or (Msg = BM_SETSTATE) then
begin
GetClientRect(hWnd, ButtonRect);
GetWindowText(hWnd, @ButtonText, SizeOf(ButtonText));
ButtonDC := GetDC(hWnd);
DrawText(ButtonDC, ButtonText, -1, ButtonRect, DT_SINGLELINE or DT_CENTER or DT_VCENTER);
ReleaseDC(hWnd, ButtonDC);
end;
end;
// 程序入口
var
hButton: HWND;
Msg: TMsg;
begin
// 建立窗口
hButton := CreateWindowEx(
0, 'Button', '测试按钮(位图+文字)',
WS_TILEDWINDOW or WS_VISIBLE or BS_BITMAP,
Integer(CW_USEDEFAULT), SW_SHOW,
Integer(CW_USEDEFAULT), 0,
0, 0, HInstance, nil);
// 设置位图
SendMessage(hButton, BM_SETIMAGE, IMAGE_BITMAP, LoadBitmap(HInstance, 'TestBMP'));
// 子类化
DefButtonProc := Pointer(SetWindowLong(hButton, GWL_WNDPROC, DWORD(@ButtonProc)));
// 消息循环
while IsWindow(hButton) do
begin
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
end.