C# 如何更改标签的字体
带有标签和“选项”按钮的表单。单击该按钮将打开一个新表单,其中包含 2 个单选按钮“字体 1”和“字体 2”以及两个按钮“应用”和“取消”。选择其中一个单选按钮并单击“应用”将使第一个表单上的标签更改字体。问题是如何更改字体,例如从 Tahoma 更改为 Arial 或标签的任何其他字体。
应用按钮的选项表单代码,如果单击该按钮将返回dialogresult.ok == true并更改第一个表单上标签的字体:
private void btnApply_Click(object sender, EventArgs e)
{
if (radioFont1.Checked)
{
mainForm.lblName.Font.Name = "Arial"; 'wrong attempt
}
this.DialogResult = DialogResult.OK;
}
第一个表单上的标签声明,以便它对第二个表单可见:
public static Label lblName = new Label();
...
private void mainForm_Load(object sender, EventArgs e)
{
lblName = lblBarName;
}
A form with a label and a button 'Options'. By clicking the button a new form opens with 2 radio buttons 'Font1' and 'Font2', and two buttons 'Apply' and 'Cancel'. Upon selecting one of the radio buttons and clicking 'Apply' will make the label on the first form change the font face. The problem is how to change the font as in from say Tahoma to Arial or to any other font face of the label.
Options form code for apply button, which if was clicked will return dialogresult.ok == true and change the font of the label on the first form:
private void btnApply_Click(object sender, EventArgs e)
{
if (radioFont1.Checked)
{
mainForm.lblName.Font.Name = "Arial"; 'wrong attempt
}
this.DialogResult = DialogResult.OK;
}
Declaration of the label on first form so that it is visible to second form:
public static Label lblName = new Label();
...
private void mainForm_Load(object sender, EventArgs e)
{
lblName = lblBarName;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Font.Name
、Font.XYZProperty
等都是只读的,因为Font
是一个不可变的对象,所以你需要指定一个新的Font
对象来替换它:检查
Font
类以获取更多选项。Font.Name
,Font.XYZProperty
, etc are readonly asFont
is an immutable object, so you need to specify a newFont
object to replace it:Check the constructor of the
Font
class for further options.字体一旦创建就无法更改 - 因此您需要创建一个新字体:
You can't change a Font once it's created - so you need to create a new one:
您需要创建一个新字体
You need to create a new Font
我注意到没有实际的完整代码答案,所以当我遇到这个问题时,我创建了一个函数,它确实改变了字体,可以轻松修改。 中对此进行了测试
我已经在XP SP3 和 Win 10 Pro 64
提示:将 Form 替换为 Label、RichTextBox、TextBox 或使用字体更改其字体的任何其他相关控件。通过使用上述函数,使其完全动态化。
你也可以,如果你想要一个完整的库,这样你就不必编写所有后端位,你可以从 Github 下载我的 dll。
Github DLL
简单。
I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in
- XP SP3 and Win 10 Pro 64
Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.
You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.
Github DLL
Simple.