Update: Discusion revealed that the problem is only arising, when you have the custom control text box hosted within a wpf application that is again hosted via elementhost within a winforms application.
I have a WPF-CustomControl inherting from TextBox. I override the OnLostKeyBoardFocus method.
As part of this method I raise an event. One event handler is showing a MessageBox (this is not under my control). When the user closes the MessageBox the KeyBoardFocus is returned to the TextBox, directly. Even though, OnLostKeyboardFocus(...) has still not returned.
The automatic (re)focussing on my TextBox control, causes a whole range of problems for me. Can I circumvent this behavior in some way other than dispatching the event with Dispatcher.BeginInvoke().
class MyTextBoxCustomControl : TextBox {
public event EventHandler<EditCompletedEventArgs> EditCompleted;
private void OnEditCompleted(EditCompletedEventArgs e)
{
var handler = EditCompleted;
if (handler != null) handler(this, e);
}
protected override OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e){
base.OnLostKeyboardFocus(e);
OnEditCompleted(new EditCompletedEventArgs())
//Before this point is reached OnGotKeyboardFocus(...) is called
}
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
//Is called twice, directly after MessageBox is closed and
//after OnLostKeyboardFocus(...) returns
}
}
class MyEventHandler {
private void Test(){
var myTBCC = new MyTextBoxCustomControl();
//Closing the message box will return focus to myTBCC, which directly
//causes OnGotKeyboardFocus to be called
myTBCC.EditCompleted += (a, b) =>
MessageBox.Show("PressOk");
}
}