Wpf prevent Popup window from removing the focus of an Textbox - c#

In my WPF-Application I use a small window to display some notifications, but when the notificationwindow shows up, the focus in the mainwindow gets lost.
For example when I'm writing in a TextBox and I'm receiving a notification (the notification window shows up), the textbox loses the focus and I have to click in the textbox again to continue my Work.
So how can I keep the focus of the mainwindow, when the notificationwindow shows up? I already tried to set Focusable="false" in the notificationwindow

It's not really a case of how can I stop some control from becoming focused?, rather how can I focus my control after it has lost focus? Now, as # AdrianFaciu mentioned, it's rather difficult to go into details when you have omitted all relevant information from your question. One option would be to set focus to your control whenever it loses focus:
private void OnControlLostFocus(object sender, RoutedEventArgs e)
{
YourControlType control = sender as YourControlType;
if (control != null) control.Focus();
}

There is a ShowActivated property on Window object so you can keep the main window activated after you show a child window.
From MSDN:
When a window with its ShowActivated property set to false is opened, the window is not activated and its Activated event is not raised until a user manually activates the window by selecting it.

Related

On windows forms, set tab focus to a button

I have created an Outlook add in which at some point displays a windows form with four buttons present on it. I am trying to default the focus to the first button, however the visual "selected" border will not appear around the button whenever I default this button as the focused one on start.
Any ideas how I could achieve this?
You can use either of these options to set the focus on a control in Load event of the form:
this.ActiveControl = this.button1;
this.button1.Select();
this.Show(); this.button1.Focus();.
You can use the Control.Focus method in the Load event of the form to set the focus on a control only after the Visible property of the form is set to true.
After selection the button, the border of the button will be drawn in a way that shows it's the active control, but the focus cues will not be drawn.
As a quick and dirty fix, you can send a Tab, and a Shift + Tab to your form:
SendKeys.SendWait("{TAB}");
SendKeys.SendWait("+{TAB}");
If you are interested to change the standard behavior of Button to see focus cues when you select button in code or using mouse, you can create your own button inheriting Button and override its ShowFocusCues to return Focused value. You can read more about it here:
public class MyCustomButton : Button
{
protected override bool ShowFocusCues
{
get { return this.Focused; }
}
}

In what situations will WPF give keyboard focus back to the main window?

In a WPF application I'm working on, I have a MenuItem with two items in it. When the MenuItem is clicked, it takes keyboard focus and opens its submenu. When the MenuItem is clicked again, the submenu is closed and for some reason, the main window takes keyboard focus. I need the MenuItem to keep focus.
I have been told that in certain other situations, the main window may be given keyboard focus - for instance, if a control has keyboard focus and IsEnabled or IsVisible becomes false. In which situations does this happen? I've been Googling like crazy but haven't found any information about this.
As far as I can tell, this is the expected behavior. WPF Menus are focus scopes by default, so any control within the menu that receives focus won't change the main logical focus of the window.
Also, certain WPF controls will sometimes call Keyboard.Focus(null); (e.g. Button does this when clicked). This call has the effect of returning the keyboard focus to the main logical focus. I suspect this is also happening when a menu is closed.
Try disabling the focus scope on the menu: <Menu FocusManager.IsFocusScope="False">
When the menu item receives the keyboard focus, and it's not in any focus scope, it will gets the main logical focus. This means the Keyboard.Focus(null) call will keep the focus on the menu item. Jowever, this will also prevent commands in the submenu from returning the focus to the non-menu window content, so routed commands won't be able to find their target.
See "For What was FocusScope Designed?" in Using the WPF FocusScope.

How can I give focus to any Control after a Tab has been selected

I have a problem .. I have an error list form (works as validation summary screen) that displays validation of controls that require to save data but have no values.
This form opened when validation occurs on controls in another form that has tab control contains all controls that have validation.
The problem is when I double click on Error List form, I need cursor focus on tab control that have this control and focus on the control itself
The result : focus happened on tab control only .. but I need to focus on the control also
Use Control.Focus() in your tab selected event handler.
Call Focus() to focus on the next control.
Step 1 : You need to handle the Enter event of the TabPage Control to perform the operations when TabPage gains the focus.
Step 2: You can call Select() function on Required control to gain the Focus.
Try This: if you want to gain the Focus of TextBox control in TabPage2 use this code
tabPage2.Enter += new System.EventHandler(this.tabPage2_Enter);
private void tabPage2_Enter(object sender, EventArgs e)
{
textBox1.Select();
}
I think the trick is to set socus on the tab page first, then set focus on the actual control you want to focus on.
What I was seeing is if the tab page was already selected setting focus to the control works fine. However, if the tab was programmatically activated then setting focus on the control alone does not work.
So this works for me reliably:
// first select and focus the tab
TabsResult.SelectedTab = tabRequest;
TabsResult.SelectedTab.Focus();
// then focus the control
txtRequestUrl.Focus();

Form Opened As Modal Dialog Closes When Button Is Pressed, Even Though Close() is not called

I'm writing a Windows application that basically runs in the background with a notification icon to interact with it. The notification icon can do basic things like exit the application or show information about it. It can also launch a modal configuration dialog.
The code that creates the dialog is pretty straightforward:
using(var frmSettings = new SettingsForm(configuration))
{
frmSettings.ConfigurationChanged += ConfigurationChangedHandler;
frmSettings.UnhandledException += UnhandledExceptionHandler;
frmSettings.ShowDialog();
}
The SettingsForm class basically has three GroupBox controls, with a Label and TextBox control in each, and 4 Button controls at the bottom: "Advanced...", "Restore Defaults", "Cancel", and "Apply". Each TextBox has a Validating event handler wired up through the designer. Each button has a Click handler wired up through the designer. Each of them does pretty obvious things: opens another modal dialog with more advanced settings, restores the textboxes to their default values, closes the dialog, or saves the changes, fires the ConfigurationChanged event, and then closes the dialog (but only if all fields are valid!).
When there is a form entry error I cancel the corresponding Validating event by setting ((CancelEventArgs)e).Cancel = true. However, the default behavior of both forms was to prevent the user from changing focus when validation failed. I found this pretty annoying and eventually found the option in the designer to still automatically validate when the user leaves the field, but to allow them to leave even if validation fails: AutoValidate = EnableAllowFocusChange.[1]
My "Apply" button Click handler looks basically like this:
private void btnApply_Click(object sender, EventArgs e)
{
try
{
if(this.ValidateChildren())
{
this.Configuration.Field1 = this.txtField1.Text;
this.Configuration.Field2 = this.txtField2.Text;
this.Configuration.Field3 = this.txtField3.Text;
if(this.Configuration.Changed)
{
this.Configuration.Save();
this.OnConfigurationChanged(new ConfigurationChangedEventArgs(
this.Configuration));
}
this.Close();
}
}
catch(Exception ex)
{
this.OnUnhandledException(new UnhandledExceptionEventArgs(
"Failed To Apply Configuration Settings",
ex));
}
}
I'm currently testing out the code by breaking on the first line and stepping through the method line by line. Essentially, ValidateChildren is returning false as expected and the entire if block, including the this.Close() are skipped. Yet, if I step all the way to the bottom of the method and then step out of it I end up back on the frmSettingsForm.ShowDialog() line and the form is magically closed.
The "Apply" button is set as the form's AcceptButton. I wonder if it's implicitly attached a handler to the button's Click event to automatically close the form when the button is pressed. That doesn't sound like it logically should be assumed, especially considering there doesn't seem to be a way to cancel the Click event, but it's the only explanation that I can come up with. To test that theory, I have tried unsetting the AcceptButton in the designer, but my form still closes when the data is invalid.
What is closing my form and how do I stop it?
[1]: If anybody else has trouble finding it, it's a form property, not a property of each individual control (as I expected it would be).
Do you have the DialogResult of the Button set? If so, when you click the Button, the DialogResult of the Form will be set to that value and the modal Form will close. To prevent this, when validation fails in your Click handler, set the Form's DialogResult to DialogResult.None.
I don't know why that happens, but you could override the event OnFormClosing and check for the value of DialogResult according to your logic.
If (DialogResult != Windows.Forms.DialogResult.Cancel )
e.Cancel = True

Close Popup when focus lost

I have a popup containing a ListView. The ListView contains customer names. The popup is openen when a search bar is clicked. The user can enter text in the search bar (TextBox) and the Listview is filterd based on the input.
I want to close the popup whenever it loses focus. However, the default "auto close" behaviour StaysOpen="False" is no good, because it closes the popup everytime someone clicks on the search bar.
How can I close the Popup always when it loses focus, except when the focus goes to the search bar?
Maybe you can put some hooks on the search text box. When it receives focus, it can open the popup and set StaysOpen = true. When the textbox loses focus, it can set StaysOpen = false on the popup.
XAML Code:
<Popup x:Name="pop" StaysOpen="False">
Add an event handler to the Leave event (called when focus on the control is lost). In this event handler, you can then check to see if the new item that has focus is the search text box.
if(FormName.ActiveForm.ActiveControl == txtSearchBox)
Then set StaysOpen appropriately based on whether or not the search textbox has focus.
How about:
Forward the focus-lost(Leave, occurs when the control is no longer the active control of the form) event of popup to the parent form
Parent form would, do nothing, if the current focus is on the search bar; else, it would close the the popup.

Categories

Resources