views:

207

answers:

3
HWND button = CreateWindowEx(0, "BUTTON", ...);
SetFocus(button); // Button no get focus! :(

Also, I have other controls on my form that I am able to SetFocus() to.

Thanks, Martin

A: 

SetFocus is a function, not a procedure. Call it as a function and check its returned value. Either the retuned value is null because you made an error in the CreateWindowEx() call and "button" isn't a valid handle or it's a window not associated with your thread's message queue, or the return value is not null (it's now the prior focused window's handle) and you do have the focus (but are somehow failing to detect it).

joe snyder
What's the difference between a function and a procedure? As far as I can see (I may be wrong), I am calling it as a function. In my code, I'm checking to see if SetFocus returns NULL and if the button's handle is NULL. They aren't. Thanks for the suggestion.
Martin
btw, I can setfocus to other controls on my window
Martin
@Martin: a function call has a return value, like CreateWindowEx(). The correct SetFocus() call would be oldhandle = SetFocus(newhandle). You should be checking the button value returned by CreateWindowEx() to determine if that call is returning a non-null. You say you are, so your actual code must be different than what you posted. Post the complete code, including how you are determining you don't have the focus (because maybe you do). Also note that SetFocus() sends WM_KILLFOCUS and WM_SETFOCUS messages to the formerly and currently focused windows.
joe snyder
ok the button gets the focus but, the border you get when you "tab" to the button is not there
Martin
thanks, but that doesn't fix the problem
Martin
@Martin: The style param (3rd param for CreateWindow, 4th param for CreateWindowEx) should include WS_TABSTOP to get the focus after a tab.
joe snyder
@Martin: You probably need to set the `BS_DEFPUSHBUTTON` style (and to remove it from any button that had the style before). Normally you shouldn't be doing this yourself and should be using something like `WM_NEXTDLGCTL` if you're using a dialog box. (Also see http://blogs.msdn.com/b/oldnewthing/archive/2004/08/02/205624.aspx .)
jamesdlin
A: 

Try setting the WS_TABSTOP style on the button.

Brian Nixon
A: 

If you create that button in respond of the WM_INITDIALOG message you should return FALSE to prevent dialog box procedure to change the focus.

Tassos