Say I have a Textbox nested within a TabControl.
When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl).
Simply calling textbox1.focus() in the Load event of the form does not appear to work.
I have been able to focus it by doing the following:
private void frmMainLoad(object sender, EventArgs e)
{
foreach (TabPage tab in this.tabControl1.TabPages)
{
this.tabControl1.SelectedTab = tab;
}
}
My question is:
Is there a more elegant way to do this?
The following is the solution:
private void frmMainLoad(object sender, EventArgs e)
{
ActiveControl = textBox1;
}
The better question would however be why... I'm not entirely sure what the answer to that one is.
Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.
Try putting it in the Form_Shown() event. Because it's in a container, putting in the Form_Load or even the Form() constructor won't work.
Try to use textbox1.Select() instead of textbox1.Focus(). This helped me few times.
You just need to add the Control.Select() for your control to this code. I have used this to set focus on controls during validation when there are errors.
private void ShowControlTab(Control ControlToShow)
{
if (!TabSelected)
{
if (ControlToShow.Parent != null)
{
if (ControlToShow.Parent.GetType() == typeof(TabPage))
{
TabPage Tab = (TabPage)ControlToShow.Parent;
if (WOTabs.TabPages.Contains(Tab))
{
WOTabs.SelectedTab = Tab;
TabSelected = true;
return;
}
}
ShowControlTab(ControlToShow.Parent);
}
}
}
I had a user control within another user control. textbox1.Select() worked for me but textbox1.Focus() did not work.
You can also try setting Tabstop to false, textbox1.Focus(), TabStop true.
private void ChildForm1_Load(object sender, EventArgs e)
{
ActiveControl = txt_fname;
}
i use this code it works fine on win tab control or dotnetbar supertab contrl
Related
I'm trying to apply focus behavior, similar to button blue border to FlowLayoutPanel. I tried to use GotFocus and LostFocus, but clearly that's not the way to go.
private void FlowLayoutPanel_Click(object sender, EventArgs e)
{
(sender as Control).BackColor = SystemColors.GradientActiveCaption;
//More operations.
}
private void Panel_LostFocus(object sender, System.EventArgs e)
{
(sender as Control).BackColor = default(Color);
//More operations.
}
While clicking on the FlowLayoutPanel nothing happens and while using tab the two event are invoked one after another.
Any suggestions?
FlowLayoutPanel is not a selectable control by default. You can create a custom flow layout panel by deriving from FlowLayoutPanel and set Selectable and UserMouse control styles to make it selectable by mouse. Also to accept tab stop, set TabStop property to true:
class ExFlowLayoutPanel:FlowLayoutPanel
{
public ExFlowLayoutPanel():base()
{
SetStyle(ControlStyles.Selectable, true);
SetStyle(ControlStyles.UserMouse, true);
TabStop = true;
}
}
Then you can handle GotFocus and LostFocus or Enter and Leave events.
The only point of using a FLP is to get it to arrange child controls. It is always a child control that gets the focus, not the FLP. So sure, nothing happens. You'd have to subscribe the Enter events of all the child controls to see the focus entering the panel or one of its children. Leave is much harder to get right, that's going to flicker like a cheap motel.
Very ugly solution, you don't want to it that way. Use the Application.Idle event instead, the best alternative when getting a reliable event just isn't practical. Check the Parent of this.ActiveControl, like this:
public Form1() {
InitializeComponent();
Application.Idle += CheckFlpFocus;
this.Disposed += delegate { Application.Idle -= CheckFlpFocus; };
}
private bool FlpHasFocus;
private void CheckFlpFocus(object sender, EventArgs e) {
bool hasFocus = false;
for (var ctl = this.ActiveControl; ctl != null; ctl = ctl.Parent) {
if (ctl == flowLayoutPanel1) hasFocus = true;
}
if (hasFocus != FlpHasFocus) {
FlpHasFocus = hasFocus;
flowLayoutPanel1.BackColor = hasFocus ? Color.Black : Color.White;
}
}
I have an application with a Panel containing children Form objects. When I click one of the children Form it brings to front. I would like to know which one is in front now...
I've looked in event list but cant find proper event form my purpose :(
These methods doesn't work:
protected void OpenedFileForm_Enter(object sender, EventArgs e)
{
MessageBox.Show("enter");
}
protected void OpenedFileForm_Click(object sender, EventArgs e)
{
MessageBox.Show("click");
}
protected void OpenedFileForm_Activated(object sender, EventArgs e)
{
MessageBox.Show("activated");
}
protected void OpenedFileForm_MouseClick(object sender, MouseEventArgs e)
{
MessageBox.Show("mouse click");
}
protected void OpenedFileForm_Shown(object sender, EventArgs e)
{
MessageBox.Show("shown");
}
OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.DefaultExt = "*.txt";
openFile1.Filter = "TXT Files|*.txt|RTF Files|*.rtf";
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
openFile1.FileName.Length > 0)
{
switch (Path.GetExtension(openFile1.FileName))
{
case ".txt":
txtForm childTXT = new txtForm();
this.childForms.Add(childTXT);
childTXT.Parent = this.mainPanel;
childTXT.richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);
childTXT.Show();
break;
}
}
Have you tried the Form.Activated Event?
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.activated(v=vs.80).aspx
Edit:
If you are in an MDI application, you might need to use MdiChildActivate instead.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.mdichildactivate.aspx
This code can only work when you set the Form.TopLevel property to false. Which makes it turn into a child control, almost indistinguishable from a UserControl.
This has many side-effects, for one there is no notion of "front" anymore. The Z-order of child controls is determined by their position in their parent's Controls collection. And it affects the events it fires, Activated and Deactivated will never fire. Furthermore, the Form class was designed to be a container control, it doesn't like taking the focus itself. Its child controls get the focus, the Form class doesn't have any use for focus. Which is why the Enter, Click and MouseClick events don't fire, they are events that require focus.
Long story short, what you are trying to do doesn't make a wholeheckofalot of sense. If it is strictly the Z-order you want to fix then write an event handler for the MouseDown event:
void OpenedFileForm_MouseDown(object sender, MouseEventArgs e) {
var frm = (Form)sender;
frm.BringToFront();
}
You could add frm.Select() to get the Enter event to fire, but only do that if the form doesn't contain any focusable controls itself. Do note that there is evidence that you don't assign the events correctly in your code. The Shown event does fire. It is also important that you set the FormBorderStyle to None, the title bar cannot indicate activation status anymore.
Ok, I got this! Thx for help everyone. You gave me a hint to think about equity of my strange MDI idea where Panel is parent for other Forms. I Removed SplitContainer containing Panel and just did standard MDI application, where Forms are MDIChildren of main Form.
childTXT.MdiParent = this;
Since TabStop does not work on RadioButtons (see linked question), how can I prevent a (WinForm) RadioButton from being tabbed into, but also allow the user to click on the RadioButton, without the tab focus jumping somewhere else.
I've read this and so I thought the following would work:
rbFMV.Enter += (s, e) => focusFirstWorkflowButton();
rbFMV.MouseUp += (s, e) => rbFMV.Focus();
But it doesn't. When I click on the RB, the focus jumps away, and does not come back on Mouse Up.
Any dirty workarounds out there?
Try something like this:
Set TabStop property of the radiobuttons to "false" in the form's constructor. Then attach the following events handlers to the CheckedChanged events of the radiobuttons.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
radioButton1.TabStop = false;
radioButton2.TabStop = false;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
radioButton1.TabStop = false;
radioButton2.TabStop = false;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
radioButton1.TabStop = false;
radioButton2.TabStop = false;
}
}
You can attach these event handlers using lambda aswell, as you have shown in your question.
But the important point here is that whenever a radiobutton is checked/unchecked, it's tabstop property is also modified simultaneously. Hence you need to set it to false everytime that event occurs.
The underlying Win32 RadioButton does not automatically change the TabStop property. However, if you use .NET Reflector you can see that the .NET control runs code to update the TabStop property whenever OnEnter method is called because focus has entered the control or whenever the AutoCheck or Checked properties are modified.
Luckily there is a simple solution to your problem. Just derive a new class that overrides the OnTabStopChanged method and automatically set it back to false again. Here is the impl...
public class NonTabStopRadioButton : RadioButton
{
protected override void OnTabStopChanged(EventArgs e)
{
base.OnTabStopChanged(e);
if (TabStop)
TabStop = false;
}
}
Then always use the NonTabStopRadioButton in your application instead of the standard one.
only one control can have input focus at the time i think, so when they click the radio button it will get focus..
But what if you do something like this?
rbFMV.GotFocus += (s, e) => someothercontrol.Focus();
also, have you looked at the TabStop property?
-edit-
i see you have, sorry, missed that :/
I need to remove the focus from several TextBoxes. I tried using:
textBox1.Focused = false;
Its ReadOnly property value is true.
I then tried setting the focus on the form, so as to remove it from all the TextBoxes, but this also fails to work:
this.Focus();
and the function returns false when a textbox is selected.
So, how do I remove the focus from a TextBox?
You can add the following code:
this.ActiveControl = null; //this = form
Focusing on the label didn't work for me, doing something like label1.Focus() right?
the textbox still has focus when loading the form, however trying Velociraptors
answer, worked for me, setting the Form's Active control to the label like this:
private void Form1_Load(object sender, EventArgs e)
{
this.ActiveControl = label1;
}
Try disabling and enabling the textbox.
You can also set the forms activecontrol property to null like
ActiveControl = null;
Focus sets the input focus, so setting it to the form won't work because forms don't accept input. Try setting the form's ActiveControl property to a different control. You could also use Select to select a specific control or SelectNextControl to select the next control in the tab order.
Try this one:
First set up tab order.
Then in form load event we can send a tab key press programmatically to application. So that application will give focus to 1st contol in the tab order.
in form load even write this line.
SendKeys.Send("{TAB}");
This did work for me.
This post lead me to do this:
ActiveControl = null;
This allows me to capture all the keyboard input at the top level without other controls going nuts.
A simple solution would be to kill the focus, just create your own class:
public class ViewOnlyTextBox : System.Windows.Forms.TextBox {
// constants for the message sending
const int WM_SETFOCUS = 0x0007;
const int WM_KILLFOCUS = 0x0008;
protected override void WndProc(ref Message m) {
if(m.Msg == WM_SETFOCUS) m.Msg = WM_KILLFOCUS;
base.WndProc (ref m);
}
}
I've found a good alternative! It works best for me, without setting the focus on something else.
Try that:
private void richTextBox_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
}
I made this on my custom control, i done this onFocus()
this.Parent.Focus();
So if texbox focused - it instantly focus textbox parent (form, or panel...)
This is good option if you want to make this on custom control.
It seems that I don't have to set the focus to any other elements. On a Windows Phone 7 application, I've been using the Focus method to unset the Focus of a Textbox.
Giving the following command will set the focus to nothing:
void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Focus();
}
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx
It worked for me, but I don't know why didn't it work for you :/
//using System;
//using System.Collections.Generic;
//using System.Linq;
private void Form1_Load(object sender, EventArgs e)
{
FocusOnOtherControl(Controls.Cast<Control>(), button1);
}
private void FocusOnOtherControl<T>(IEnumerable<T> controls, Control focusOnMe) where T : Control
{
foreach (var control in controls)
{
if (control.GetType().Equals(typeof(TextBox)))
{
control.TabStop = false;
control.LostFocus += new EventHandler((object sender, EventArgs e) =>
{
focusOnMe.Focus();
});
}
}
}
The way I get around it is to place all my winform controls. I make all labels and non-selecting winform controls as tab order 0, then my first control as tab order 2 and then increment each selectable control's order by 1, so 3, 4, 5 etc...
This way, when my Winforms start up, the first TextBox doesn't have focus!
you can do this by two method
just make the "TabStop" properties of desired textbox to false now it will not focus even if you have one text field
drag two text box
make one visible on which you don't want foucus which is textbox1
make the 2nd one invisible and go to properties of that text field and select
tabindex value to 0 of textbox2
and select the tabindex of your textbox1 to 1
now it will not focus on textbox1
If all you want is the optical effect that the textbox has no blue selection all over its contents, just select no text:
textBox_Log.SelectionStart = 0;
textBox_Log.SelectionLength = 0;
textBox_Log.Select();
After this, when adding content with .Text += "...", no blue selection will be shown.
Please try set TabStop to False for your view control which is not be focused.
For eg:
txtEmpID.TabStop = false;
You can try:
textBox1.Enable = false;
using System.Windows.Input
Keyboard.ClearFocus();
Kinda late to the party in 2022, however none of the solutions here worked for me (idk why) using .Net_6.0_windows, so I've come up with this solution:
Label focusoutLabel = new Label() {
Text = "",
Name = "somegenericplaceholdernamethatwillneverbeusedinmyprogram",
Visible = false,
};
this.Controls.Add(focusoutLabel);
this.ActiveControl = focusoutLabel;
^Place this code to your Form load handler^
In the constructor of the Form or UserControl holding the TextBox write
SetStyle(ControlStyles.Selectable, false);
After the InitializeComponent();
Source: https://stackoverflow.com/a/4811938/5750078
Example:
public partial class Main : UserControl
{
public Main()
{
InitializeComponent();
SetStyle(ControlStyles.Selectable, false);
}
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;