I am writing a WinForms application. In this application I generate dynamic Label, PictureBox and TextBox controls.
With dragging and dropping an Image into the PictureBox , the added TextBox opens. With entering some text and pressing 'Enter' the following method is fired.
private void tb_Tile_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
TextBox tb_Tile = sender as TextBox;
Tile tb_Tag = tb_Tile.Tag as Tile;
//add function that overgives the given name to the matrix i.e. GiveNameToMatrix()
tb_Tile.Visible = false;
Label lbl_Tile = Controls.Find("Label" + tb_Tag.X + tb_Tag.Y, true).FirstOrDefault() as Label;
lbl_Tile.Visible = true;
//find picture box by tag or sth and then make this pB the parent
PictureBox pb_Tile = (PictureBox)gb_gridBox.Controls["Tile" + tb_Tag.X + tb_Tag.Y];
pb_Tile.BackgroundImage = pb_Tile.Image;
lbl_Tile.Parent = pb_Tile;
// pb_Tile.Visible = false;
if (pb_Tile.HasChildren)
{
lbl_Tile.Text = tb_Tile.Text; //parent has to be set to PictureBox
lbl_Tile.Visible = true;
lbl_Tile.ForeColor = Color.Black;
lbl_Tile.BackColor = Color.Transparent;
lbl_Tile.Location = pb_Tile.Location;
lbl_Tile.Refresh();
pb_Tile.Refresh();
gb_gridBox.Controls.Add(lbl_Tile);
lbl_Tile.BringToFront();
}
}
}
I want the Label.Text to be displayed on the PictureBox. This is why I set the PictureBox as the parent of the Label and the Label.BackColor as Transparent. But the Label just disappears behind the PictureBox...
Does anyone have a clue how to solve this or can give me a hint to another possibility of showing Text in front of the PictureBox?
Thanks in advance.
The problem I see is here:
lbl_Tile.Location = pb_Tile.Location;
The documentation for Location property:
Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container.
In your case the pb_Tile is the container of the lbl_Tile, so to achive the desired location you should use something like
lbl_Tile.Location = new Point(0, 0);
Also you should remove this line
gb_gridBox.Controls.Add(lbl_Tile);
because it changes the Parent of the label. parent.Controls.Add(child) and child.Parent = parent do one and the same.
I want make a form whit a picture box and resizing the picture box on resizing the form also resizing the picture in the picture box on resizing the picture box.how do it? sorry for my poor english
Try to add this method:
private void Form1_Resize(object sender, System.EventArgs e)
{
Control control = (Control)sender;
double percentage = 0.7;
int width = control.Size.Width;
//width = (int)Math.Round(test*perc); imagewidth 70% of form width
int heigth = control.Size.Width;
picturebox1.Size = new Size(width,height);
}
Dock the picture box in the parent form, and change the SizeMode property of the picturebox to stretch
When I add a picturebox to the form at runtime, the picturebox acts exactly like I want. But when I add it to the panel, the pictureBox expands to fit the image.
Below is the code:
private PictureBox globalPicBox = (PictureBox)null;
private void Form1_Load(object sender, EventArgs e)
{
this.globalPicBox = new PictureBox();
this.globalPicBox.Name = "a";
this.globalPicBox.Tag = (object)"a";
this.globalPicBox.SizeMode = PictureBoxSizeMode.StretchImage;
this.globalPicBox.Top = 50;
this.globalPicBox.Left = 50;
this.globalPicBox.Height = 100;
this.globalPicBox.Width = 100;
this.globalPicBox.Image = Image.FromFile(#"C:\Users\PC\Downloads\Photo.jpg");
this.globalPicBox.BorderStyle = BorderStyle.FixedSingle;
this.globalPicBox.AutoSize = true;
this.panel1.Controls.Add((Control)this.globalPicBox);
}
What is the problem? And why?
Based on your edit ... set globalPicBox.AutoSize = false and it'll work.
If it doesn't please check the rest of your code for changes to globalPicBox's AutoSize, SizeMode and Dock parameters and hopefully you'll find your answer!
Simple Just Set globalPicBox.SizeMode=Strech
The image will shrink or stretch to meet the picturebox size and your picture box will not expand or shrink it will remain the same size
I'm writing a program where the user should be able to write text in a TextBox. I'd like the TextBox to resize itself, so it fits to the content.
I've tried the following:
private void textBoxTitle_TextChanged(object sender, TextChangedEventArgs e)
{
System.Drawing.Font myFont = new System.Drawing.Font("Verdana", 8);
System.Drawing.SizeF mySize = e.Graphics.MeasureString("This is a test", myFont);
this.textBoxTitle.Width = (int)Math.Round(mySize.Width, 0);
}
I get an error saying that Graphics doesn't work for TextChangedEventArgs. Is there another way I can resize the TextBox?
You should try a code something like below. It has worked for me well.
private void textBox1_TextChanged(object sender, EventArgs e)
{
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
textBox1.Height = size.Height;
}
For more information refer to TextRenderer.MeasureText()
I am adding this answer as I do not see the fixed width aspect of a textbox being discussed in any of the other. If you have a fixed width for your textbox, and you want to adjust only its height you can do something like the following:
Something like this gives the height of the text as how it is drawn in the multiline wordwrapped textbox itself:
SizeF MessageSize = MyTextBoxControl.CreateGraphics()
.MeasureString(MyTextBoxControl.Text,
MyTextBoxControl.Font,
MyTextBoxControl.Width,
new StringFormat(0));
I am not sure what StringFormat should be but the values StringFormatFlags do not seem to apply to a default TextBox make up.
Now with MessageSize.Height you know the height of the text in the textbox.
I had the same problem and I solved it in a simpler way.
I used the AutoSize property of a Label control.. I added an invisible label to my form, set its AutoSize property True. When the I need to change the size of my TextBox I use this code:
MyLabel.Text = MyTextBox.Text;
MyTextBox.Size = MyLabel.Size;
I set the Maximum and Minimum Size of the label for better results.
Have Fun
Your binding to the wrong event, and you cannot use the graphics object in the TextChangedEventArgs object.
Try using the TextChanged event. The following snippet is working:
public Form1()
{
InitializeComponent();
this.textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
}
void textBox1_TextChanged(object sender, EventArgs e)
{
System.Drawing.SizeF mySize = new System.Drawing.SizeF();
// Use the textbox font
System.Drawing.Font myFont = textBox1.Font;
using (Graphics g = this.CreateGraphics())
{
// Get the size given the string and the font
mySize = g.MeasureString(textBox1.Text, myFont);
}
// Resize the textbox
this.textBox1.Width = (int)Math.Round(mySize.Width, 0);
}
}
first, create method to Make the TextBox fit its contents.
private void AutoSizeTextBox(TextBox txt)
{
const int x_margin = 0;
const int y_margin = 2;
Size size = TextRenderer.MeasureText(txt.Text, txt.Font);
txt.ClientSize =
new Size(size.Width + x_margin, size.Height + y_margin);
}
then with the TextChanged event handler calls AutoSizeTextBox() function to make the TextBox fit its text when the text changes.
private void txtContents_TextChanged(object sender, EventArgs e)
{
AutoSizeTextBox(sender as TextBox);
}
That’s all, for more info:
resize-a-textbox-to-fit-its-text
You will need to use the CreateGraphics() method of the form to create the Graphics instance to measure the string on.
The TextChangedEventArgs class does not have a Graphics property, that is a property of the PaintEventArgs class passed in to the Paint event handler
Try this:
using System.Drawing;
...
private void textBoxTitle_TextChanged(object sender, TextChangedEventArgs e)
{
// Determine the correct size for the text box based on its text length
// get the current text box safely
TextBox tb = sender as TextBox;
if (tb == null) return;
SizeF stringSize;
// create a graphics object for this form
using(Graphics gfx = this.CreateGraphics())
{
// Get the size given the string and the font
stringSize = gfx.MeasureString(tb.Text, tb.Font);
}
// Resize the textbox
tb.Width = (int)Math.Round(stringSize.Width, 0);
}
Essentially you create your own Graphics object for the form, then measure it based on the text and font of the TextBox. The using will properly dispose the Graphics object - your previous code would have leaked horribly!
Whatever the aim is.
If the size of the textbox should be dynamically set up based on the string, which should be the text inside this box, there is no nice option.
Reasons : MeasureString uses usual string formatters as delimiters for its own width and height.
Means, carriage return and line feed are parsed, too. Resulting in a sizeF.Width and sizeF.Height.
Depending on the string( and its font and number of lines ) these both variables can carry values, which are sometimes useless to be used as width/height values of a textbox ( because they can be bigger than the parentform's values and this would resize the textbox to a size, with left and bottom borders beyond those of the parent form).
Some solutions are still available, depending on the aim, one would like to achieve.
One idea would be :
Create a textbox in designer, size = 100 X 100. enable word-wrapping.
In the OnTextChanged event handler of the textbox, we just resize the textbox's width to a value, defined by ourself (e.g. parentform.Width or another hard value ).
This would cause the word wrap to recalculate the string in the textbox and this would rearrange all the characters inside the textbox, because word wrap is enabled.
The height of the textbox could can be set hard to parentform.Height, for example.
BUT,
better : set the height dynamically,based on the Y value of the ReturnValue (Point) of the method texbox.GetPositionFromCharIndex(textbox.TextLength -1 ).
Then, with Math.Min() determine, which is smaller ( either parentform.Height or Point.Y ) , and reset the textbox size to new Size(previousDeterminedWidth, nowDeterminedHeight).
Please keep in mind ( if scrollbars are enabled ) to add about 17 pixs to Your width calculation.
Best regards
Did you try to set yourTextBox.AutoSize = true;?
This property may be hidden in the GUI designer, but you can set it in the form constructor right after InitializeComponent(); call.
Graphics.Measure string you can do o PaintEventArgs, not on TextChangedEventArgs
What I think you want is this
System.Drawing.Font myFont = new System.Drawing.Font("Verdana", 8);
Graphics graphics = this.CreateGraphics();
SizeF textSize = graphics.MeasureString("This is a test", myFont);
The problem is that you just cannot create a Graphics object by simply allocating it since it has no public constructor, so you should better go and use TextRenderer.MeasureText, as done in http://msdn.microsoft.com/en-us/library/y4xdbe66.aspx
TextRenderer is less accurate because it uses GDI and Graphics uses GDI+, so maybe you should leave a little margin on the value you get from the Width property.
Hope this helps
How to navigate the image using Keyboard arrow keys in C#.
My 1st form contains listView. Listview contains 10 images in thumbnail format.Images are from perticular folder. When i double click the image in the list view, its opening in a new window as large image. I want to navigate the image in the new window as per listview order.
If i click the image randomly, want to navigate the image from that selected image.
Its like a Microsoft picture manager.
Plz give me an Idea.
Set your form's KeyPreview property to True. Then add this line of code to the top of your CS file:
using System.IO;
Next, inside the scope of your form, add these two lines:
private FileInfo[] _files;
private int _currentFile;
In your form's Load event, put this code:
DirectoryInfo dirinfo = new DirectoryInfo(
Path.Combine(Application.StartupPath, "images"));
_files = dirinfo.GetFiles();
_currentFile = 0;
Bitmap bmp = (Bitmap)Bitmap.FromFile(_files[_currentFile].FullName);
pictureBox1.Image = bmp;
Finally, in your form's KeyDown event, put this code:
if (e.KeyCode == Keys.Down)
{
_currentFile--;
if (_currentFile < 0)
{
_currentFile = _files.Length - 1;
}
}
else if (e.KeyCode == Keys.Up)
{
_currentFile++;
if (_currentFile >= _files.Length)
{
_currentFile = 0;
}
}
Bitmap bmp = (Bitmap)Bitmap.FromFile(_files[_currentFile].FullName);
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
}
pictureBox1.Image = bmp;
This code assumes that you have a PictureBox on your form named "pictureBox1", and it assumes that you have a folder named "\images" in your application folder that contains the image files you wish to display.
As o.k.w. mentioned in a comment, you may want to enhance this code by resizing the PictureBox to fit the dimensions of the image file. You can do that by setting the SizeMode property of your PictureBox to AutoSize (or set it to CenterImage, if you wish to keep the overall image centered on your form).