开发中,经常需要对一些编辑框作输入限制,如限制只能输入0..9的数字,这通过OnKeyPress事件即可达到:if not (Key in ['0'..'9', #8]) then Key := #0; 但是这只能限制键盘输入,对通过鼠标右键粘贴的情况就无法进行限制啦。下面的代码是通过对编辑框进行subclass而过滤掉WM_CONTEXTMENU右键菜单消息,从而达到屏蔽右键菜单。
var
FHookCtrls: TStringList;
{ 截获过滤编辑框Edit弹出右键菜单消息WM_CONTEXTMENU }
function EditWndProc(hwnd: HWND; Msg: UINT; WParam: WPARAM; LParam: LPARAM): LRESULT; stdcall; var I: Integer; begin if Msg = WM_CONTEXTMENU then Result := 1 else begin I := FHookCtrls.IndexOf(IntToStr(hwnd)); if I >= 0 then Result := CallWindowProc(Pointer(FHookCtrls.Objects[I]), hwnd, Msg, WParam, LParam) else Result := 1; end; end;
procedure HookControl(const Control: array of TWinControl); var I, X: Integer; begin for X := Low(Control) to High(Control) do begin I := FHookCtrls.Add(IntToStr(Control[X].Handle)); FHookCtrls.Objects[I] := Pointer(GetWindowLong(Control[X].Handle, GWL_WNDPROC)); SetWindowLong(Control[X].Handle, GWL_WNDPROC, Longint(@EditWndProc)); end; end;procedure UnhookControl(const Control: array of TWinControl);
var
I, X: Integer;
begin
for X := Low(Control) to High(Control) do
begin
I := FHookCtrls.IndexOf(IntToStr(Control[X].Handle));
if I >= 0 then
begin
SetWindowLong(Control[X].Handle, GWL_WNDPROC, Longint(FHookCtrls.Objects[I]));
FHookCtrls.Delete(I);
end;
end;
end;
initialization
FHookCtrls := TStringList.Create;
FHookCtrls.Sorted := True;
finalization
FHookCtrls.Free;
end.
来源:http://www.delphibbs.com/keylife/iblog_show.asp?xid=17224