Re: ContainsFocus == broken?
The focus is always set to whatever window has the focus.
In the case of an edit box it will have the focus, not its parent window (although the window focus is to its parent).
Therefore try this :
Code:
class FocusHelper
{
static public bool HasFocus(Control control)
{
if (control.Focused)
{
return true;
}
foreach (Control control in control.Controls)
{
if (HasFocus(control))
{
return true;
}
}
return false;
}
}
Bear in mind that Form is derived from Control, so you can pass the parent form into this function.
Darwen.
Re: ContainsFocus == broken?
Ok, I tried that and it seems that none of the controls returns true for .Focused
Here's what I ended up using
Code:
class FocusHelper
{
static public bool HasFocus(Control control)
{
if (control.Focused)
{
return true;
}
foreach (Control ctrl in control.Controls)
{
if (HasFocus(ctrl))
{
return true;
}
}
return false;
}
}
and I followed it through each control and each one returns a false. event he one that had the cursor flashing in it. There's got to be something that I'm missing.
Re: ContainsFocus == broken?
Where are you doing this method ? If you're doing it as a response to a mouse click on another window then the other window will have focus and not the one you're testing.
Darwen.
Re: ContainsFocus == broken?
The check is launched in a method called by an event generated when a network packet arrives from another machine. (I have two physical machines set up to test it).
A problem comes that the user needs some way of being notified that the packet has arrived, but only if the window is not the currently focused window.
I guess the best analogy would be MSN messenger, it flashes and beeps when someone sends you a reply to an ongoing conversation and you are in a different window. And then if you are in that window when another message arrives it's silent.
I did some further checking, I added a logger to the FocusHelper, just to see if perhaps the BreakPoint I added was causing things not to be in focus. Even when running in release mode it still came back as false for each control.
Re: ContainsFocus == broken?
So does anyone have any examples where either .ContainsFocus or .Focused works?
Thanks.
Re: ContainsFocus == broken?
Well, I had once tried it too... but really this property does not work...
Re: ContainsFocus == broken?
Thanks Andy, that's the answer I was afraid of. This like so much other stuff in .net. It's really frustrating that they included it and never made it work.
Re: ContainsFocus == broken?
Hmmm - not really experienced any bugs in .NET that I'd really gripe about. If I had I wouldn't be using it in anger.
Of course you can hook the GotFocus and LostFocus events and set a variable to record which control has the focus.
Darwen.