Solved

right clicking titlebar (Hooks/subclassing??)

Posted on 2000-03-25
13
404 Views
Last Modified: 2010-04-04
I am trying to capture every time any titlebar is right-clicked.  I can hook into the mouse, and so can capture any right click, but am having difficulty actually identifying what they have clicked on.  I believe its WM_NCHITTEST that is needed, but I'm stuck, and really need a code example, so any offers? please??
0
Comment
Question by:essexboy
  • 7
  • 5
13 Comments
 
LVL 3

Expert Comment

by:ckaneta
ID: 2657767
in private section
 procedure WMNCHitTest( var Msg : TWMNCHitTest ); message wm_NCHitTest;

procedure Tmnfrm.WMNCHitTest(var Msg:TWMNCHitTest);
 begin
  inherited;
  if(htCaption = Msg.Result)then  
   Msg.Result := htClient;
 end;

this basically just ignores all clicks on the caption of the form.

I'm fairly sure if you add an if statement that checks MSG to see if it is something like WM_RBUTTONDOWN or WM_RBUTTONUP you can distinguish between a left and right button click
0
 
LVL 10

Expert Comment

by:Lischke
ID: 2660004
Actually, what you need to capture is WM_NCRBUTTONDOWN:

type
  TMyForm = class(TForm)
  private
    procedure WMNCRButtonDown(var Message: TWMNCRButtonDown); message WM_NCRBUTTONDOWN;
  end;

procedure TMyForm.procedure WMNCRButtonDown(var Message: TWMNCRButtonDown);

begin
  if ARightClickIsAllowed then inherited
    else Message.Result := 0;
end;

Ciao, Mike
0
 

Author Comment

by:essexboy
ID: 2662634
Adjusted points from 100 to 110
0
 

Author Comment

by:essexboy
ID: 2662635
Ah, sorry, I feel that I did not explain correctly what it was that I wanted to do, so I shall try again.

I wish to capture right click on a titlebar on any window in the entire system, not just my app.

The two solutions i can see, are to hook into the mouse and then when a right click is detected, subclass the active window and process the message just received, but I think that this may not work too well/at all.

The second is to hook to receive WM_NCHITEST, and then process from there, but I do not know what to do about mouse buttons here.

My attempts at subclassing have failed, but I would prefer to use hooks, since I imagine it would be more reliable.

To try and hook into NCHITTEST, I have tried to do:

HookHandle := SetWindowsHookEx(WH_CALLWNDPROCRET, HookCallBack, HInstance, 0)

 and then

function HookCallBack(Code: integer; Msg: WPARAM; Hook: LPARAM): LRESULT; stdcall;
if Code >= 0 then begin
case Msg of
WM_NCHITTEST:
begin
MessageBeep(1);
..
..
and was kinda hoping for lots of beeps, but have had no success.  I adapted the hooking from <a href="http://202.206.32.19/delphi32.sonic.net.cn/delphi/D32SAMPL/WINHOOK.ZIP">http://202.206.32.19/delphi32.sonic.net.cn/delphi/D32SAMPL/WINHOOK.ZIP</a>

So, any suggestions?

Cheers

James


0
 

Author Comment

by:essexboy
ID: 2662650
oops, seems i messed up that last link a bit.

Anyway, I hope all the above made sense.

Thanks to the people who have tried to help so far.

Oh, also, I do not wish to use a component (just in case someone suggests it)

Thanks

James
0
 
LVL 10

Expert Comment

by:Lischke
ID: 2663261
Ah, yes, now I understand. Well, Brad usually writes really good software but the hook sample he wrote is, ...., uhm, ...., suboptimal ;-) Despite the fact that many stuff applies only to Win3.1 (e.g. task identifier in SetWindowHookEx) he also ignored one of the most important fact to consider when writing hooks. All variables (including the global hook handle declared in the units) are specific to the process the hook has been activated in. So when the mouse hook callback is triggered for another process than the one which installed the hook ALL these variables are uninitialized and invalid!

Here's correct code to do the hook:



library Hook;

uses
  Windows, SysUtils;

type
  // shared memory area used by the DLL in different process contexts (loacted in memory mapped file)
  PHookInfo = ^THookInfo;
  THookInfo = record
    MouseHook,           // general mouse messages
    SynchEvent: THandle; // used to synchronize main program and hook DLL
    Windows9x: Boolean;
  end;

const
  InternalFileMappingName = 'HookInternalMemory';
  HookEvent = 'HookInternalEvent';

var
  InternalMapping: THandle;
  HookInfo: PHookInfo;
 
//----------------------------------------------------------------------------------------------------------------------

function GetSharedData: Boolean;

begin
  Result := True;
  // create shared memory area to use some global variables for all process contexts the DLL can be called in
  InternalMapping := CreateFileMapping(DWORD(-1), nil, PAGE_READWRITE, 0, SizeOf(THookInfo), InternalFileMappingName);
  if DictInternalMapping <> 0 then
  begin
    // the shared memory will be mapped for the entire lifetime of the DLL (it needs really not much memory)
    HookInfo := MapViewOfFile(InternalMapping, FILE_MAP_READ or FILE_MAP_WRITE, 0, 0, SizeOf(THookInfo));
    if Assigned(HookInfo) then
    begin
      with HookInfo^ do
      begin
        // Retrieve handle to synchronization event. This handle needs not to be freed from here and must be
        // created by the main application. The event must be created initially set as this is the state which
        // indicates free operation for the hook.
        SynchEvent := OpenEvent(EVENT_ALL_ACCESS, False, HookEvent);
        if SynchEvent = 0 then Result := False; // show that something went wrong
        Windows9x := (Win32Platform and VER_PLATFORM_WIN32_NT) = 0;
      end;
    end
    else Result := False; // show that something went wrong
  end
  else Result := False; // show that something went wrong
end;

//----------------------------------------------------------------------------------------------------------------------

procedure ReleaseSharedData;

begin
  if Assigned(HookInfo) then
  begin
    UnmapViewOfFile(HookInfo);
    if InternalMapping <> 0 then CloseHandle(InternalMapping);
    InternalMapping := 0;
    HookInfo := nil;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function MouseHookProc(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT stdcall;

var IsEvent: Boolean;

  function DoDefault: LRESULT;

  begin
    Result := CallNextHookEx(HookInfo.MouseHook, Code, wParam, lParam);
  end;

begin
  if GetSharedData then
  begin
    // check if we have still a pending message to swallow
    if (HookInfo.SwallowMessage = wParam) then
    begin
      HookInfo.SwallowMessage := -1;
      if Code < 0 then Result := DoDefault
                  else Result := 1;
    end
    else
    begin
      // A timeout value of 0 means not to wait for the event but to check it.
      // An unsignaled event means there were no results before or the main application has already
      // processed the last result. The event must manually be reset by the application!
      IsEvent := (WaitForSingleObject(HookInfo.SynchEvent, 0) = WAIT_TIMEOUT) and
                 ((wParam = WM_MBUTTONDOWN) or (wParam = WM_NCMBUTTONDOWN));

      if IsEvent and (GetAsyncKeyState(VK_CONTROL) < 0) then
      begin
        with PMouseHookStruct(lParam)^ do
          if HookInfo.Windows9x then DoWin9xStuff(hwnd, Pt)
                                else DoWinNTStuff(hwnd, Pt);
        if Code < 0 then Result := DoDefault
                    else Result := 1;
      end
      else Result := DoDefault;
    end;
  end
  else Result := 1;
  ReleaseSharedData;
end;

//----------------------------------------------------------------------------------------------------------------------

function InitializeHook: Boolean;

begin
  if GetSharedData then
  begin
    with HookInfo^ do
    begin
      if MouseHook = 0 then
        MouseHook := SetWindowsHookEx(WH_MOUSE, MouseHookProc, HInstance, 0);
      Result := (MouseHook <> 0);
    end;
  end
  else Result := False;
  ReleaseSharedData;
end;

//----------------------------------------------------------------------------------------------------------------------

function RemoveHook: Boolean;

begin
  if GetSharedData then
  begin
    Result := True;
    with HookInfo^ do
    begin
      if MouseHook <> 0 then
      begin
        Result := UnhookWindowsHookEx(MouseHook);
        MouseHook := 0;
      end;
    end;
  end
  else Result := False;
  ReleaseSharedData;
end;

//----------------------------------------------------------------------------------------------------------------------

var
  LastExitProc: Pointer;

function ExitLibrary: Boolean;

begin
  ExitProc := LastExitProc;
  Result := True;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure InitLibrary;

begin
  LastExitProc := ExitProc;
  ExitProc := @ExitLibrary;
end;

//----------------------------------------------------------------------------------------------------------------------

exports
  InitializeHook,
  RemoveHook;

begin
  InitLibrary;
end.

Ciao, Mike
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:essexboy
ID: 2665717
Thanks for the code Mike. Please could you explain a little what DictInternalMapping and SwallowMessage do/are, since these mean it won't compile, I guess the second is whether or not to pass on the message, but the first has stumped me completely.

See ya

James
0
 
LVL 10

Expert Comment

by:Lischke
ID: 2679149
Oops, sorry. I copied the code out from one of my projects and have obviously not changed all references. Please, just change DictInternalMapping to InternalMapping (there is a variable declaration). The SwallowMesage is quite simple. Sometimes it is important not to handle a particular message when a previous one has been picked up by the hook. E.g. mouse down triggers in my case a popup window, so this message doesn't go through to the target application. But because mouse down doesn't come through I don't want mouse up to come through, either.

Ciao, Mike
0
 

Author Comment

by:essexboy
ID: 2681619
Adjusted points from 110 to 150
0
 

Author Comment

by:essexboy
ID: 2681620
Mike,

Firstly, my computer with delphi on is inaccessable for a few days, so I'm trying just to follow the code by eye (and memory), so I hope I don't say anything to obviously stupid..

So SwallowMessage should be defined in THookInfo as Integer, or wParam or something similar?

Also for swallowmessage it is set to -1 at one point, but never cleared or anything else.  -1 is mouseup?  why is it never cleared?

I want detect WM_NCRBUTTONDOWN which is what is sent when the user right clicks the titlebar, and then swallow the WM_RBUTTONUP which follows (and [possibly] triggers the menu).  I do not understand why Windows sends WM_RBUTTONUP and not WM_NCRBUTTONUP, its very annoying (plus it means hittest is htClient and not htCaption, also a pain!).  But anyway, if you can explain these things, and show me what to do, the points are all yours (I've upped it to the amount I have - I really am grateful for your help)

Cheers,

James
0
 
LVL 10

Accepted Solution

by:
Lischke earned 150 total points
ID: 2683068
Hi James,

since you came so far (at least with understanding the basics) it is hard to understand the rest. In MouseHookProc I changed the line

  if Code < 0 then Result...

from

        if Code < 0 then Result := DoDefault
                    else
        begin
          Result := 1;
          if wParam = WM_MBUTTONDOWN then HookInfo.SwallowMessage := WM_MBUTTONUP
                                     else HookInfo.SwallowMessage := WM_NCMBUTTONUP;
        end;


SwallowMessage is indeed defined as Integer so setting it to -1 is possible (which denotes no pending message) and makes sure it does not represent a valid message as this value is compared with the incoming message in MouseHookProc, in this line:

if (HookInfo.SwallowMessage = wParam) then ...

and reset if it applies. Furthermore, no redirection of the message is done so it never reaches the target window.

Ciao, Mike
0
 
LVL 10

Expert Comment

by:Lischke
ID: 2683071
.. it is NOT hard to understand the rest. :-)))
0
 

Author Comment

by:essexboy
ID: 2685155
Brilliant, it all makes sense now.

Cheers

James
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now