截获消息(1)
很久没有给大家写东西了,今天有点兴趣,写一点。
Delphi中,每一个构件都有一个内在的消息处理机制,这是默认的,如果没有特别制定消息处理,就调用默认的消息处理。
理论我就不和大家说了,大家实践为主,省去一大堆什么vcl什么结构的,免得看了头痛。
截获消息主要有3种方法:
1、重载构建继承的虚拟方法wndproc,这可以截获所有消息
2、针对某消息写的消息处理句柄,可以截获制定的消息
3、重载构建继承的虚拟方法defhandler.
1种:重载wndproc
procedure tmyobject.wndproc(var message:tmessage);
begin
{
inherited wndproc(message);
end;
给个例子:
procedure TControl.wndproc(var meesag:tmessage);
begin
{
if (message.msg>=wm_mousefirst)and(message.msg<=wm_mouselast) then
if dragging then
dragmousemsg(twmmouse(message))
else begin
………(处理其他的鼠标消息)
end;
dispatch(message); //否则正常发送信息
end;
我们来写一个完整的类,一个没有焦点的edit控件
unit myedit;
interface
uses
Windows,Messages,SysUtils,Classes,Graphics,Controls,Forms,Dialogs,
StdCtrls;
type
Tmyedit=class(TEdit)
private
{Privatedeclarations}
protected
{Protected declarations}
{other fields and methods}
procedure wndproc(var message:Tmessage);override;//重载
public
{Publicdeclarations}
published
{Publisheddeclarations}
end;
procedure Register;
implementation
procedure Register;//在IDE中进行注册
begin
RegisterComponents('Samples',[Tmyedit]);
//注册到Samples页中,控件名是Tmyedit
end;
procedure Tmyedit.wndproc(var message:tmessage);
begin
if message.msg=wm_mousemove then
begin
{设置光标为crarrow,而不是缺省的crBeam光标}
cursor:=crarrow;
exit;
end;
{屏蔽掉WM_SetFocus消息,不让Tmyedit控件获得输入焦点}
if message.msg=wm_SetFocus then exit;{什么也不执行}
inherited wndproc(message);{其它消息交父辈的wndproc处理}
end;
end.
对于第2种方法,很简单,用消息发生器就可以了,第3种嘛我也没用过,有兴趣的朋友可以自己搞一下。因为第一种处理有优势,可以处理全部的消息,所以比较实用。
看到这里可能大家还在想,看了这么多还没有说到怎么截获其他程序的消息亚,别急,这是前奏,下一篇就讲如何解或其他程序的消息了