MouseLeftButtonDown not recognized by a ListBox? - c#

I'm encountering a huge problem, I have tried everything I could, but I didn't find any solution.
I have a listBox, with a DataTemplate. I want to use the events MouseLeftButtonDown and MouseLeftButtonUp to check the item selected is the same the user clicked on.
The problem is the event MouseLeftButtonUp is recognized but not the event MouseLeftButtonDown.
Part of my XAML code :
<ListBox Grid.Row="1" MouseLeftButtonDown="listBox_Faits_MouseLeftButtonDown"
MouseLeftButtonUp="listBox_Faits_MouseLeftButtonUp">
The code behind :
private void listBox_Faits_MouseLeftButtonUp(object sender, MouseEventArgs e)
{
...
}
private void listBox_Faits_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
...
}
Is anyone know why ?
Thanks you,
Regards,
Flo

This happens because the MouseLeftButtonDown event is getting handled by the list box item. To handle already handled events you can subscribe to it in code-behind and specify that you want to handle handled events, like this:
listBox_Faits.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(listBox_Faits_MouseLeftButtonDown), true);

Related

What event should I use to something when I select any text in a RichTextBox in WinForms?

I want to perform some action when some text is selected from a RichTextBox. So in what event of the RichTextBox should I write my logic?
I'm designing a notepad. I have one Menustrip and in the Menustrip I have Copy, Paste, Undo and Redo option. I want these options to be visible to the users only when a user selects any text in the RichTextBox.
I've tried it in many events but haven't succeeded so far.
I've tried in RichTextBox the Mousecapturechanged event and Toolstripmenu menu active event.
I am using C#.
Kindly help.
The best solution would be to subscribe to the MouseUp event of the RichTextBox and within the event handler, check if the length of the selected text is greater than 0 like this:
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
if (richTextBox1.SelectedText.Length > 0)
{
// Show the Copy, Paste, Cut Buttons...
}
}
This is because the SelectionChanged event fires whenever the selection is changed and so will not even let you select text properly.
You can use SelectionChanged event and check if the cursor has changed or a part of text has been selected.
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
if (richTextBox1.SelectionLength < 2) return;
//Show the menu
}
You can use the SelectionChanged event which:
Occurs when the selection of text within the control has changed.
MSDN Link - RichTextBox.
This event would be ideal for what you aim to achieve.
Now you also need to use this properly. This event will fire even if you type something. So you have to verify that something is selected like this:
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
if (richTextBox1.SelectedText.Length > 1)
{
// Show the Copy, Paste, Cut Buttons...
}
}

Hyperlink events are not raised on first click if MousePreviewUp event is subscribed

I have loaded a TextBlock in a ContentControl and added a Hyperlink as an object in the Inlines collection in the TextBlock.
If I subscribe a handler to the ContentControl.PreviewMouseUp event which sets the ContentControl.Foreground property, the RequestNavigate and Click events are not raised the first time the link is clicked. If the link is clicked a second time, the events are raised.
Everything works fine if the event is not subscribed, or the handler does nothing.
Initialization code (in window constructor, after InitializeComponent()):
var run = new Run("Google");
Hyperlink hyperlink = new Hyperlink(run);
hyperlink.Click += hyperlink_Click;
hyperlink.RequestNavigate += hyper_RequestNavigate;
hyperlink.NavigateUri = new Uri("http://www.google.com");
textBlock.Inlines.Clear();
textBlock.Inlines.Add(hyperlink);
Event handlers as follows:
private void hyper_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(e.Uri.ToString());
}
void contentControl_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
contentControl.Foreground = Brushes.Green;
}
void hyperlink_Click(object sender, RoutedEventArgs e)
{
}
XAML as follows:
<Grid>
<ContentControl Name="contentControl">
<TextBlock Name="textBlock"
Width="200"
Height="30" />
</ContentControl>
</Grid>
Note: if the PreviewMouseUp handler is changed so that it always changes the color (e.g. create a bool that selects between two different colors and is toggled each time the handler is called), the events are never raised. E.g.:
private bool _toggle;
void contentControl_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
contentControl.Foreground = _toggle ? Brushes.Red : Brushes.Green;
_toggle = !_toggle;
}
Is there any way to have the PreviewMouseUp handler set the color but still have the RequestNavigate and Click events raised when the link is clicked the first time?
I don't know exactly what's going on here, but it's clear from the symptoms that there's something about changing the ContentControl.Foreground property that interrupts the normal handling of the mouse event. When you set the property value, this causes WPF to decide that the event should be ignore (maybe it treats the property change as an indication that the event has been handled), and so the events which would normally be raised later aren't in fact raised.
Given that, it seems to me that the most obvious work-around is to defer the change in the property value until after mouse event has in fact been completely handled, including raising those events. And the most obvious way I can think of to do that is to use the Dispatcher to invoke the operation later.
I.e. by using Dispatcher.InvokeAsync(), we can ensure that the handling of the mouse event itself is completely processed before the property change is done, because the dispatcher is busy dealing with the mouse event and won't be available to run the invoked delegate until it's finished with the mouse event.
That would look something like this:
void contentControl_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
Dispatcher.InvokeAsync(() =>
{
contentControl.Foreground = Brushes.Green;
});
}
If you change your PreviewMouseUp handler to the above, you should see that the events are raised even on the first mouse click.

Method for Focus Change

Is there a method which initiates on focus change and can be overridden?
My goal is for the program to fetch closest data automatically from database to input fields whenever user changes his focus/presses enter or tab when on corresponding field. I'm still looking for a way to do this when user selects an item by mouse.
I'm aware that this could be implemented on mouse click but I refuse to believe that there is not a general method for focus change.
What about something like this:
foreach(Control ctrl in this.Controls)
{
ctrl.Enter += new EventHandler(Focus_Changed); // Your method to fire
}
Iterate through all controls and add a enter-event. Bind this handler to your method.
Edit:
Just in case you are wondering why "Enter" and not "LostFocus" or something like that: From my knowledge not every control got focus-events. As I've seen so far "Enter" is presented for all. Maybe there are exceptions. Should be checked out...
You could use Control.Enter event and Control.Leave event for that purpose.
See on MSDN Control.Enter and
Control.Leave.
textBox1.Enter += textBox1_Enter;
textBox1.Leave += textBox1_Leave;
private void textBox1_Enter(object sender, System.EventArgs e)
{
// the control got focus
}
private void textBox1_Leave(object sender, System.EventArgs e)
{
// the control lost focus
}

Who handled my event

I have registered to a LostFocus event on a TextBox and yet the event is not catch - my guess is that someone else handled it.
I've tried using snoop but it only shows me the MouseDown and MouseUp events (and I need the LostFocus).
Any ideas on how can I find out?
Thanks
Update:
Not so clear but the code where I register is:
eventInfo.AddEventHandler(cloningObject, eventDelegate);
In the XAML, make sure you assign a name to your TextBox:
<TextBox Name="MyTextBox" />
Create a function in your code behind to handle the event:
public void MyLostFocusHandler(object sender, RoutedEventArgs e) {
// ...
}
And then in your window's constructor (assuming this is in a window):
MyTextBox.LostFocus += MyLostFocusHandler;
Note also there is another event, LostKeyboardFocus.

How to call an event handler from one control to the another control?

In Visual C# Form Application, When I Click on the button I want to add to the other controls(like listboxes,labels,textboxes) in same form.
How do I do this?
I have no idea what "to come to the other controls" might mean. But the event handlers in your Form derived class is the switchboard. Implement the button's Click event and have it do whatever you want done with any other controls. A trivial example:
private void button1_Click(object sender, EventArgs e) {
label1.Text = "You clicked the button!";
}
In the form designer, add an event handler to the button's Click event.
The form designer will give you a new method like this; add your code into this method:
private void button_Click(object sender, EventArgs e)
{
// Write some code that uses list boxes, labels, text boxes etc.
}
You question is somewhat unclear, but if you simply want to access other controls on the form, just go ahead and do so:
private void YourButton_Click(object sender, EventArgs e)
{
string someValue = yourTextBox.Text;
// do something with the value
}
If you want to add one event handler to many controls, you can do it.
Just go to properties of control you wish to subscribe, find appropriate event from list (ex: onClick) and choise your existed handler.
But this method will be sutable if events compotable.
Describe your task more detail.

Categories