TreeNode click vs TreeView click - c#

I have a TreeView and I need two things.
A Right-Click support if I click on a specific node.
A Right-Click support if I click anywhere else on the tree (where there is no nodes).
The two options would both give me a different ContextMenuStrip.
My two program now supports both type of clicks like this.
Specific Node click :
var someNode = e.Node.Tag as SomeNode;
if (someNode != null)
{
someContextMenu.Show(someTree, e.Location);
return;
}
Anywhere on the tree click :
The problem is that the Anywhere on the tree click event will fire before checking if I clicked on the node or on a blank spot from the TreeView.
Any Idea how I could change that behaviour ?

Assuming you are asking about winforms.
You can use the TreeView.HitTest method which return a TreeViewHitTestInfo where you can know if you hit a node or not.

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
TreeViewHitTestInfo info = treeView1.HitTest(e.Location);
treeView1.SelectedNode = info.Node;
if (info.Node == null)
{
contextMenuStrip1.Show(Cursor.Position);
}
else
{
contextMenuStrip2.Show(Cursor.Position);
}
}
}
Or the mouse up event depending on your needs. Also you can use GetNodeAt(e.Location) instead of the TreeViewHitTestInfo class.

Related

Choosing an MSChart-Extension tool from button click

I am using MSChart-Extensions and I would like the option to choose the Zoom, Pan and Select tools from a button, as well as from the ContextMenuStrip. I feel like the easiest way is to simulate a click from the ContextMenuStrip.Items collection
Here is what I've got. In my form I have this
private void zoomButton_Click(object sender, EventArgs e)
{
this.chart.ChangeTool("Zoom");
}
And in MSChartExtensions.cs I have this
public static void ChangeTool(this Chart sender, string option)
{
Chart chart = sender;
foreach(ToolStripItem item in chart.ContextMenuStrip.Items)
{
if (item.Text == option)
{
item.PerformClick();
break;
}
}
}
This successfully chooses the tool from the collection. However, I am getting a System.ArgumentNullException in the SetChartControlState method. I have stepped through the code and I see that when the application enters ChartContext_ItemClicked, the sender's source control is null. I've dug through MSDN, and found this
A Control that represents the control that is displaying the shortcut menu. If no control has displayed the shortcut menu, the property returns a null reference (Nothing in Visual Basic).
So I assume that because no right-click menu (ContextMenuStrip) is shown, the source control is null. Is there a way around this? How can I get this working? Thanks for the help
I figured it out. Change the ChangeTools() method to this
// In MSChartExtensions.cs
public static void ChangeTool(this Chart sender, string option)
{
if (option == "Zoom")
SetChartControlState(sender, MSChartExtensionToolState.Zoom);
else if (option == "Select")
SetChartControlState(sender, MSChartExtensionToolState.Select);
else if (option == "Pan")
SetChartControlState(sender, MSChartExtensionToolState.Pan);
else if (option == "Zoom Out")
{
Chart ptrChart = sender;
WindowMessagesNativeMethods.SuspendDrawing(ptrChart);
ptrChart.ChartAreas[0].AxisX.ScaleView.ZoomReset();
ptrChart.ChartAreas[0].AxisY.ScaleView.ZoomReset();
ptrChart.ChartAreas[0].AxisY2.ScaleView.ZoomReset();
WindowMessagesNativeMethods.ResumeDrawing(ptrChart);
}
}
And then call this method like how I did in the question
// In the form
private void zoomButton_Click(object sender, EventArgs e)
{
this.chart.ChangeTool("Zoom"); // As an example
}
If anyone has a better way of doing this, feel free to let me know

Right click select on .Net TreeNode

I am trying to show a popup menu on my treeview when users right click - allowing them to choose context sensitive actions to apply against the selected node.
At the moment the user has to left click node and then right click to choose.
Is it possible to make a right click on a node select that node - and if so what is the best method to do this.
Both left and right clicks fire a click event and cause the selection to change. However, in certain circumstances (that I haven't yet bothered to trace down) the selection will change from the node that was right clicked to the originally selected node.
In order to make sure that the right click changes the selection, you can forcibly change the selected node by using the MouseDown event:
treeView.MouseDown += (sender, args) =>
treeView.SelectedNode = treeView.GetNodeAt(args.X, args.Y);
A little better, as one of the other posters pointed out, is to use the NodeMouseClick event:
treeView.NodeMouseClick += (sender, args) => treeView.SelectedNode = args.Node;
yes. Here is processing for NodeMouseClick event:
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
treeView1.SelectedNode = e.Node;
}
Drag a context menu strip onto the form then:
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
// Display context menu for eg:
ContextMenu1.Show();
}
}

C# Listbox Item Double Click Event

I have a list box with some items. Is there anyway I can attach a double click event to each item?
Item 1
Item 2
Item 3
If i was to double click Item 2, a Messagebox saying "Item 2" would pop up
How would i do this?
void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
int index = this.listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
MessageBox.Show(index.ToString());
}
}
This should work...check
WinForms
Add an event handler for the Control.DoubleClick event for your ListBox, and in that event handler open up a MessageBox displaying the selected item.
E.g.:
private void ListBox1_DoubleClick(object sender, EventArgs e)
{
if (ListBox1.SelectedItem != null)
{
MessageBox.Show(ListBox1.SelectedItem.ToString());
}
}
Where ListBox1 is the name of your ListBox.
Note that you would assign the event handler like this:
ListBox1.DoubleClick += new EventHandler(ListBox1_DoubleClick);
WPF
Pretty much the same as above, but you'd use the MouseDoubleClick event instead:
ListBox1.MouseDoubleClick += new RoutedEventHandler(ListBox1_MouseDoubleClick);
And the event handler:
private void ListBox1_MouseDoubleClick(object sender, RoutedEventArgs e)
{
if (ListBox1.SelectedItem != null)
{
MessageBox.Show(ListBox1.SelectedItem.ToString());
}
}
Edit: Sisya's answer checks to see if the double-click occurred over an item, which would need to be incorporated into this code to fix the issue mentioned in the comments (MessageBox shown if ListBox is double-clicked while an item is selected, but not clicked over an item).
Hope this helps!
I know this question is quite old, but I was looking for a solution to this problem too. The accepted solution is for WinForms not WPF which I think many who come here are looking for.
For anyone looking for a WPF solution, here is a great approach (via Oskar's answer here):
private void myListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DependencyObject obj = (DependencyObject)e.OriginalSource;
while (obj != null && obj != myListBox)
{
if (obj.GetType() == typeof(ListBoxItem))
{
// Do something
break;
}
obj = VisualTreeHelper.GetParent(obj);
}
}
Basically, you walk up the VisualTree until you've either found a parent item that is a ListBoxItem, or you ascend up to the actual ListBox (and therefore did not click a ListBoxItem).
For Winforms
private void listBox1_DoubleClick(object sender, MouseEventArgs e)
{
int index = this.listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
MessageBox.Show(listBox1.SelectedItem.ToString());
}
}
and
public Form()
{
InitializeComponent();
listBox1.MouseDoubleClick += new MouseEventHandler(listBox1_DoubleClick);
}
that should also, prevent for the event firing if you select an item then click on a blank area.
It depends whether you ListBox object of the System.Windows.Forms.ListBox class, which does have the ListBox.IndexFromPoint() method. But if the ListBox object is from the System.Windows.Control.Listbox class, the answer from #dark-knight (marked as correct answer) does not work.
Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI.
See also: WPF vs Windows Form
This is very old post but if anyone ran into similar problem and need quick answer:
To capture if a ListBox item is clicked use MouseDown event.
To capture if an item is clicked rather than empty space in list box check if listBox1.IndexFromPoint(new Point(e.X,e.Y))>=0
To capture doubleclick event check if e.Clicks == 2
The post is old but there is a simple solution for those who need it
private void listBox1_DoubleClick(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
MessageBox.Show(listBox1.Items[listBox1.SelectedIndex].ToString());
}
}

How to hide the tool tips

I am having a treeview with some nodes. I am also having a panel. I have taken some usercontrol forms and i will load those usercontrols when corresponding node is selected from the child hood. Now what i need is have some validations like if i left the text box empty i will have some tooltips displayed to the user. Suppose if i click on first node i will have a user control loaded. With out giving any values if i hit ok i will have some tool tips as follows
Now if i select the second node from the tree still the tooltips getting displayed i would like to hide those
Any Help please
my code for rasing error tooltips is as shown below
public class TestClass
{
public void RequiredText(TextBox txtTemp, ToolTip newtoolTip)
{
if (txtTemp.Text != string.Empty)
{
txtTemp.BackColor = System.Drawing.Color.White;
newtoolTip.Hide(txtTemp);
}
else
{
txtTemp.BackColor = System.Drawing.Color.Tomato;
newtoolTip.Show("Required", txtTemp);
}
}
}
But this was done in the use control form.
I haven't yet mastered the art of reverse-engineering code from a screenshot. I'm guessing that you don't dispose the previous user control when you select a new one. Allowing the tool tip to stay visible. Use code like this:
private UserControl currentView;
public void SelectView(UserControl view) {
if (currentView == view) return;
if (currentView != null) currentView.Dispose();
if (view != null) this.Controls.Add(view);
currentView = view;
}
And call SelectView() from the TreeView's AfterSelect event handler.
Have you tried the Hide method?
http://dotnetperls.com/tooltip
Got the answer just written Usrcntrl_Leave event for every user control as
private void usrcntrlPPD_Leave(object sender, EventArgs e)
{
this.Dispose();
}
This solved my problem :)
private void timer1(object sender, EventArgs e)
{
count++;
if (count == 2)
{
toolTMensaje.SetToolTip(textBox1,"");
toolTMensaje.Hide(textBox1);
count = 0;
timer1.Stop();
}
}

c# winforms context menu events problem

I added a context menu (add, cancel) to tree view dynamically. Now I want to show the selected tree node value when I click on context menu item click.
How can I do that?
I assume you want to know which node was right-clicked when the context menu is opened?
To determine this you can handle the mousedown event on the treeview and ensure the node you right-clicked is selected before the context menu is displayed.
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var node = treeView1.HitTest(e.X, e.Y).Node;
treeView1.SelectedNode = node;
}
}
In the ToolStripMenuItem's click handler you can check treeView1.SelectedNode, it will be null if the user right clicked the treeview outside a node.
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
if (treeView1.SelectedNode != null) MessageBox.Show("Node selected: " + treeView1.SelectedNode.Text);
}
I assume you just need to know the text of the treenode? This code should do the job
string treeNodeText = this.treeView1.SelectedNode.Text;

Categories