ToggleButton in C# WinForms - c#

Is it possible to create a toggle button in C# WinForms? I know that you can use a CheckBox control and set it's Appearance property to "Button", but it doesn't look right. I want it to appear sunken, not flat, when pressed. Any thoughts?

You can just use a CheckBox and set its appearance to Button:
CheckBox checkBox = new System.Windows.Forms.CheckBox();
checkBox.Appearance = System.Windows.Forms.Appearance.Button;

Check FlatStyle property. Setting it to "System" makes the checkbox sunken in my environment.

You may also consider the ToolStripButton control if you don't mind hosting it in a ToolStripContainer. I think it can natively support pressed and unpressed states.

thers is a simple way to create toggle button. I test it in vs2010. It's perfect.
ToolStripButton has a "Checked" property and a "CheckOnClik" property. You can use it to act as a toggle button
tbtnCross.CheckOnClick = true;
OR
tbtnCross.CheckOnClick = false;
tbtnCross.Click += new EventHandler(tbtnCross_Click);
.....
void tbtnCross_Click(object sender, EventArgs e)
{
ToolStripButton target = sender as ToolStripButton;
target.Checked = !target.Checked;
}
also, You can create toggle button list like this:
private void Form1_Load(object sender, EventArgs e)
{
arrToolView[0] = tbtnCross;
arrToolView[1] = tbtnLongtitude;
arrToolView[2] = tbtnTerrain;
arrToolView[3] = tbtnResult;
for (int i = 0; i<arrToolView.Length; i++)
{
arrToolView[i].CheckOnClick = false;
arrToolView[i].Click += new EventHandler(tbtnView_Click);
}
InitTree();
}
void tbtnView_Click(object sender, EventArgs e)
{
ToolStripButton target = sender as ToolStripButton;
if (target.Checked) return;
foreach (ToolStripButton btn in arrToolView)
{
btn.Checked = false;
//btn.CheckState = CheckState.Unchecked;
}
target.Checked = true;
target.CheckState = CheckState.Checked;
}

How about this?
Assuming you have System.Windows.Forms referenced.
var cbtnToggler = new CheckBox();
cbtnToggler.Appearance = Appearance.Button;
cbtnToggler.TextAlign = ContentAlignment.MiddleCenter;
cbtnToggler.MinimumSize = new Size(75, 25); //To prevent shrinkage!
Hope this helps ;)

This is my simple codes I hope it can help you
private void button2_Click(object sender, EventArgs e)
{
if (button2.Text == "ON")
{
panel_light.BackColor = Color.Yellow; //symbolizes light turned on
button2.Text = "OFF";
}
else if (button2.Text == "OFF")
{
panel_light.BackColor = Color.Black; //symbolizes light turned off
button2.Text = "ON";
}
}

When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).
I end up setting the FlatStyle to flat and wrote a new Paint event handler.
private void checkbox_paint(object sender, PaintEventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
Rectangle borderRectangle = myCheckbox.ClientRectangle;
if (myCheckbox.Checked)
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Sunken);
}
else
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Raised);
}
}
I give a similar answer to this question:
C# winforms button with solid border, like 3d
Sorry for double posting.

You can always code your own button with custom graphics and a PictureBox, though it won't necessarily match the Windows theme of your users.

I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well.

use if command to check status and let operate as a toggle button
private void Protection_ON_OFF_Button_Click(object sender, EventArgs e)
{
if (FolderAddButton.Enabled == true)
{
FolderAddButton.Enabled = false;
}
else
{
FolderAddButton.Enabled = true;
}
}

You should look into Siticone I use it and I love it. It works exactly like a checkbox but is a toggle button. Its downside is a message box will come up every time you open Visual Studios so I just installed a tool that disables it. You can also look into Guana but I found that to have a few bugs :)

Changing a CheckBox appearance to Button will give you difficulty in adjustments. You cannot change its dimensions because its size depends on the size of your text or image.
You can try this: (initialize the count variable first to 1 | int count = 1)
private void settingsBtn_Click(object sender, EventArgs e)
{
count++;
if (count % 2 == 0)
{
settingsPanel.Show();
}
else
{
settingsPanel.Hide();
}
}
It's very simple but it works.
Warning: This will work well with buttons that are occasionally used (i.e. settings), the value of count in int/long may be overloaded when used more than it's capacity without closing the app's process. (Check data type ranges: http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx)
The Good News: If you're running an app that is not intended for use 24/7 all-year round, I think this is helpful. Important thing is that when the app's process ended and you run it again, the count will reset to 1.

Related

Disable repositoryItemCheckEdit after it's checked

I have a repositoryItemCheckEdit in a column of my grid. The task I want to do is :
Once the user pressed the CheckEdit , this cell become disable so that the user can not make click again.
To do this task I'm using the CheckedChanged event, in the following way :
private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
{
var obj = sender as CheckEdit;
if (obj.Checked)
{
repositoryItemCheckEdit1.Enabled = false;
}
}
With the above event the only thing I get is that the cell becomes clearer , but not is disabled. Even if I make click again it allows me to do it.
Any help is appreciated.
You will probably have more luck/an easier time dealing with this using the brute force method... at least i find this a lot easier than dealing with the crazyness of DataGridView controls scheme.
Use the Tag attribute of your control to set a flag on it, and then when someone tries to un-check it/change it, force it back to checked. Like so:
private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
{
var obj = sender as CheckEdit;
if(obj.Tag != null)
{
obj.Checked = true;
repositoryItemCheckEdit1.Enabled = false;
}
else
{
if (obj.Checked)
{
obj.Tag = true;
repositoryItemCheckEdit1.Enabled = false;
}
}
}

setting Back color of a disabled combo to white color

hi
I have a combo box which can enabled and disabled at run time.now i needed to make make the back color constant even if it is enabled or disabled.any one can help me?
I found following solutions.
Solution 1:
set the dropdownstyle to be "DropDownList" when disabled and then reset it to "DropDown" when you enabled the control
combobox.DropDownStyle = ComboBoxStyle.DropDownList;
Solution 2:
Go here http://www.codeproject.com/Articles/22454/ReadOnly-ComboBox
First solution work for me and 2nd solution u can try it.
This worked for me
comboBox1.DropDownHeight = 1;
comboBox1.KeyDown += new KeyEventHandler(comboBox1_KeyDown);
comboBox1.KeyPress += new KeyPressEventHandler(comboBox1_KeyPress);
comboBox1.KeyUp += new KeyEventHandler(comboBox1_KeyUp);
Now in each of this handlers just set e.Handled = true
void comboBox1_KeyUp(object sender, KeyEventArgs e)
{
e.Handled = true;
}
void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
Now when you have to function it as a Enabled just remove the handlers and set the DropDownHeight
comboBox1.KeyDown -= new KeyEventHandler(comboBox1_KeyDown);
comboBox1.KeyPress -= new KeyPressEventHandler(comboBox1_KeyPress);
comboBox1.KeyUp -= new KeyEventHandler(comboBox1_KeyUp);
If this is WinForms then set the BackColor Property to whatever you want it to be.
As stated below this does NOT work.
Depending on exactly what you are after, Googling has found me a potential solution:
If what you're after is to get the combobox in a disabled state (unchangable, but looking the same as when enabled), then quickly setting the Enabled property from true, to false, then back again on Enter achieves it, although in a somewhat hacky manner:
bool isDisabled = true;
private void comboBox1_Enter(object sender, EventArgs e)
{
if(isDisabled)
{
comboBox1.Enabled = false;
comboBox1.Enabled = true;
}
}

Hanging controls properties on Application.Idle, good or bad?

I'm writing a simple application with several controls on a Windows form. I need to monitor the state of buttons (enabled/disabled) according to the state of a textbox and a listbox.
For example, when the listbox is empty, buttons Delete, Delete All and Edit are to be disabled, or when either the textbox or the listbox is empty button Forward is disabled, and so on.
So, I put the change of these properties on Application.Idle event, so it goes something like this:
private void MainForm_Load(object sender, EventArgs e)
{
Application.Idle += new EventHandler(Application_Idle);
}
public void Application_Idle(object sender, EventArgs e)
{
CheckFillingFields(forwardBtn);
CheckFillingList(deleteBtn);
CheckFillingList(deleteAllBtn);
CheckFillingList(editBtn);
}
private void CheckFillingFields(object sender)
{
if (questionTxt.Text == "" || answersLst.Items.Count == 0)
(sender as Button).Enabled = false;
else
(sender as Button).Enabled = true;
}
private void CheckFillingList(object sender)
{
if (answersLst.Items.Count == 0)
(sender as Button).Enabled = false;
else
(sender as Button).Enabled = true;
}
So, the question is - is it acceptable to use Application.Idle in this case? Or should I make these properties dependable on user actions? (For example, when the user deletes an item from the listbox, I should check if it was the last one, and disable the corresponding buttons.)
Thanks a lot in advance, I really appreciate your help!
The simple answer is that, yes, the idle checking is bad and you should re-check the state of your controls on their change events, not "whenever possible".

C# TabControl - is it possible to "disable" individual TabPages?

Is it somehow possible to disable one (or more) tabs of tab control? At some point I need to make user stay on the active tab and prevent him from leaving... I know I can disable the whole TabControl component, but that disables also all components on active tab...
I also tried to use the Selecting method of TabControl:
private void TabControl_Selecting(object sender, TabControlCancelEventArgs e) {
e.Cancel = PreventTabSwitch;
}
This works, prevents user from switching (if PreventTabSwitch==true), but since all tabs look active and just don't react it's confusing...
There is no Enabled property for individual tab pages, so I don't know what else to do...
Thanks a lot for in advance for all tips.
IIRC, this is the only way to prevent a user from switching tabs.
I presume you are preventing them from leaving as validation on the form has failed? Using the ErrorProvider component would provide some sort of visual cue that they need to do something before switching tabs.
I've had a similar need once (I wanted the active tab to have different background color and some other stuff) and ended up creating new Controls that inherited from TabControl & TabPage where I used OwnerDraw to alter the look.
What you are doing is the right way to go according to MSDN but it does suggest that another option is to hide/show the pages as needed.
TabControl - Disable/Enable tab page at
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/985b41c3-a1de-4744-8875-63262d4c2718/
MSDN Search for "tabcontrol disabled tabpage" at http://social.msdn.microsoft.com/Search/en-US?query=tabcontrol+disabled+tabpage&ac=8
The user cannot click on tabs to navigate, but they can use the two buttons ( Next , 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;
}
If you want to cancel the change of a tab, you can use the Deselecting event. There you can cancel the change by setting property Cancel of the provided TabControlCancelEventArgs to true.

Custom button in C#: How to remove hover background?

I'm trying to do a custom button to my form (which has FormBorderStyle = none) using Visual Studio 2005. I have my 3 states button images in an ImageList linked to the button.
this.btnClose.AutoSize = false;
this.btnClose.BackColor = System.Drawing.Color.Transparent;
this.btnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnClose.FlatAppearance.BorderSize = 0;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnClose.ForeColor = System.Drawing.Color.Transparent;
this.btnClose.ImageKey = "Disabled";
this.btnClose.ImageList = this.imageList1;
this.btnClose.Location = new System.Drawing.Point(368, -5);
this.btnClose.Margin = new System.Windows.Forms.Padding(0);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(31, 31);
this.btnClose.TabIndex = 0;
this.btnClose.UseVisualStyleBackColor = false;
this.btnClose.MouseLeave += new System.EventHandler(this.btnClose_MouseLeave);
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
this.btnClose.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnClose_MouseDown);
this.btnClose.MouseHover += new System.EventHandler(this.btnClose_MouseHover);
private void btnClose_MouseHover(object sender, EventArgs e)
{
btnClose.ImageKey = "enabled";
}
private void btnClose_MouseDown(object sender, MouseEventArgs e)
{
btnClose.ImageKey = "down";
}
private void btnClose_MouseLeave(object sender, EventArgs e)
{
btnClose.ImageKey = "disabled";
}
All is working, but there's one catch. Whenever I move the mouse hover the button I get a really annoying grey background.
How can I remove that?
btnClose.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
The grey background is due to the setting of "System.Windows.Forms.FlatStyle.Flat", it's the default behaviour, since it need to highlight the button when you hover. To eliminate that, you might have to write a custom button class, inherit from the original button and do some custom painting to achieve that.
Btw, instead of setting "enabled" in MouseHover, you should do it in MouseEnter. MouseEnter and MouseLeave is a pair which indicate whether is the mouse is within the button or not, and it's fired once per entry/exit. Where as MouseHover is fire whenever the mouse moved within the button, which create unnessecery repeated setting of "enabled".
I've solved this using a label instead of a button.
//
// imageListButtons
//
this.imageListButtons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListButtons.ImageStream")));
this.imageListButtons.TransparentColor = System.Drawing.Color.Transparent;
this.imageListButtons.Images.SetKeyName(0, "close_normal");
this.imageListButtons.Images.SetKeyName(1, "close_hover");
//
// lblClose
//
this.lblClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblClose.BackColor = System.Drawing.Color.Transparent;
this.lblClose.ImageKey = "close_normal";
this.lblClose.ImageList = this.imageListButtons;
this.lblClose.Location = new System.Drawing.Point(381, 7);
this.lblClose.Margin = new System.Windows.Forms.Padding(0);
this.lblClose.Name = "lblClose";
this.lblClose.Size = new System.Drawing.Size(12, 12);
this.lblClose.TabIndex = 0;
this.lblClose.MouseLeave += new System.EventHandler(this.lblClose_MouseLeave);
this.lblClose.MouseClick += new System.Windows.Forms.MouseEventHandler(this.lblClose_MouseClick);
this.lblClose.MouseEnter += new System.EventHandler(this.lblClose_MouseEnter);
private void lblClose_MouseEnter(object sender, EventArgs e)
{
lblClose.ImageKey = "close_hover";
}
private void lblClose_MouseLeave(object sender, EventArgs e)
{
lblClose.ImageKey = "close_normal";
}
private void lblClose_MouseClick(object sender, MouseEventArgs e)
{
this.Close();
}
PS: notice that I'm using now a two state button, instead of three. It is intended (I know that I still can use three).
create Mouse Enter event which is given below.
private void forAllButtons_MouseEnter(object sender, EventArgs e)
{
Button b = (Button)sender;
b.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
}
then assign this event to all the buttons.
Happy programming :)
I have got one suggestion.Create your own button class deriving from Button.Then override the MouseEnter event in that.Just remove the code for calling the base implementaion.
base.OnMouseEnter(e)
PS: You won't be able to use the MouseEnter event outside the derived class (e.g. a project using this control)
Hi you simply can apply these changes to your button easily using these two lines of codes.
Set the button's FlatStyle to Flat
this.btnClose.FlatStyle = FlatStyle.Flat;
Set the button's MouseOverBackColor to Transparent
this.btnClose.FlatAppearance.MouseOverBackColor = Color.Transparent;
Hope this will help. Thanks
You can also stop changing color of button by deselecting IsHitTestVisible option in Button Properties>common> IsHitTestVisible
Maybe this can also help ...
To solve the problem, Set the MouseOverBackColor to transparent inorder to remove the grey backgroud.

Categories