Winforms list display options? - c#

I am building a WinForms program that connects to a DB. On one form I want to display a list of elements recovered from the DB. The elements have to be clickable (radio buttons are an option here), and must have a hover option, as I want some info to appear in a textbox when mouse is hovered over a specific item.
I cannot find an adequate ToolBox control for this. Has anyone got some suggestions? I am using VS2010.
Thanks.

There is no such ready-to-use control in .net framework instead you have to design/create your own using Window custom controls.

Using a standard ListBox, you can just track the mouse position with the MouseMove event.
Example:
int _HoverIndex = -1;
private void listBox1_MouseMove(object sender, MouseEventArgs e) {
int index = listBox1.IndexFromPoint(e.Location);
if (index != _HoverIndex) {
_HoverIndex = index;
if (_HoverIndex == -1)
textBox1.Text = string.Empty;
else
textBox1.Text = listBox1.Items[_HoverIndex].ToString();
}
}
private void listBox1_MouseLeave(object sender, EventArgs e) {
_HoverIndex = -1;
textBox1.Text = string.Empty;
}

Related

Getting a control name/Displaying tooltip text

I am developing a form with multiple options that simulates a signup form, and I want to display some tips and descriptions in a RichTextBox located by the options when the user's mouse hover by it's GroupBoxes.
Since I am fairly new to programming, I don't know if getting all the controls names one by one is the optimal, so I want to grab the controls' names inside of the tabControl control that I am using to organize everything.
private void TabControl1_MouseHover(object sender, EventArgs e)
{
foreach(Control c in this.Controls)
{
string name = c.Name;
TooltipText(name);
}
}
And I also have a method where I will write the text that will be displayed in the RichTextBox.
private string TooltipText(string name)
{
if(name == "Name:")
{
return "blabla";
}
else
{
return "none";
}
}
I've tried a generic method to show a message box if the control was detected and, as I suspected, nothing showed up:
private void TooltipText(string name)
{
if(name == "LBL_Name")
{
MessageBox.Show("hey");
return;
}
}
How can I properly detect the Groupboxes or other types of Controls inside of the TabControl control, and also display the text in the box beside it?
You don't have to create your own Tool Tips. The .net WinForms provides a ToolTip class. https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.tooltip?view=netframework-4.8
I added 2 radio buttons to a group box in design view.
Try it and see.
private void Form1_Load(object sender, EventArgs e)
{
ToolTip tip = new ToolTip();
tip.AutoPopDelay = 5000;
tip.InitialDelay = 1000;
tip.ReshowDelay = 500;
tip.SetToolTip(radioButton1, "Choose to Add Onions");
tip.SetToolTip(radioButton2, "Choose to Add Pickles");
}

How to change selection of richtextbox from another form in C#?

I am trying to implement Notepad application clone in C#. Now I have a smaller problem in implementation. In a notepad application for implementing find next option, I created a new form which will have a reference to the main form. When Find Next button is clicked on the find form, I will use the richtextbox content in the mainform, current cursor position,direction of search, search string and matchcase to calculate selectionstart for the richtextbox and then update the selection. Now the calculation of selectionstart is working fine. I can get the length of selection from the search string and set selection. I am trying to set selection on the main form by using the reference I passed to the find form. When I do that, richtextbox won't highlight unless I BringToFront the mainForm or close the find form window. So my question is how to achieve selection of contents of richtextbox from another form(child form) just as implemented in windows notepad?
Code snippets:
FormFind.cs
private void btnFindNext_Click(object sender, EventArgs e)
{
qry.SearchString = txtFind.Text;
qry.Direction = oUp.Checked ? "UP" : "DOWN";
qry.MatchCase = chkMatchCase.Checked ? true : false;
qry.Content = mainForm.GetContent();
qry.Position = mainForm.GetCurrentCursorPosition();
FindNextResult result=editOperation.FindNext(qry);
if (result.SearchStatus)
mainForm.SetSelection(result.SelectionStart,
txtFind.Text.Length);
}
MainForm.cs
private void findEditMenu_Click(object sender, EventArgs e)
{
if (formFind == null)
formFind = new FormFind(this);
formFind.Show();
}
public string GetContent()
{
return txtArea.Text.ToString();
}
internal void SetSelection(int selectionStart, int length)
{
txtArea.SelectionStart=selectionStart;
txtArea.SelectionLength = length;
this.BringToFront();
}
internal int GetCurrentCursorPosition()
{
return txtArea.SelectionStart;
}

Keeping a listBox's selectedIndex updated while navigating with keyboard

I have this code:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (listBox1.SelectedItem != null)
{
item = listBox1.SelectedItem.ToString();
}
}
Then in the Load event of the Form where the listBox1 is on in the designer I did:
private void NewForm_Load(object sender, EventArgs e)
{
this.Size = new Size(416, 506);
this.Location = new Point(23, 258);
listBoxIndexs();
this.listBox1.SelectedIndex = 0;
}
listBoxIndexs() is:
private void listBoxIndexs()
{
for (int i = 0; i < Form1.test.Count; i++)
{
listBox1.Items.Add(Form1.test[i]);
}
}
In the Load event, I did:
this.listBox1.SelectedIndex = 0;
So when I make Show to this Form i see the listBox when index 0 is already selected.
The problem is when im using my keys arrows up and down to move between the items i see only the Frame around the items moving up down the selectedIndex is all the time keep on 0.
How can i fix it?
I tried to add after the this.listBox1.SelectedIndex = 0; also listBox1.Select(); but it didn't help.
I'm using visual studio c# 2010 pro .net 4 Client Profile.
Make sure your ListBox.SelectionMode is set to One.
If it is set to MultiSimple or MultiExtended, selections will only occur when the user uses the spacebar or the mouse button to select the item. The arrow keys in these modes just moves the selection marquee.

Multiselect picture gallery with winforms c#

I'm trying to create a multiselect picturegallery with winforms.
Currently I have created a flowcontrolpanel that adds images as a selectablepicturebox control.
The selectablepicturebox control is a customer usercontrol that is a blank control with a picturebox and a checkbox on the top right of the picturebox. The picturebox is slightly smaller and centered in the usercontrol.
Clicking on the selectablepicturebox control will turn the background on and off indication selection.
What I want to be able to do is to select a bunch of selectablepicturebox controls and be able to capture the spacebar event to check and uncheck the checkboxes in the selected controls.
The problem is that the flowlayoutpanel never knows to capture the spacebar event.
Does anyone know away of doing this or another technology? I'm happy to use any .net based tech.
Thanks
EDIT:
Here is a link to the code
Are you trying the KeyDown event ?
As per MSDN, This member is not meaningful for this control.
Read here & here. Instead, you may try PreviewKeyDown
Solution: [The GitHub codebase]
[Code Changes]
1. SelectablePictureBox.cs - NOTE the Set Focus
public void SetToSelected()
{
SelectedCheckBox.Checked = true;
PictureHolder.Focus();
}
private void PictureHolder_Click(object sender, EventArgs e)
{
BackColor = BackColor == Color.Black ? Color.Transparent : Color.Black;
// TODO: Implement multi select features;
if ((Control.ModifierKeys & Keys.Shift) != 0)
{
// Set the end selection index.
}
else
{
// Set the start selection index.
}
PictureHolder.Focus();
}
// subscribe to picture box's PreviewKeyDown & expose a public event
public event PreviewKeyDownEventHandler OnPicBoxKeyDown;
private void OnPicBoxPrevKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (OnPicBoxKeyDown != null)
{
OnPicBoxKeyDown(sender, e);
}
}
[Code Changes]
1. FormMain.cs
private void FormMain_Load(object sender, EventArgs e)
{
SensitiveInformation sensitiveInformation = new SensitiveInformation();
int index = 0;
//foreach (var photo in Flickr.LoadLatestPhotos(sensitiveInformation.ScreenName))
for (int i = 0; i < 10; i++)
{
SelectablePictureBox pictureBox = new SelectablePictureBox(index);
// subscribe to picture box's event
pictureBox.OnPicBoxKeyDown += new PreviewKeyDownEventHandler(pictureBox_OnPicBoxKeyDown);
PictureGallery.Controls.Add(pictureBox);
index++;
}
}
// this code does the selection. Query the FLowLayout control which is the 1st one and select all the selected ones
void pictureBox_OnPicBoxKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode != Keys.Space) return;
foreach (SelectablePictureBox item in Controls[0].Controls)
{
if (item.IsHighlighted)
{
item.SetToSelected();
}
}
}

Displaying tooltip on mouse hover of a text

I want to display a tooltip when the mouse hovers over a link in my custom rich edit control. Consider the following text:
We all sleep at night .
In my case the word sleep is a link.
When the user moves the mouse under the link, in this case "sleep", I want to display a tooltip for the link.
The following came to my mind, but they are not working
1) Trapping OnMouseHover
if(this.Cursor == Cursors.Hand)
tooltip.Show(textbox,"My tooltip");
else
tooltip.Hide(textbox);
But this does not work out.
UPDATE
The links mentioned are not URLs, i.e these are custom links, so Regex won't be of much help here, it can be any text. The user can choose to create it a a link.
Though I have not tried GetPosition method, I dont think it would be that elegant in terms of design and maintenance.
Let me say I have the following line, in my richedit box
We sleep at night. But the bats stay awake. Cockroaches become active at night.
In the above sentence, I want three different tooltips, when the mouse hovers over them.
sleep -> Human beings
awake -> Nightwatchman here
active -> My day begins
I trapped OnMouseMove as follows:
Working- with Messagebox
OnMouseMove( )
{
// check to see if the cursor is over a link
// though this is not the correct approach, I am worried why does not a tooltip show up
if(this.Cursor.current == Cursors.hand )
{
Messagebox.show("you are under a link");
}
}
Not Working - with Tooltip - Tooltip does not show up
OnMouseMove( MouseventArgs e )
{
if(cursor.current == cursors.hand )
{
tooltip.show(richeditbox,e.x,e.y,1000);
}
}
Just add ToolTip tool from toolbox to the form and add this code in a mousemove event of any control you want to make the tooltip start on its mousemove
private void textBox3_MouseMove(object sender, MouseEventArgs e)
{
toolTip1.SetToolTip(textBox3,"Tooltip text"); // you can change the first parameter (textbox3) on any control you wanna focus
}
hope it helps
peace
Well, take a look, this works, If you have problems please tell me:
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
ToolTip tip = new ToolTip();
void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
if (!timer1.Enabled)
{
string link = GetWord(richTextBox1.Text, richTextBox1.GetCharIndexFromPosition(e.Location));
//Checks whether the current word i a URL, change the regex to whatever you want, I found it on www.regexlib.com.
//you could also check if current word is bold, underlined etc. but I didn't dig into it.
if (System.Text.RegularExpressions.Regex.IsMatch(link, #"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$"))
{
tip.ToolTipTitle = link;
Point p = richTextBox1.Location;
tip.Show(link, this, p.X + e.X,
p.Y + e.Y + 32, //You can change it (the 35) to the tooltip's height - controls the tooltips position.
1000);
timer1.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e) //The timer is to control the tooltip, it shouldn't redraw on each mouse move.
{
timer1.Enabled = false;
}
public static string GetWord(string input, int position) //Extracts the whole word the mouse is currently focused on.
{
char s = input[position];
int sp1 = 0, sp2 = input.Length;
for (int i = position; i > 0; i--)
{
char ch = input[i];
if (ch == ' ' || ch == '\n')
{
sp1 = i;
break;
}
}
for (int i = position; i < input.Length; i++)
{
char ch = input[i];
if (ch == ' ' || ch == '\n')
{
sp2 = i;
break;
}
}
return input.Substring(sp1, sp2 - sp1).Replace("\n", "");
}
}
}
You shouldn't use the control private tooltip, but the form one. This example works well:
public partial class Form1 : Form
{
private System.Windows.Forms.ToolTip toolTip1;
public Form1()
{
InitializeComponent();
this.components = new System.ComponentModel.Container();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
MyRitchTextBox myRTB = new MyRitchTextBox();
this.Controls.Add(myRTB);
myRTB.Location = new Point(10, 10);
myRTB.MouseEnter += new EventHandler(myRTB_MouseEnter);
myRTB.MouseLeave += new EventHandler(myRTB_MouseLeave);
}
void myRTB_MouseEnter(object sender, EventArgs e)
{
MyRitchTextBox rtb = (sender as MyRitchTextBox);
if (rtb != null)
{
this.toolTip1.Show("Hello!!!", rtb);
}
}
void myRTB_MouseLeave(object sender, EventArgs e)
{
MyRitchTextBox rtb = (sender as MyRitchTextBox);
if (rtb != null)
{
this.toolTip1.Hide(rtb);
}
}
public class MyRitchTextBox : RichTextBox
{
}
}
This is not elegant, but you might be able to use the RichTextBox.GetCharIndexFromPosition method to return to you the index of the character that the mouse is currently over, and then use that index to figure out if it's over a link, hotspot, or any other special area. If it is, show your tooltip (and you'd probably want to pass the mouse coordinates into the tooltip's Show method, instead of just passing in the textbox, so that the tooltip can be positioned next to the link).
Example here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.getcharindexfromposition(VS.80).aspx
Use:
ToolTip tip = new ToolTip();
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
Cursor a = System.Windows.Forms.Cursor.Current;
if (a == Cursors.Hand)
{
Point p = richTextBox1.Location;
tip.Show(
GetWord(richTextBox1.Text,
richTextBox1.GetCharIndexFromPosition(e.Location)),
this,
p.X + e.X,
p.Y + e.Y + 32,
1000);
}
}
Use the GetWord function from my other answer to get the hovered word.
Use timer logic to disable reshow the tooltip as in prev. example.
In this example right above, the tool tip shows the hovered word by checking the mouse pointer.
If this answer is still not what you are looking fo, please specify the condition that characterizes the word you want to use tooltip on.
If you want it for bolded word, please tell me.
I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
objfrmmain = new Frm_Main();
Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
Application.Run(objfrmmain);
}
so I solved this problem by puting following code in Fram_main_load event procedure like this
private void Frm_Main_Load(object sender, EventArgs e)
{
Program.Showtop();
}
If you are using RichTextBox control. You can simply define the ToolTip object and show the tool-tip as the text is selected by moving the mouse inside the RichTextBox control.
ToolTip m_ttInput = new ToolTip(); // define as member variable
private void rtbInput_SelectionChanged(object sender, EventArgs e)
{
if (rtbInput.SelectedText.Length > 0)
{
m_ttInput.Show(rtbInput.SelectedText.Length.ToString(), rtbInput, 1000);
}
}
For the sake of ease of use and understandability.
You can simply put a Tooltip anywhere on your form (from toolbox). You will then be given an options in the Properties of everything else in your form to determine what is displayed in that Tooltip (it reads something like "ToolTip on toolTip1"). Anytime you hover on an object, the text in that property will be displayed as a tooltip.
This does not cover custom on-the-fly tooltips like the original question is asking for. But I am leaving this here for others that do not need
As there is nothing in this question (but its age) that requires a solution in Windows.Forms, here is a way to do this in WPF in code-behind.
TextBlock tb = new TextBlock();
tb.Inlines.Add(new Run("Background indicates packet repeat status:"));
tb.Inlines.Add(new LineBreak());
tb.Inlines.Add(new LineBreak());
Run r = new Run("White");
r.Background = Brushes.White;
r.ToolTip = "This word has a White background";
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Identical Packet received at this time."));
tb.Inlines.Add(new LineBreak());
r = new Run("SkyBlue");
r.ToolTip = "This word has a SkyBlue background";
r.Background = new SolidColorBrush(Colors.SkyBlue);
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Original Packet received at this time."));
myControl.Content = tb;

Categories

Resources