I need to be able to determine when ContainsFocus changes on a Control (specifically a windows form). Overriding OnGotFocus is not the answer. When I bring the form to the foreground, ContainsFocus is true and Focused is false. So is there an OnGotFocus equivalent for ContainsFocus? Or any other way?
Note: GotFocus events of the child controls are fired if you have a child control. Otherwise OnGotFocus of the form is called.
If I understood the question correctly, then this should work:
bool lastNotificationWasGotFocus = false;
protected override void OnControlAdded(ControlEventArgs e)
{
SubscribeEvents(e.Control);
base.OnControlAdded(e);
}
protected override void OnControlRemoved(ControlEventArgs e)
{
UnsubscribeEvents(e.Control);
base.OnControlRemoved(e);
}
private void SubscribeEvents(Control control)
{
control.GotFocus += new EventHandler(control_GotFocus);
control.LostFocus += new EventHandler(control_LostFocus);
control.ControlAdded += new ControlEventHandler(control_ControlAdded);
control.ControlRemoved += new ControlEventHandler(control_ControlRemoved);
foreach (Control innerControl in control.Controls)
{
SubscribeEvents(innerControl);
}
}
private void UnsubscribeEvents(Control control)
{
control.GotFocus -= new EventHandler(control_GotFocus);
control.LostFocus -= new EventHandler(control_LostFocus);
control.ControlAdded -= new ControlEventHandler(control_ControlAdded);
control.ControlRemoved -= new ControlEventHandler(control_ControlRemoved);
foreach (Control innerControl in control.Controls)
{
UnsubscribeEvents(innerControl);
}
}
private void control_ControlAdded(object sender, ControlEventArgs e)
{
SubscribeEvents(e.Control);
}
private void control_ControlRemoved(object sender, ControlEventArgs e)
{
UnsubscribeEvents(e.Control);
}
protected override void OnGotFocus(EventArgs e)
{
CheckContainsFocus();
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)
{
CheckLostFocus();
base.OnLostFocus(e);
}
private void control_GotFocus(object sender, EventArgs e)
{
CheckContainsFocus();
}
private void control_LostFocus(object sender, EventArgs e)
{
CheckLostFocus();
}
private void CheckContainsFocus()
{
if (lastNotificationWasGotFocus == false)
{
lastNotificationWasGotFocus = true;
OnContainsFocus();
}
}
private void CheckLostFocus()
{
if (ContainsFocus == false)
{
lastNotificationWasGotFocus = false;
OnLostFocus();
}
}
private void OnContainsFocus()
{
Console.WriteLine("I have the power of focus!");
}
private void OnLostFocus()
{
Console.WriteLine("I lost my power...");
}
One way to solve this is to use a Timer. It's definitely brute force, but it gets the job done:
private Timer m_checkContainsFocusTimer = new Timer();
private bool m_containsFocus = true;
m_checkContainsFocusTimer.Interval = 1000; // every second is good enough
m_checkContainsFocusTimer.Tick += new EventHandler(CheckContainsFocusTimer_Tick);
m_checkContainsFocusTimer.Start();
private void CheckContainsFocusTimer_Tick(object sender, EventArgs e)
{
if (!m_containsFocus && ContainsFocus)
OnAppGotFocus();
m_containsFocus = ContainsFocus;
}
But is there an easier way?
Handling the GotFocus and LostFocus events should do it.
Another thing to note... the SDK says this about the ContainsFocus property:
You can use this property to determine
whether a control or any of the
controls contained within it has the
input focus. To determine whether the
control has focus, regardless of
whether any of its child controls have
focus, use the Focused property.
EDIT:
When handling the GotFocus event, you may still have to check the Focused/ContainsFocus property depending on how the hierarchy of your controls is set up.
ContainsFocus will be true if the control or any of its children have focus.
Focus will only be true if the specific control itself has focus, regardless of its children.
Related
I have 18 buttons on the child form "Control Test" which send event to the parent form
Out of 18 buttons, 14 are ON and OFF functionality, making 7 pairs as in the picture
The problem is raising the event for each button, it causes very long and messy code, both in the child and the parent form,
Is there any less complex way to do it? like I have done with the menu.
Child Form:
Child Form:
// B Plus Relay On Button
public event EventHandler BPRElayOnBtnClicked;
protected virtual void WhenBPRelayOnBtnClicked(EventArgs e)
{
BPRElayOnBtnClicked.Invoke(this, e);
}
private void BPRelayOn_btn_Click(object sender, EventArgs e)
{
WhenBPRelayOnBtnClicked(e);
}
// B Plus Relay OFF Button
public event EventHandler BPRElayOffBtnClicked;
protected virtual void WhenBPRelayOffBtnClicked(EventArgs e)
{
BPRElayOnBtnClicked.Invoke(this, e);
}
private void BPRelayOff_btn_Click(object sender, EventArgs e)
{
WhenBPRelayOffBtnClicked(e);
}
// B Minus Relay ON Button
public event EventHandler BMRElayOnBtnClicked;
protected virtual void WhenBMRelayOnBtnClicked(EventArgs e)
{
BMRElayOnBtnClicked.Invoke(this, e);
}
private void BMRelayOn_btn_Click(object sender, EventArgs e)
{
WhenBMRelayOnBtnClicked(e);
}
// B Minus Relay OFF Button
public event EventHandler BMRElayOffBtnClicked;
protected virtual void WhenBMRelayOffBtnClicked(EventArgs e)
{
BMRElayOffBtnClicked.Invoke(this, e);
}
private void BMRelayOff_btn_Click(object sender, EventArgs e)
{
WhenBMRelayOffBtnClicked(e);
}
...... //event for each button
Parent Form:
private void viewToolStripMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menu = sender as ToolStripMenuItem;
switch (menu.Name)
{
case "controlTestToolStripMenuItem":
if (Application.OpenForms["CtrlTest"] is CtrlTest ctrlTest)
{
ctrlTest.Focus();
return;
}
ctrlTest = new CtrlTest();
ctrlTest.BPRElayOnBtnClicked += CtrlTest_BPRElayOnBtnClicked;
ctrlTest.BPRElayOffBtnClicked += CtrlTest_BPRElayOffBtnClicked;
ctrlTest.BMRElayOnBtnClicked += CtrlTest_BMRElayOnBtnClicked;
ctrlTest.BMRElayOffBtnClicked += CtrlTest_BMRElayOffBtnClicked;
ctrlTest.PreRElayOnBtnClicked += CtrlTest_PreRElayOnBtnClicked;
ctrlTest.PreRElayOffBtnClicked += CtrlTest_PreRElayOffBtnClicked;
ctrlTest.MdiParent = this;
ctrlTest.Show();
break;
.........//Other menus ...
default:
break;
private void CtrlTest_BPRElayOnBtnClicked(object sender, EventArgs e)
{
//Do something here
}
private void CtrlTest_BPRElayOffBtnClicked(object sender, EventArgs e)
{
//Do something here
}
private void CtrlTest_BMRElayOnBtnClicked(object sender, EventArgs e)
{
//Do something here
}
private void CtrlTest_BMRElayOffBtnClicked(object sender, EventArgs e)
{
//Do something here
}
For the on/off, take a look at the following control. For the others setup one event and work out logic similar to the on/off buttons.
Download the source, add the class project to your Visual Studio solution. Open the class project and change the .NET Framework currently set to 4, to your project's .NET Framework version.
Setup an enum where for each on/off button set it's tag to one of the members. this ways things are clearer using a switch and enums.
public enum OperationType
{
BPlusRelay,
BMinusRelay,
PreRelay,
CycleCount,
PairDown,
TestMode,
StandbyMode
}
In the child form, setup and event and set tags for each on/off control. Change the names to reflect their purpose, I simply added them quickly for demoing purposes.
public partial class ChildForm : Form
{
public delegate void OnClicked(OperationType operationType, bool state);
public event OnClicked ClickedEvent;
public ChildForm()
{
InitializeComponent();
SetProperties();
}
public void SetProperties()
{
ToggleSwitch1.Tag = OperationType.BPlusRelay;
ToggleSwitch2.Tag = OperationType.BMinusRelay;
ToggleSwitch3.Tag = OperationType.PreRelay;
ToggleSwitch4.Tag = OperationType.CycleCount;
ToggleSwitch5.Tag = OperationType.PairDown;
ToggleSwitch6.Tag = OperationType.TestMode;
ToggleSwitch7.Tag = OperationType.StandbyMode;
var list = Controls.OfType<JCS.ToggleSwitch>().ToList();
foreach (var toggleSwitch in list)
{
toggleSwitch.CheckedChanged += ToggleSwitchOnCheckedChanged;
}
}
private void ToggleSwitchOnCheckedChanged(object sender, EventArgs e)
{
var current = (JCS.ToggleSwitch)sender;
ClickedEvent?.Invoke((OperationType)current.Tag, current.Checked);
}
}
In the main form, show the child form, subscribe to the event above.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void ShowChildFormButton_Click(object sender, EventArgs e)
{
var childForm = new ChildForm();
childForm.ClickedEvent += ClickedEvent;
try
{
childForm.ShowDialog();
}
finally
{
childForm.Dispose();
}
}
private void ClickedEvent(OperationType operationType, bool state)
{
switch (operationType)
{
case OperationType.BPlusRelay:
// TODO
break;
case OperationType.BMinusRelay:
// TODO
break;
case OperationType.PreRelay:
// TODO
break;
case OperationType.CycleCount:
// TODO
break;
case OperationType.PairDown:
// TODO
break;
case OperationType.TestMode:
// TODO
break;
case OperationType.StandbyMode:
// TODO
break;
}
}
}
Partly done form, and note you can change the size of the buttons.
I'd like the activated event to only run once. I've tried using an If condition but the Reload variable doesn't set to false and thus it keeps looping endlessly. Is there a way around this?
Form1.cs code:
private void Form1_Activated(object sender, EventArgs e)
{
if (Class1.Reload == true) {
Class1.Reload = false;
}
}
Class1.cs code:
public class Class1 {
public static void Refresh() { Reload = true; }
public static bool Reload { get; set; }
Just unsubscribe from the event the first time it is triggered.
private void Form1_Activated(object sender, EventArgs e)
{
this.Activated -= Form1_Activated;
// Do other stuff here.
}
While CathalMF's solution is valid, I'll post the solution I implemented, whose aim was to refresh a DatagridView when I come back to the main form.
private void Form1_Activated(object sender, EventArgs e) {
if (Class1.Reload == true) {
Activated -= Form1_Activated;
Class1.Reload = false;
//Here I implement the code to refresh a DatagridView
Activated += Form1_Activated;
}
}
Class1.cs stays the same.
Let's assume the following Situation:
a Control (e.g. a Button) has an attached behavior to enable a Drag&Drop-Operation
<Button Content="test">
<i:Interaction.Behaviors>
<SimpleDragBehavior/>
</i:Interaction.Behaviors>
</Button>
And the SimpleDragBehavior
public class SimpleDragBehavior: Behavior<Button>
{
protected override void OnAttached ()
{
AssociatedObject.MouseLeftButtonDown += OnAssociatedObjectMouseLeftButtonDown;
AssociatedObject.MouseLeftButtonUp += OnAssociatedObjectMouseLeftButtonUp;
AssociatedObject.MouseMove += OnAssociatedObjectMouseMove;
mouseIsDown = false;
}
private bool mouseIsDown;
private void OnAssociatedObjectMouseMove (object sender, MouseEventArgs e)
{
if (mouseIsDown)
{
AssociatedObject.Background = new SolidColorBrush(Colors.Red);
DragDrop.DoDragDrop((DependencyObject)sender,
AssociatedObject.Content,
DragDropEffects.Link);
}
}
private void OnAssociatedObjectMouseLeftButtonUp (object sender, MouseButtonEventArgs e)
{
mouseIsDown = false;
}
private void OnAssociatedObjectMouseLeftButtonDown (object sender, MouseButtonEventArgs e)
{
mouseIsDown = true;
}
}
The task now is to determine when the drag ends, to restore the orignal backgound of the button.
This is no problem when droped on an drop-target. But how do i recognize a drop on something which isn't a drop-target? In the worst case: outside the window?
DragDrop.DoDragDrop returns after drag-and-drop operation is completed.
Yes, "Initiates a drag-and-drop operation" is confusing, since it could be read as "start drag-and-drop and return":
private void OnAssociatedObjectMouseMove (object sender, MouseEventArgs e)
{
if (mouseIsDown)
{
AssociatedObject.Background = new SolidColorBrush(Colors.Red);
var effects = DragDrop.DoDragDrop((DependencyObject)sender,
AssociatedObject.Content,
DragDropEffects.Link);
// this line will be executed, when drag/drop will complete:
AssociatedObject.Background = //restore color here;
if (effects == DragDropEffects.None)
{
// nothing was dragged
}
else
{
// inspect operation result here
}
}
}
I have a class (which extends Framework Element) which contains within it a number of other Elements.
// Click event coverage area
private Rectangle connectorRectangle;
These shapes all have their event handlers, and when the user clicks on them its working well. Now what I want is to be able to 'handle' a right-click on my class from outside the scope of the class.
So I figured the best way to do it is to handle the event internally, and somehow bubble it to the top
private void connectorRectangle_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
MouseButtonEventArgs args = new MouseButtonEventArgs();
//???
e.Handled = true;
}
The problem is that I have no idea how to raise the event. this.OnMouseRightButtonUp doesn't exist, and all the tutorials I'm finding are for raising custom events.
I'm pretty new to silverlight, so bear with me if I missed something obvious.
Try it :
public Rectangle
{
this.Click += new System.EventHandler(Function);
}
private void Function(object sender, System.EventArgs e)
{
if (((MouseEventArgs)e).Button == MouseButtons.Right)
{
//Your code
}
}
Your "exteded Framework Element class" shouldn't handel the mouse event (or if they handel them, set e.Handled to false). Then the event should bubble up automatically (without reraise the event).
EDIT
public class ExtendedFrameworkElement : Grid
{
public ExtendedFrameworkElement()
{
Border b1 = new Border();
b1.Padding = new Thickness(20);
b1.Background = Brushes.Red;
b1.MouseRightButtonUp += b1_MouseRightButtonUp;
Border b2 = new Border();
b2.Padding = new Thickness(20);
b2.Background = Brushes.Green;
b2.MouseRightButtonUp += b2_MouseRightButtonUp;
b1.Child = b2;
this.Children.Add(b1);
}
private void b1_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//DoSomeThing
e.Handled = false;
}
private void b2_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//DoSomeThing
e.Handled = false;
}
}
Xaml:
<Window x:Class="WpfApplicationTest.MainWindow">
<wpfApplicationTest:ExtendedFrameworkElement MouseRightButtonUp="UIElement_OnMouseRightButtonUp"/>
</Window>
Code Behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void UIElement_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
//DoSomeThing
}
}
In my User Control I have a Text Box which does the validation to take only digits. I place this user control on my form but the Keypress event is not Firing in form.Following is the code in my user control
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (this.KeyPress != null)
this.KeyPress(this, e);
}
private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar!=(char)Keys.Back)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
but in Form also i want keypress event to fire but it is not firing
public Form1()
{
InitializeComponent();
txtNum.KeyPress += new KeyPressEventHandler(txtPrprCase1_KeyPress);
}
void txtPrprCase1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("KeyPress is fired");
}
but it is not firing. I don't understand what i want to do? It is Urgent for me.
This following override is not needed:
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (this.KeyPress != null)
this.KeyPress(this, e);
}
Because base.OnKeyPress(e); will fire the attached event. You don't need to do it manually.
Instead call OnKeyPress of user control in the text-box's event handler:
private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (e.KeyChar!=(char)Keys.Back)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
Try putting the event handler code in your Form_Load event, or using the Form Designer to create the event handler (it's in the lightning icon on the properties page).