Собственно код:
Form Form2 = new Form1();
Form2.Size = new System.Drawing.Size(1000, 300);
Form2.BackColor = System.Drawing.Color.Red;
Form2.MaximizeBox = false;
Form2.MinimizeBox = false;
Form2.FormBorderStyle = FormBorderStyle.FixedDialog;
Form2.Text = "CryptLocker Moscow";
Label text_for_user = new Label();
text_for_user.ForeColor = System.Drawing.Color.White;
text_for_user.Top = 100;
text_for_user.AutoSize = false;
text_for_user.Text = "HEY, USER!!!";
text_for_user.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
text_for_user.Size = new System.Drawing.Size(50, 50);
text_for_user.Font = new System.Drawing.Font("Arial", text_for_user.Font.Size);
text_for_user.Dock = System.Windows.Forms.DockStyle.Fill;
Form2.Controls.Add(text_for_user);
Application.Run(Form2);
Так вот, строчка:
text_for_user.Size = new System.Drawing.Size(50, 50);
является бессмысленной, так как есть она, нет ее, стоит ли там 50,50 или 500,500, при исполнении программы размер текста по факту не меняется. Что делать?
задан 25 сен 2015 в 18:26
Семён СавенкоСемён Савенко
731 золотой знак1 серебряный знак5 бронзовых знаков
4
Form Form2 = new Form1();
Form2.Size = new System.Drawing.Size(1000, 300);
Form2.BackColor = System.Drawing.Color.Red;
Form2.MaximizeBox = false;
Form2.MinimizeBox = false;
Form2.FormBorderStyle = FormBorderStyle.FixedDialog;
Form2.Text = "CryptLocker Moscow";
//Написание текста
Label text_for_user = new Label();
text_for_user.ForeColor = System.Drawing.Color.White;
text_for_user.Top = 150;
text_for_user.Left = 500;
text_for_user.AutoSize = false;
text_for_user.Text = "HEY, USER!!!";
text_for_user.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
text_for_user.Size= new System.Drawing.Size(50, 50);
text_for_user.Font = new System.Drawing.Font("Arial", 24, System.Drawing.FontStyle.Bold);
//text_for_user.Dock = System.Windows.Forms.DockStyle.Fill;
Form2.Controls.Add(text_for_user);
Application.Run(Form2);
ответ дан 25 сен 2015 в 18:49
Семён СавенкоСемён Савенко
731 золотой знак1 серебряный знак5 бронзовых знаков
В свойствах нужно найти Autosize и выбрать False)
ответ дан 20 фев 2017 в 7:43
Improve Article
Save Article
Improve Article
Save Article
In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the size of Label control using Size Property. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the Size property of the Label control using the following steps:
- Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp - Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
- Step 3: After drag and drop you will go to the properties of the Label control to set the Size property of the Label.
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the size of the Label control programmatically with the help of given syntax:
public System.Drawing.Size Size { get; set; }
Here, Size indicates the height and the width of the Label in pixel. Following steps are used to set the Size property of the Label:
- Step 1: Create a label using the Label() constructor is provided by the Label class.
// Creating label using Label class Label mylab = new Label();
- Step 2: After creating Label, set the Size property of the Label provided by the Label class.
// Set Size property of the label mylab.Size = new Size(120, 25);
- Step 3: And last add this Label control to form using Add() method.
// Add this label to the form this.Controls.Add(mylab);
Example:
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApp16 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Label mylab =
new
Label();
mylab.Text =
"GeeksforGeeks"
;
mylab.Location =
new
Point(222, 90);
mylab.Size =
new
Size(120, 25);
mylab.BorderStyle = BorderStyle.FixedSingle;
this
.Controls.Add(mylab);
}
}
}
Output:
I’m trying to allow user to resize a label (the control, not the font) before printing it.
For this I’m using a LabelPrint class and I’ve set AutoSize property to false. I already made a code that would adjust font size to my label size. But I can’t change the label size… Thanks for help, here’s the code.
class LabelPrint : Label
{
public LabelPrint()
{
this.ResizeRedraw = true;
this.AutoSize = false;
this.TextAlign = ContentAlignment.MiddleCenter;
this.Font = new Font(this.Font.FontFamily, 12);
this.SizeChanged += new EventHandler(this.SizeLabelFont);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x84)
{ // Trap WM_NCHITTEST
var pos = this.PointToClient(new Point(m.LParam.ToInt32()));
if (pos.X >= this.Size.Width - grab && pos.Y >= this.Size.Height - grab)
m.Result = new IntPtr(17); // HT_BOTTOMRIGHT
}
}
private const int grab = 16;
public void SizeLabelFont(object sender, EventArgs e)
{
// Only bother if there's text.
string txt = this.Text;
if (txt.Length > 0)
{
int best_size = 100;
// See how much room we have, allowing a bit
// for the Label's internal margin.
int wid = this.DisplayRectangle.Width - 3;
int hgt = this.DisplayRectangle.Height - 3;
// Make a Graphics object to measure the text.
using (Graphics gr = this.CreateGraphics())
{
for (int i = 1; i <= 100; i++)
{
using (Font test_font =
new Font(this.Font.FontFamily, i))
{
// See how much space the text would
// need, specifying a maximum width.
SizeF text_size =
gr.MeasureString(txt, test_font);
if ((text_size.Width > wid) ||
(text_size.Height > hgt))
{
best_size = i - 1;
break;
}
}
}
}
// Use that font size.
this.Font = new Font(this.Font.FontFamily, best_size);
}
}
}
I tried to add this in LabelPrint class:
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
base.AutoSize = false;
}
But I still get the same problem: AutoSize is set to false so when i increase the fontsize, i can’t see all my label.Text but I can’t resize the label itself… I mean with the mouse and ResizeRedraw().
I’m trying to allow user to resize a label (the control, not the font) before printing it.
For this I’m using a LabelPrint class and I’ve set AutoSize property to false. I already made a code that would adjust font size to my label size. But I can’t change the label size… Thanks for help, here’s the code.
class LabelPrint : Label
{
public LabelPrint()
{
this.ResizeRedraw = true;
this.AutoSize = false;
this.TextAlign = ContentAlignment.MiddleCenter;
this.Font = new Font(this.Font.FontFamily, 12);
this.SizeChanged += new EventHandler(this.SizeLabelFont);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x84)
{ // Trap WM_NCHITTEST
var pos = this.PointToClient(new Point(m.LParam.ToInt32()));
if (pos.X >= this.Size.Width - grab && pos.Y >= this.Size.Height - grab)
m.Result = new IntPtr(17); // HT_BOTTOMRIGHT
}
}
private const int grab = 16;
public void SizeLabelFont(object sender, EventArgs e)
{
// Only bother if there's text.
string txt = this.Text;
if (txt.Length > 0)
{
int best_size = 100;
// See how much room we have, allowing a bit
// for the Label's internal margin.
int wid = this.DisplayRectangle.Width - 3;
int hgt = this.DisplayRectangle.Height - 3;
// Make a Graphics object to measure the text.
using (Graphics gr = this.CreateGraphics())
{
for (int i = 1; i <= 100; i++)
{
using (Font test_font =
new Font(this.Font.FontFamily, i))
{
// See how much space the text would
// need, specifying a maximum width.
SizeF text_size =
gr.MeasureString(txt, test_font);
if ((text_size.Width > wid) ||
(text_size.Height > hgt))
{
best_size = i - 1;
break;
}
}
}
}
// Use that font size.
this.Font = new Font(this.Font.FontFamily, best_size);
}
}
}
I tried to add this in LabelPrint class:
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
base.AutoSize = false;
}
But I still get the same problem: AutoSize is set to false so when i increase the fontsize, i can’t see all my label.Text but I can’t resize the label itself… I mean with the mouse and ResizeRedraw().
Практическое руководство. Приведение размера элемента управления Label в соответствие с его содержимым в Windows Forms
Элемент управления Windows Forms Label может быть однострочным или многострочным, он может быть фиксированным по размеру либо автоматически изменять размер в соответствии с заголовком. Свойство AutoSize помогает менять размер элементов управления в соответствии с размером заголовка, что особенно полезно, если заголовок меняется во время выполнения.
Динамическое изменение размера элемента управления меткой в соответствии с его содержимым
- Для его свойства AutoSize задайте значение true .
Если для AutoSize задано значение false , слова, указанные в свойстве Text, переносятся на следующую строку, если это возможно, но элемент управления не будет увеличиваться.
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Мне надо в ходе программы изменить размер шрифта Label’а, а Visual Studio 2005 говорит, что параметр Label.Font.Size доступен только для чтения. Как тут быть?
Профиль
Группа: Участник
Сообщений: 523
Регистрация: 18.1.2008
Репутация: нет
Всего: 15
А в 2005 разве не так
Код |
Label1.FontSize = 30 |
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Вся проблема в том, что число в Label’е не помещается в заданном пространстве и «лезет» на соседние кнопки. Изменить дизайн нельзя, поменять шрифт заранее на маленький тоже нельзя, а мне надо сделать примерно следующее:
Код |
If TextBox.Text > 999999 Then Label.Font.Size = 35 End If |
А как я говорил, параметр Label.Font.Size доступен только для чтения.
Профиль
Группа: Модератор
Сообщений: 20516
Регистрация: 8.4.2004
Где: Зеленоград
Репутация: 1
Всего: 453
О(б)суждение моих действий — в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция — Администрация форума.
Профиль
Группа: Модератор
Сообщений: 20516
Регистрация: 8.4.2004
Где: Зеленоград
Репутация: 1
Всего: 453
О(б)суждение моих действий — в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция — Администрация форума.
Доктор Зло(диагност, настоящий, с лицензией и полномочиями)
Профиль
Группа: Модератор
Сообщений: 5817
Регистрация: 14.8.2008
Где: В Коньфпольте
Репутация: 8
Всего: 141
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
Доктор Зло(диагност, настоящий, с лицензией и полномочиями)
Профиль
Группа: Модератор
Сообщений: 5817
Регистрация: 14.8.2008
Где: В Коньфпольте
Репутация: 8
Всего: 141
Код |
Label1.Font = New Font(Label1.Font.FontFamily, Label1.Font.Size / 2) |
Профиль
Группа: Участник
Сообщений: 16
Регистрация: 11.8.2009
Репутация: нет
Всего: нет
- Прежде чем задать вопрос, воспользуйтесь поиском: возможно Ваш вопрос уже обсуждался и на него был получен ответ.
- Если такой же вопрос не найден, не стоит задавать свой вопрос в любую тему, создайте новую.
- Заголовок темы должен отображать ее суть.
- Содержание поста должно описывать проблему понятно, но в то же время, по возможности, лаконично. Сначала следует описать суть вопроса, потом можно привести пример кода, не вынуждайте других участников угадывать в чем Ваша проблема — телепатов здесь нет.
- Будьте взаимно вежливы и дружелюбны.
- При оформлении сообщений используйте форматирование, примеры кода заключайте в теги [CODE=vbnet][/CODE].
- Также ознакомьтесь с общими правилами, действующими на всем форуме.
- Если вопрос решен, не забывайте помечать тему решенной(вверху темы есть ссылка). Кроме того, если Вы хотите отблагодарить участников, оказавших помощь в решении, можно повысить им репутацию, в случае, если у Вас менее 100 сообщений в форуме и функция изменения репутации Вам недоступна, можете написать сюда.
- Общие вопросы по программированию на платформе .NET обсуждаются здесь.
- Литература по VB .NET обсуждается здесь.
Если Вам помогли и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, diadiavova.
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | VB .NET | Следующая тема » |
[ Время генерации скрипта: 0.1514 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Как изменить размер Label, Visual C#?
является бессмысленной, так как есть она, нет ее, стоит ли там 50,50 или 500,500, при исполнении программы размер текста по факту не меняется. Что делать?
В свойствах нужно найти Autosize и выбрать False)
Всё ещё ищете ответ? Посмотрите другие вопросы с метками c# winforms или задайте свой вопрос.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.10.42345
Нажимая «Принять все файлы cookie», вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
The <label> element specifies a text label for the <input> tag. Since it is an inline element, using the width property alone won’t have any effect. But there are some methods to add width to the <label> tag.
In this tutorial, we’ll demonstrate some examples of controlling the width of the <label> tag by using the display property set to “block” in combination with the width property.
- Usa a <form> element.
- Place the <label> tag with the for attribute and the <input> tag with the id, name, and type attributes inside the <form> element.
<form>
<label for="name">Enter your name:</label>
<input id="name" name="name" type="text" />
</form>
- Set the display to “block”.
- Specify the width.
label {
display: block;
width: 130px;
}
Example of adding width to the <label> tag using the «block» value of the display property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
label {
display: block;
width: 130px;
}
</style>
</head>
<body>
<form>
<label for="name">Enter your name:</label>
<input id="name" name="name" type="text" />
</form>
</body>
</html>
Result
Let’s see another example where we use the display property set to “inline-block”.
Example of adding width to the <label> tag using the «inline-block» value of the display property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
label {
display: inline-block;
width: 150px;
}
</style>
</head>
<body>
<form>
<label for="name">Enter your name:</label>
<input id="name" name="name" type="text" />
</form>
</body>
</html>