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");
}
Similar questions have been already asked (e.g., here), however I've not found an answer for my specific case. I'm building a custom control based on a DevExpress control, which in turns is based on standard TextBox and I've a flickering problem that seems due to the base TextBox component, which tries to update selection.
Without explaining all the details of my custom control, to reproduce the problem you just need to place a TextBox inside a Form and then use this code:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
textBox1.MouseMove += TextBox1_MouseMove;
}
private void TextBox1_MouseMove(object sender, MouseEventArgs e) {
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
}
}
If you launch it, you click on the TextBox and then you move the cursor toward right you will notice the flickering problem (see video here). For my custom control I would need to avoid this flickering. I'm bound to use a TextBox (so no RichTextBox). Any idea?
The solution has been provided in the meantime by Reza Aghaei by overriding WndProc and intercepting WM_SETFOCUS messages. See here
Depending on what u want to do there are several solutions:
If you want to prevent the selection it would be:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectionLength = 0;
}
Or for selecting all:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectAll();
}
And besides that u also could specify the conditions for selecting, for example:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
if (MouseButtons == MouseButtons.Left) (sender as TextBox).SelectAll();
else (sender as TextBox).SelectionLength = 0;
}
But as long as you want to select the text you always will get some flickering, because a normal Textbox has not the possibility to use things like BeginEdit and EndEdit and so it will change the text first and then select it.
Looking at the video it looks like your textbox is calling WM_ERASEBKGND unnecessarily. In order to remedy this problem you can subclass the textbox class and intercept these messages. Below is sample code which should do the trick (untested) Disclaimer: I have used this technique for other WinForm controls that had the type of flicker shown in your video but not TextBox. If it does work for you, please let me know. Good luck!
// textbox no flicker
public partial class TexttBoxNF : TextBox
{
public TexttBoxNF()
{
}
public TexttBoxNF(IContainer container)
{
container.Add(this);
InitializeComponent();
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
//http://stackoverflow.com/questions/442817/c-sharp-flickering-listview-on-update
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}
first, I would like to apologize for my lack of knowledge, but I am new in C# and I am missing some basic principles.
Here is my current scenario:
In my scenario I create something like chess desk of pictureboxes. They are placed inside of control "Panel" in Winform form - panel is scrollable!
Each picture box has unique name like pbR1_C1 generated in constructor.
R - stands for Row on desk
C - Stands for Column on desk
All is made during runtime since the chess desk size is loaded after program starts. Used objects look like this:
/* Simple preview of object with public variables - just for preview */
public class ptFcElement
{
public string stName; /* "pbR1_C1", "pbR1_C2" */
public int iRow; /* 1 */
public int iColumn; /* 4 */
public PictureBox pbPictureBox; /* using System.Drawing;*/
public ptFcElement()
{
stName = sGenerateName();
}
}
Then I assign event handler for each picture box
ptFcElementTemp.pbPictureBox.MouseClick += new MouseEventHandler(MouseButton_Click);
At this point I am able to identify that I have pressed some picture box, but I don't know which one.
Here is the question:
Since panel is scrollable - I can not simple identify pressed picture box - it always calls the same function.
void MouseButton_Click(object sender, MouseEventArgs e)
{
//Do some stuff....
//In case panel is not scrollable,
//I can identify pressed picture box by coordinates of mouse click.
//But if panel is scrollable, I am screwed.
}
Desired idea:
Is there any possibility to extend MouseEventHandler event function? I know that simple classes are easily to extend, but I am not sure how to work with event functions.
ptFcElementTemp.pbPictureBox.MouseClick +=
new MouseEventHandler(MouseButton_Click, "pbR1_C1");
void MouseButton_Click(object sender, MouseEventArgs e, string sUniqueName)
{
//Here I am able to identify pressed bisturebox by sUniqueName
if (sUniqueName == "pbR1_C1")
{
//do something
}
if (sUniqueName == "pbR2_C3")
{
//do something different
}
}
Thank you, see you.
And please, explain it as easy as possible, for dummy. :-)
You could try it like this:
void MouseButton_Click(object sender, MouseEventArgs e)
{
var pb = sender as PictureBox;
if(pb!=null){
//Do something with the instance the PictureBox which fired the event
}
}
After discussion with Yacoub Massad I want to suggest you following enhancement:
Declare your own event, which you fire when the PictureBox is clicked.
public class ptFcElement {
public string stName; /* "pbR1_C1", "pbR1_C2" */
public int iRow; /* 1 */
public int iColumn; /* 4 */
public PictureBox pbPictureBox; /* using System.Drawing;*/
public event EventHandler PictureBoxWasClicked;
protected virtual void OnPictureBoxWasClicked(){
if (this.PictureBoxWasClicked != null)
this.PictureBoxWasClicked(this, new EventArgs());
}
public ptFcElement() {
stName = sGenerateName();
this.pbPictureBox.Click += pbPictureBox_Click;
}
private void pbPictureBox_Click(object sender, EventArgs e) {
this.OnPictureBoxWasClicked();
}
}
Outside you can react on this event instead of the PictureBox' Click-event. The "sender" will be the instance of your own class directly.
If you want you could even define an own EventArgs-class to pass what ever parameters you like...
As a direct answer to your question, you can do something like this:
ptFcElementTemp.pbPictureBox.MouseClick +=
(object sndr, MouseEventArgs m_args)
=> MouseButton_Click(sndr, m_args, "pbR1_C1");
You can pass whatever parameter that you want.
This is helpful if you want more context than just the PictureBox that was clicked since that object can be access using the sender parameter. For example, you might want to get access to the corresponding ptFcElement.
Basically you are trying to determine wich control was clicked? I hope that's what you're asking for.
The sender parameter contains your control.
For example:
if (sender==ptFcElementTemp.pbPictureBox){
//Do stuff
}
else if(sender==ptFcElementTemp.otherControl){
//Do other stuff
}
i'm new to C# i've been messing around to discover this language so far i've wrote many programs in my quest but now i'm stuck with one thing, i can't explain by words but codes can say what i want so here we go i know it's silly program but it's for education purpose only :D
Private void change()
{
anycontrol.BackColor = Color.Gold; // when this function called the control's BackColor will Change to gold
}
// example
private void TextBox1_Focused(object sender, EventArgs e)
{
Change(); // this suppose to change the color of the controls which is now textbox1 i want it to work on other controls such as buttons progressbars etc
}
now after i explained my problem i may ask you if you can to help it will be appreciated.
You can create a method that takes a Control and a Color as a parameter, and anything that inherits from Control (i.e. TextBox, DropDownList, Label etc.) will work with this:
void SetControlBackgroundColour(Control control, Color colour)
{
if (control != null)
{
control.BackColor = colour;
}
}
In your example, you could use it like this:
private void TextBox1_Focused(object sender, EventArgs e)
{
SetControlBackgroundColour(sender as Control, Color.Gold);
}
In response to the comments, you could then use this method in a recursive method that will set the background colour for each control on the form:
void SetControlBackgroundColourRecursive(Control parentControl, Color colour)
{
if (parentControl != null)
{
foreach (Control childControl in parentControl.Controls)
{
SetControlBackgroundColour(childControl, colour);
SetControlBackgroundColourRecursive(childControl);
}
}
}
And then call this function on your Form object (this) in your Form1_Load method (assuming the form is called Form1):
protected void Form1_Load(object sender, EventArgs e)
{
SetControlBackgroundColourRecursive(this, Color.Gold);
}
Is there a way to disable a tab in a TabControl?
Cast your TabPage to a Control, then set the Enabled property to false.
((Control)this.tabPage).Enabled = false;
Therefore, the tabpage's header will still be enabled but its contents will be disabled.
The TabPage class hides the Enabled property. That was intentional as there is an awkward UI design problem with it. The basic issue is that disabling the page does not also disable the tab. And if try to work around that by disabling the tab with the Selecting event then it does not work when the TabControl has only one page.
If these usability problems do not concern you then keep in mind that the property still works, it is merely hidden from IntelliSense. If the FUD is uncomfortable then you can simply do this:
public static void EnableTab(TabPage page, bool enable) {
foreach (Control ctl in page.Controls) ctl.Enabled = enable;
}
You can simply use:
tabPage.Enabled = false;
This property is not shown, but it works without any problems.
You can program the Selecting event on TabControler to make it impossible to change to a non-editable tab:
private void tabControler_Selecting(object sender, TabControlCancelEventArgs e)
{
if (e.TabPageIndex < 0) return;
e.Cancel = !e.TabPage.Enabled;
}
You could register the "Selecting" event and cancel the navigation to the tab page:
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
if (e.TabPage == tabPage2)
e.Cancel = true;
}
Another idea is to put all the controls on the tabpage in a Panel control and disable the panel! Smiley
You could also remove the tabpage from the tabControl1.TabPages collection. That would hide the tabpage.
Credits go to littleguru # Channel 9.
Presumably, you want to see the tab in the tab control, but you want it to be "disabled" (i.e., greyed, and unselectable). There is no built-in support for this, but you can override the drawing mechanism to give the desired effect.
An example of how to do this is provided here.
The magic is in this snippet from the presented source, and in the DisableTab_DrawItem method:
this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
this.tabControl1.DrawItem += new DrawItemEventHandler( DisableTab_DrawItem );
Extending upon Cédric Guillemette answer, after you disable the Control:
((Control)this.tabPage).Enabled = false;
...you may then handle the TabControl's Selecting event as:
private void tabControl_Selecting(object sender, TabControlCancelEventArgs e)
{
e.Cancel = !((Control)e.TabPage).Enabled;
}
This will remove the tab page, but you'll need to re-add it when you need it:
tabControl1.Controls.Remove(tabPage2);
If you are going to need it later, you might want to store it in a temporary tabpage before the remove and then re-add it when needed.
The only way is to catch the Selecting event and prevent a tab from being activated.
The most tricky way is to make its parent equals null (make the tab alone without parent):
tabPage.Parent = null;
And when you want to return it back (will return it back at the end of pages collection) :
tabPage.Parent = tabControl;
And if you want to return it back in a specific location among the pages you can use :
tabControl.TabPages.Insert(indexLocationYouWant, tabPage);
I had to handle this a while back. I removed the Tab from the TabPages collection (I think that's it) and added it back in when the conditions changed. But that was only in Winforms where I could keep the tab around until I needed it again.
I've removed tab pages in the past to prevent the user from clicking them. This probably isn't the best solution though because they may need to see that the tab page exists.
Using events, and the properties of the tab control you can enable/disable what you want when you want. I used one bool that is available to all methods in the mdi child form class where the tabControl is being used.
Remember the selecting event fires every time any tab is clicked. For large numbers of tabs a "CASE" might be easier to use than a bunch of ifs.
public partial class Form2 : Form
{
bool formComplete = false;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
formComplete = true;
tabControl1.SelectTab(1);
}
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages[1])
{
tabControl1.Enabled = false;
if (formComplete)
{
MessageBox.Show("You will be taken to next tab");
tabControl1.SelectTab(1);
}
else
{
MessageBox.Show("Try completing form first");
tabControl1.SelectTab(0);
}
tabControl1.Enabled = true;
}
}
}
I've solved this problem like this:
I've got 3 tabs and I want to keep user at the first tab if he didnt log in,
so on the SelectingEvent of TabControl I wrote
if (condition) { TabControl.Deselect("2ndPage"); TabControl.Deselect("3dPage"); }
The user cannot click on tabs to navigate, but they can use the two buttons (Next and Back). The user cannot continue to the next if the //conditions are no met.
private int currentTab = 0;
private void frmOneTimeEntry_Load(object sender, EventArgs e)
{
tabMenu.Selecting += new TabControlCancelEventHandler(tabMenu_Selecting);
}
private void tabMenu_Selecting(object sender, TabControlCancelEventArgs e)
{
tabMenu.SelectTab(currentTab);
}
private void btnNextStep_Click(object sender, EventArgs e)
{
switch(tabMenu.SelectedIndex)
{
case 0:
//if conditions met GoTo
case 2:
//if conditions met GoTo
case n:
//if conditions met GoTo
{
CanLeaveTab:
currentTab++;
tabMenu.SelectTab(tabMenu.SelectedIndex + 1);
if (tabMenu.SelectedIndex == 3)
btnNextStep.Enabled = false;
if (btnBackStep.Enabled == false)
btnBackStep.Enabled = true;
CannotLeaveTab:
;
}
private void btnBackStep_Click(object sender, EventArgs e)
{
currentTab--;
tabMenu.SelectTab(tabMenu.SelectedIndex - 1);
if (tabMenu.SelectedIndex == 0)
btnBackStep.Enabled = false;
if (btnNextStep.Enabled == false)
btnNextStep.Enabled = true;
}
tabControl.TabPages.Remove(tabPage1);
This is an old question, but someone may benefit from my addition. I needed a TabControl that would show hidden tabs successively (after an action was performed on the current tab). So, I made a quick class to inherit from and called HideSuccessive() on Load:
public class RevealingTabControl : TabControl
{
private Action _showNextRequested = delegate { };
public void HideSuccessive()
{
var tabPages = this.TabPages.Cast<TabPage>().Skip(1);
var queue = new ConcurrentQueue<TabPage>(tabPages);
tabPages.ToList().ForEach(t => t.Parent = null);
_showNextRequested = () =>
{
if (queue.TryDequeue(out TabPage tabPage))
tabPage.Parent = this;
};
}
public void ShowNext() => _showNextRequested();
}
There is the XtraTabPage.PageEnabled property allowing you to disable certain pages.
Here the solution that i implement:
private void switchTapPage(TabPage tabPage)
{
foreach(TabPage page in tabControl1.TabPages)
{
tabControl1.TabPages.Remove(page);
}
tabControl1.TabPages.Add(tabPage);
}
Basically, i just call this method sending the tabPage that i currently need to show, the method will remove all the tabPages on the tabControl and after that it will just add the one that i sent it.
So the rest of the tabHeaders will not shown and they will be inaccessible, because they dont even exists in the tabControl.
I took the idea from the #stormenet answer.
You can do it through the tabpages: tabPage1.Hide(), tabPage2.Show() etc.
In the form load event if we write this.tabpage.PageEnabled = false, the tabpage will be disabled.
Assume that you have these controls:
TabControl with name tcExemple.
TabPages with names tpEx1 and tpEx2.
Try it:
Set DrawMode of your TabPage to OwnerDrawFixed;
After InitializeComponent(), make sure that tpEx2 is not enable by adding this code:
((Control)tcExemple.TabPages["tpEx2").Enabled = false;
Add to Selection tcExemple event the code below:
private void tcExemple_Selecting(object sender, TabControlCancelEventArgs e)
{
if (!((Control)e.TabPage).Enabled)
{
e.Cancel = true;
}
}
Attach to DrawItem event of tcExemple this code:
private void tcExemple_DrawItem(object sender, DrawItemEventArgs e)
{
TabPage page = tcExemple.TabPages[e.Index];
if (!((Control)page).Enabled)
{
using (SolidBrush brush = new SolidBrush(SystemColors.GrayText))
{
e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
}
}
else
{
using (SolidBrush brush = new SolidBrush(page.ForeColor))
{
e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
}
}
}
It will make the second tab non-clickable.
I could not find an appropriate answer to the question. There looks to be no solution to disable the specific tab. What I did is to pass the specific tab to a variable and in SelectedIndexChanged event put it back to SelectedIndex:
//variable for your specific tab
int _TAB = 0;
//here you specify your tab that you want to expose
_TAB = 1;
tabHolder.SelectedIndex = _TAB;
private void tabHolder_SelectedIndexChanged(object sender, EventArgs e)
{
if (_TAB != 0) tabHolder.SelectedIndex = _TAB;
}
So, you don't actually disable the tab, but when another tab is clicked it always returns you to the selected tab.
in C# 7.0, there is a new feature called Pattern Matching. You can disable all tabs via Type Pattern.
foreach (Control control in Controls)
{
// the is expression tests the variable and
// assigned it to a new appropriate variable type
if (control is TabControl tabs)
{
tabs.Enabled = false;
}
}
Use:
tabControl1.TabPages[1].Enabled = false;
By writing this code, the tab page won't be completely disabled (not being able to select), but its internal content will be disabled which I think satisfy your needs.
The solution is very simple.
Remove/comment this line
this.tabControl.Controls.Add(this.YourTabName);
in IntializeComponent() method in MainForm.cs
MyTabControl.SelectedTab.Enabled = false;