2

I need to disable the close button on a window from another process. I have its handle in hWnd and I try to do this:

DWORD dwCStyle = GetClassLongPtr(hWnd, GCL_STYLE);
SetClassLongPtr(hWnd, GCL_STYLE, dwCStyle | CS_NOCLOSE);

But that doesn't seem to have any effect on that window.

PS. I test this on Vista. Both processes don't run elevated.

PS2. I check the result both "visually" and by using Spy++. The hWnd handle seems to point to the right window.

ahmd0
  • 16,633
  • 33
  • 137
  • 233
  • What does `SetClassLongPtr` return? – Billy ONeal May 30 '13 at 00:29
  • @ahmd0, And what does `GetLastError` return? "If the function fails, the return value is zero. To get extended error information, call GetLastError." – chris May 30 '13 at 00:33
  • @chris: Sorry, forgot to mention. GetLastError also returns 0. Do I need to enable any special privileges for my process? – ahmd0 May 30 '13 at 00:55
  • If I change `hWnd` to point to the main window in my own process, then this method succeeds and the close button is grayed out. – ahmd0 May 30 '13 at 00:56
  • It's possible you might have to inject the code into the other process. – chris May 30 '13 at 00:59
  • @chris: Oops, just realized that I wasn't calling GetLastError immediately after that API. It actually returns 5, which is ERROR_ACCESS_DENIED. Crap! – ahmd0 May 30 '13 at 01:09
  • You can try adjusting your process's token's privileges. I'm not sure if you need the same privileges to inject the code as you do to call this. – chris May 30 '13 at 01:11
  • 1
    The alternative is to patch the system menu, GetSystemMenu(). Disable the SC_CLOSE menu item. Having this work across process boundaries is equally iffy. – Hans Passant May 30 '13 at 01:25
  • @HansPassant: Wow. Amazing. I thought I would get another failure, but what would you know, the `hMenu=GetSystemMenu(hWnd, false);` followed by `DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);` worked. I tried it on the Notepad and even though the X in its menu can be clicked, it doesn't do anything. (Alt+F4 works though.) Thanks. If there's no other alternative to gray it out, you may want to post it as the answer. – ahmd0 May 30 '13 at 01:34
  • Don't delete it, disable it. I'll skip, I don't want to support these kind of cross-process hacking answers. – Hans Passant May 30 '13 at 01:38
  • @HansPassant: I'm not hacking anything. I need this to disable close button on one of our programs at the office because one lady seems to hit close on it all the time and forgets to reopen it. That's it. – ahmd0 May 30 '13 at 01:46
  • 1
    @ahmd0 If she's that inept get a new lady. – Captain Obvlious May 30 '13 at 01:56
  • @CaptainObvlious: Haha. – ahmd0 May 30 '13 at 02:04
  • 1
    Perhaps instead of disabling the close button, just a small program to run in the background that restarts the app when/if she closes it? – Jerry Coffin May 30 '13 at 05:20

0 Answers0