C# Windows forms textbox greyed out [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'll try to be as specific as possible. I'm using visual basic 2010 c# express edition. I'm trying to create a textbox that is filled with information from the program. Suppose I put the text "Hello" in the textbox, when I run it, the form has a textbox saying Hello.
Here, the user can select the text and copy it. Basically, when the mouse goes over the textbox, it changes appearance and the textbox is interactive.
What I need to make is the textbox as not-interactive. In the textbox properties, there is an option called "Enabled". If I make it as False, all my requirements are satisfied. But the textbox is greyed out. Is there any way to get "Enabled" to false and still make the textbox look not greyed out. My query is regarding aesthetics.

You can make the textbox readonly:
Creating a Read-Only Text Box (Windows Forms)
To make the background gray, you probably need to change the background color:
txtFoo.BackColor = ...;
And if you do no want to make the text selectable, set Enabled = false;

You can create your own control that will look exactly like a TextBox but will be static. It's very easy to achieve that. Right-click on your project name in Solution Explorer and choose: Add > New Item... > Custom Control. You can name it somehow, e.g. DisabledTextBox.
Here's the full code of the new control.
public partial class DisabledTextBox : Control
{
public DisabledTextBox()
{
InitializeComponent();
DoubleBuffered = true; // To avoid flickering
}
protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.Clear(SystemColors.Window); // White background
pe.Graphics.DrawRectangle(SystemPens.ActiveBorder, new Rectangle(0, 0, Width - 1, Height - 1)); // Gray border
pe.Graphics.DrawString(Text, Font, SystemBrushes.WindowText, 1, 3); // Our text
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
Invalidate(); // We want to repaint our control when text changes
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
Height = Font.Height + 7; // This limit the height of our control so it will beahave like a normal TextBox
}
}
When you compile it, your new control will be available in Toolbox, so you can use like any other control. It will look exactly like TextBox.

textBox.BackColor = System.Drawing.SystemColors.Window;

Setting ReadOnly property to True should do the trick

I was looking for the easy solution to this question>
Here is what worked for me:
textBox Enabled property -- true
textBox ReadOnly property -- true
And below line of code to get rid of they greyed out area.
public Test_class()
{
InitializeComponent();
textBox.BackColor = System.Drawing.SystemColors.Window;
}
Yes, the user still can select the value in the text box but not entering a new value or edit old one.
Cheers!

Related

StatusStrip label not visible when text too long

I have a StatusStrip docked to the bottom of a C# Form, it contains a label, the text in it displays fine, except when there is longer length of text then it does not display at all, and I have to widen the form and then all of a sudden it appears. Is it possible to show it in the form below:
This is a very long tex...
So that the user knows that the app is showing something and then he can widen it himself, because when it is not visible at all, it does not indicate anything to user.
You can create a custom renderer based on ToolStripProfessionalRenderer and override OnRenderItemText method and draw text with ellipsis:
public class CustomRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (e.Item is ToolStripStatusLabel)
TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont,
e.TextRectangle, e.TextColor, Color.Transparent,
e.TextFormat | TextFormatFlags.EndEllipsis);
else
base.OnRenderItemText(e);
}
}
Then it's enough to set Renderer of your StatusStrip to your custom renderer:
this.statusStrip1.Renderer = new CustomRenderer();
In below example, You can see the behavior of a ToolStripStatusLabel which it's Spring property is set to true and its StatusStrip uses CustomRenderer:
If you set
ToolStripStatusLabel.Spring = True;
then you won't get the "..." but the text will be shown even when the available space is insufficient.
On Visual Studio 2017, the accepted answer didn't work for me. So here is another simple solution.
Set LayoutStyle property of StatusStrip to Flow. i.e:
statusStrip1.LayoutStyle= LayoutStyle.Flow;
And Set
`statusStrip1.AutoSize= false;`

C# When the mouse cursor hovering in ControlLabel it will show up list of items? What kind of control is that? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a Label Control then when mouse cursor is hovering around it for about 1second, it will show list of items in text format(the items are either plain text or it is also a control). It's like in the website Home/Contact Us/About Us/Help. What kind of control i'm going to use?
Like for example. www.ebay.com. Under "My Ebay", it will shows you the items, eg Summary/Bids/List/Messages...etc...
What you see is best implemented by a ToolTip.
To add a ToolTip to a Control you usually do this:
Add a ToolTip from the toolbox to the Form
Now each control on the form as a new property field in the properties pane: "ToolTip" on "yourToolTipName"
Set a tooltip text for each control you want to show a tool tip.
This is really simple.
Therefore many folks believe that that is all a ToolTip can do.
But it can be created and modified dynamically and styled in many ways. Showing a list of items is no problem at all..
To load it with data dynamically you code the MouseHover event of your Label:
private void yourLabel_MouseHover(object sender, EventArgs e)
{
toolTip1.SetToolTip(yourLabel, yourData);
}
Of course you may want to call a function to load the right and current data for each of your Labels..: string loadData(Label lbl).
If you want to you can easily ownerdraw the ToolTip. First code its Popup event:
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
toolTip1.BackColor = Color.LightGoldenrodYellow; // pick a Color if you want to
toolTip1.OwnerDraw = true;
}
Then the Draw event:
private void toolTip1_Draw(object sender, DrawToolTipEventArgs e)
{
using (Font font = new Font("Consolas", e.Font.SizeInPoints))
{
e.DrawBackground();
e.DrawBorder();
e.Graphics.DrawString(e.ToolTipText, font, Brushes.DarkMagenta, e.Bounds);
}
Note that the ToolTip will automatically resize to display the text. Also note that you can embed \n characters to create line breaks.
I chose the monospaced font Consolas, so I can create nicely aligned columns of text. Also note that if you want to enlarge the font you should add enough room via extra lines and/or space, this is because the size of the ToolTip area is calculated from its original font size and you can't pick a different Font for it.. See here for a little more on that..
Also note that you do not need to set the property in the designer at all. The MouseHover does all you need..
Create ContextMenuStrip, set event handlers for items:
var contextMenu = new ContextMenuStrip();
contextMenu.Items.Add("Item 1");
contextMenu.Items.Add("Item 2");
contextMenu.Items.Add("Item 3");
Your ControlLabel:
var label = new Label { Parent = this, BorderStyle = BorderStyle.FixedSingle, Text = "Test" };
Show menu manually:
label.MouseHover += (s, e) =>
{
contextMenu.Show(label, 0, label.Height);
};

Add Label with Textbox at design time

I am creating a project using VS.NET (C#) with many forms that contain textboxes and associated labels. I have created the association through an exposed property I created for the textbox which contains the label name. The problem is that each time I add a textbox at design-time I have to add a label and then enter the label name into the property of the textbox. I would much rather do this dynamically at design-time when I create the textbox, much like the old VB textbox add. I have been scouring the net for a way to dynamically add a label whenever I add a textbox at design-time without finding any acceptable solutions. I found an answer on this site that suggested adding a user control containing a textbox and label, and though it is probably the best solution I have found, I think it restricts me more than I would like. Do I have to go through some full-blown custom designer to do this hopefully simple task?
TIA
Although I like the solution that uses UserControl better (simpler and easier to handle), but there may be some cases where not creating one more thing that will eat the resources is preferable (for example if you need a lot of such label-textbox pairs on one form).
The simplest solution I came up with is as follows (the label shows in the designer after you build the project):
public class CustomTextBox : TextBox
{
public Label AssociatedLabel { get; set; }
public CustomTextBox():base()
{
this.ParentChanged += new EventHandler(CustomTextBox_ParentChanged);
}
void CustomTextBox_ParentChanged(object sender, EventArgs e)
{
this.AutoAddAssociatedLabel();
}
private void AutoAddAssociatedLabel()
{
if (this.Parent == null) return;
AssociatedLabel = new Label();
AssociatedLabel.Text = "Associated Label";
AssociatedLabel.Padding = new System.Windows.Forms.Padding(3);
Size s = TextRenderer.MeasureText(AssociatedLabel.Text, AssociatedLabel.Font);
AssociatedLabel.Location = new Point(this.Location.X - s.Width - AssociatedLabel.Padding.Right, this.Location.Y);
this.Parent.Controls.Add(AssociatedLabel);
}
}
Although it isn't a complete solution, you need to code the additional behaviour such as moving the label with the textbox, changing the location of the label when its text changes, removing the label when the textbox is removed, and so on.
Another solution would be to not use the label at all, and just draw the text beside the textbox manually.
I'm afraid not, you would have to use either UserControl or CustomControl as there is no way to add a TextBox and associated Label at the same time

Changing RichTextBox to a Label [duplicate]

This question already has answers here:
How do I change the style of a disabled control?
(2 answers)
Closed 9 years ago.
I am using a rich text box as a label for my application. The text box is read-only but its content can be selected. How can I make users can't select text in the rich text box while it is read-only?
When I disable the control can't select text but I loose the colors, because they become grey (disabled). How can I disable text selection without disabling the rich text box control?
FYI: I am using a rich text box as a label because, I need to change the fore color to red for one word in the string which needs to be shown to the user. I used this SO article and following method to do it.
string word = "red";
int start = richTextBox1.Find(word);
if (start >= 0) {
richTextBox1.Select(start, word.Length);
richTextBox1.SelectionColor = Color.Red;
}
EDIT: BTW It's C# WinForm
Simply handle the selection, and restore it to "nothing":
// so you have colour (set via the Designer)
richTextBox.Enabled = true;
// so users cannot change the contents (set via the Designer)
richTextBox.ReadOnly = true;
// allow users to select the text, but override what they do, IF they select the text (set via the Designer)
richTextBox.SelectionChanged += new System.EventHandler(this.richTextBox_SelectionChanged);
// If the user selects text, then de-select it
private void richTextBox_SelectionChanged(object sender, EventArgs e)
{
// Move the cursor to the end
if (this.richTextBox.SelectionStart != this.richTextBox.TextLength)
{
this.richTextBox.SelectionStart = this.richTextBox.TextLength;
}
}
Taken from: http://social.msdn.microsoft.com/Forums/en-US/winformsdesigner/thread/d1132ee5-acad-49f3-ae93-19d386fe2d12/
(By the way, a little bit of searching goes a long way.)

Hide Tab Header on C# TabControl

I am developing a Windows Form Application with several pages. I am using a TabControl to implement this. Instead of using the header to switch between tabs, I want my application to control this e.g. the next tab should open after the user has filled in a text box and clicked the next button.
Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It shows the tabs at design time so you can easily switch between them while designing. They are hidden at runtime, use the SelectedTab or SelectedIndex property in your code to switch the page.
using System;
using System.Windows.Forms;
public class TablessControl : TabControl {
protected override void WndProc(ref Message m) {
// Hide tabs by trapping the TCM_ADJUSTRECT message
if (m.Msg == 0x1328 && !DesignMode) m.Result = (IntPtr)1;
else base.WndProc(ref m);
}
}
tabControl1.Appearance = TabAppearance.FlatButtons;
tabControl1.ItemSize = new Size(0, 1);
tabControl1.SizeMode = TabSizeMode.Fixed;
Create new UserControl, name it for example TabControlWithoutHeader and change inherited UserControl to TabControl and add some code. Result code should look like:
public partial class TabControlWithoutHeader: TabControl
{
public TabControlWithoutHeader()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x1328 && !DesignMode)
m.Result = (IntPtr)1;
else
base.WndProc(ref m);
}
}
After compile you will have TabControlWithoutHeader control in ToolBox. Drop it on form, in designer you will see headers, but at runtime they'll be hidden. If you want to hide them in designer too, then remove && !DesignMode.
Hope that helps.
http://social.msdn.microsoft.com/Forums/windows/en-US/c290832f-3b84-4200-aa4a-7a5dc4b8b5bb/tabs-in-winform?forum=winforms
You can replace tabcontrol with a hand made panel that mimic like you want:
class MultiPagePanel : Panel
{
private int _currentPageIndex;
public int CurrentPageIndex
{
get { return _currentPageIndex; }
set
{
if (value >= 0 && value < Controls.Count)
{
Controls[value].BringToFront();
_currentPageIndex = value;
}
}
}
public void AddPage(Control page)
{
Controls.Add(page);
page.Dock = DockStyle.Fill;
}
}
And then add pages and set current visible page:
MultiPagePanel p;
// MyTabPage is a Control derived class that represents one page on your form.
MyTabPage page = new MyTabPage();
p.AddPage(page);
p.CurrentPageIndex = 0;
I was needing this code but in VB.net so I converted it. If someone needs this code in VB.Net there it is
Imports System
Imports System.Windows.Forms
Public Class TablessControl
Inherits System.Windows.Forms.TabControl
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
' Hide tabs by trapping the TCM_ADJUSTRECT message
If (m.Msg = Convert.ToInt32("0x1328", 16) And Not DesignMode) Then
m.Result = CType(1, IntPtr)
Else
MyBase.WndProc(m)
End If
End Sub
End Class
and thanks to #Hans Passant for the answer in C#
To complement Hans Passant's existing answer, I've found four ways to hide the arrows from the user when the numbers of tabs exceeds the width of the TablessControl. No single solution is necessarily perfect for everyone, but may be for you (or at least a combination of them).
Solution 1:
Simply enable Multiline. This will prevent the arrows from appearing in the first place. However, bear in mind, you may lose WYSIWYG in the designer because the vertical space will be adjusted downwards vertically, and controls within the TablessControl may even be 'chopped off' at the bottom (again, only in developer mode though).
Solution 2:
A more advanced solution which solves the WYSIWYG problem above is to only enable Multiline once the program gets running. Simply add this constructor to the TablessControl class:
public TablessControl()
{
bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
if (!designMode) Multiline = true;
}
To the developer, they will still appear as a single line of tabs.
Solution 3:
Decrease the font size of the TablessControl. Each tab should shrink accordingly. Since the user never gets to see the tabs, it shouldn't matter much if you set the font sizes to even 4pt.
However be careful, because the TablessControl's contents may also be resized. If this happens, re-edit the font size for each widget inside, and at that point, they'll thankfully stay at that size even if you then decide to re-change the main TablessControl's font size again.
This approach also has the advantage of more closely showing the true WYSIWYG vertical real-estate to the developer (which can look fine for the user, but may be cut off slightly at the bottom in the designer due to the height of the tabs).
This solution can be combined with Solution 1 and 2 for accumulated advantages.
Solution 4:
This solution isn't necessarily so great if any of the tabs have text which are long. Thanks to Hans for suggesting it.
First set the TablessControl's SizeMode to 'Fixed', and then reduce the TablessControl's ItemSize Width property to a smaller number to reduce each tab's width. Feel free also to adjust the ItemSize Height property to help address the aforementioned WYSIWYG issue, though Solution 3 may be more helpful for that problem.
This solution can be combined with the above solutions to further accumulate advantages.
If you really want to do this, yo can do something like this
tcActionControls.Region = new Region(new RectangleF(
tbPageToShow.Left,
tbPageToShow.Top,
tbPageToShow.Width,
tbPageToShow.Height)
);
Where tcActionControls is your TabControl and tbPageToShow is a TabPage to show in this precise moment.
Should work for you.
Regards.
This solution appears to work well -
How to hide tabs in the tab control?
Insert Tabcontrol into a form, the default name being tabcontrol1.
Ensure that tabcontrol1 is selected in the Properties pane in visual studio and change the following properties:
a. Set Appearance to Buttons
b. Set ItemSize 0 for Width and 1 for Height
c. Set Multiline to True
d. Set SizeMode to Fixed
This is best done after your have finished your design time tasks as it hides them in the designer as well - making it difficult to navigate!
You can try removing the TabPage from the TabPageCollection :
TabControl.TabPageCollection tabCol = tabControl1.TabPages;
foreach (TabPage tp in tabCol)
{
if(condition)
{
tabCol.Remove(tp);
}
}
In my WinForms app, I was able to work around this by positioning the TabControl's y-coordinate outside the visible range of the form, so the tabs were effectively hidden. This example only works if the tabControl is near the top of the form, but you get the idea.
private void frmOptions_Load(object sender, EventArgs e)
{
tabControl1.Top = -23; //Only tabPage contents visible
}

Categories

Resources