Optimizing repeated code - c#

I have alot of methods who use same line of code:
title.Font = new Font("Arial", 12, FontStyle.Bold);
I want to optimize it and just call another function instead create a new font foreach method so I try something like this:
void titleFont()
{
var font = new Font("Arial", 12, FontStyle.Bold);
return ;
}
and then call as:
title.Font = titleFont();
But I get
The name 'titleFont' does not exist in the current context
What am I doing wrong? Regards

The method is likely not accessible due to scope. By making it public, it is available to all callers. Also, your method needs to return your font or the font variable doesn't get set to anything. The code below replaces void with Font so that the method itself will return the value of the internal font variable upon returning.
public Font titleFont()
{
var font = new Font("Arial", 12, FontStyle.Bold);
return font;
}

your return type is void, change that to font
public Font titleFont()
{
Font fnt = new Font("Arial", 12, FontStyle.Bold);
return fnt ;
}
and yes the error is because you are not using the reference properly suppose you have the method in a class f suppose and is non static method then you have to Create object of f class and call that method.

Related

Font Size change KerningAdjustment, why?

I solved the problem, I created a function where I just pass the value of the spacing I need and the TextField
public static void ChangeSpaceBetweenCharacters(this UITextField textField, float space)
{
textField.WeakDefaultTextAttributes.SetValueForKey(NSObject.FromObject((nfloat)space), UIStringAttributeKey.KerningAdjustment);
}
Best regards,
Rafael Santos
I think the problem may be caused by the font method you use, I can't make it work with:
UIFont("ArialMT", 13)
Instead, you can use :
Font = UIFont.FromName("ArialMT", 13),
Or
Font = UIFont.SystemFontOfSize(10),
I test below sample code and it works for me:
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
NSMutableAttributedString mtText = new NSMutableAttributedString("testTextfield", new UIStringAttributes
{
Font = UIFont.SystemFontOfSize(10),
KerningAdjustment = 8.0f
});
UITextField textField = new UITextField();
textField.Frame = new CoreGraphics.CGRect(10,20,350,50);
textField.AttributedText = mtText;
Add(textField);
}

How to create unstable font sizes?

I have created a TextBox on the code
RichTextBox tb3 = new RichTextBox();
Then I wrote an other code (in the same void) to change it's font:
tb3.Font.Size(FontSize.Text);
But the following error appeares : "non-invocable member 'Font Size' cannot be used like a method.
Note: "FontSize" is an ID for a textbox.
How can I do it without creating a new Font?
Please help!
tb3.Font.Size isn't a method, it is
public float Size { get; }
and you can't change it so.
if you want to change font see it -> link1
and it link2
you should create new font, for example:
tb3.Font = new Font(tb3.Font.FontFamily, 23, FontStyle.Regular);

What is the best way to create customized Windows Form controls?

I'm making C# Windows Form application that has many forms that use many textboxes and labels of the same properties and style.
Instead of changing properties of every textbox and every label I created class called MyTextBox that inherits from System.Windows.Forms.TextBox and then changed its properties in class constructor like this:
class MyTextBox:TextBox
{
public MyTextBox()
{
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Font = new System.Drawing.Font("Bookman Old Style", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.Blue;
this.Size = new System.Drawing.Size(257, 23);
}
}
After building project class appeared in toolbox and by making instances from this class on my form it worked fine.
The problem is that when I change any of the properties in MyTextBox class and rebuilding project, changes do not apply to the already instanced objects and when I looked at the designer code, I found that the IDE copied all properties from MyTextBox class to the designer code so I have to recreate all my instances after any change to class code.
private void InitializeComponent()
{
this.MyTextBox1 = new WindowsFormsApplication9.MyTextBox();
this.SuspendLayout();
//
// MyTextBox1
//
this.MyTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.MyTextBox1.Font = new System.Drawing.Font("Bookman Old Style", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.MyTextBox1.ForeColor = System.Drawing.Color.Blue;
this.MyTextBox1.Location = new System.Drawing.Point(67, 43);
Any way to solve this problem? I want any changes to the class code applied to all already instanced objects without need to recreate them or if there is a better way please help.
Suppose I need to be controlling 5 properties of MyTextBox instance like ForeColor,default Width, default Font Style , default Font size and BorderStyle. All of them except Width property are not supposed to have other value than default value.
First you should provide suitable default values for properties in constructor. Then you should override or shadow properties and decorate them with one of these attributes:
[DefaultValue]
The designer will serialize these properties only if the value of theme is different than the default value which you set in the attribute.
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
The designer will not serialize values of these properties.
Code
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
public partial class MyTextBox : TextBox
{
public MyTextBox()
{
this.ForeColor = Color.Red;
this.Font = new Font("Tahoma", 9, FontStyle.Italic);
this.Width = 200;
}
[DefaultValue(typeof(Color), "Red")]
public override Color ForeColor
{
get { return base.ForeColor; }
set { base.ForeColor = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Font Font
{
get { return base.Font; }
set { base.Font = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new Size Size
{
get { return base.Size; }
set { base.Size = value; }
}
}
In the above example, I created a custom TextBox having these features:
The default value for ForeColor is Color.Red. If you change value of ForeColor in instances of the control, the value will be serialized. If you change the default value in class, only those instances which their ForeColor was untouched will use new default value, other instances will use their ForeColor value.
The default value for Font is new Font("Tahoma", 9, FontStyle.Italic) and since we said to the designer to not serialize Font property, the new value for property will not be saved if you change the value of different instances and all instances will use default value which is set in constructor of MyTextBox.
For setting default Width which user can not change it using designer, I overrided Size and said the designer to not serialize it, so the width will be set to the default Width which I set in constructor.
A settings file should do what you want. Create a new settings file in your project, if one doesn't exist already, and add a new setting like this:
then in your custom TextBox override OnCreateControl
protected override void OnCreateControl() {
base.OnCreateControl();
ForeColor = Settings.Default.TextBox_ForeColor;
}
Now you can change ForeColor in the settings file and the changes will cascade to all instances of your custom TextBox. Follow the same pattern for Font, Size, etc, just be sure to set the correct Type in the settings file.

How to print information programmatically on a doc template?

I have an application in C# that would print invoices and payslips. The client have sent me a template which would be used for the day to day operations. I don't know how to print to it, though I already know how to print a programmatically made text file which contains the information from an access database.
How do I print the information on this kind of template? (This is only something I [found on Google][1] and is a good candidate for a simple invoice printing) The document template I have also have a LOGO..
Do it by mail merge in Word. Using this technique you create Word document. Inside document you create placeholders for text. And from code you fill placeholders with whatever you want.
For example:
In word document type ctrl + F9
Right click on field and Edit field
Choose MergeField
On field name type FirstName
Add code:
.
var document = new Document("document.docx");
var sqlCommand = "SELECT TOP 1 userName FirstName FROM Users";
var table = GetTable(sqlCommand, String.Empty);
document.MailMerge.Execute(table);
I've been using the PrintDocument and PrintPreview objects. That use the the Graphics class. When print is called you get an "PrintEventArgs e" object. Then you can use e.Graphics to have access to things like e.Graphics.DrawString, .DrawImage etc.
I built a whole print objects class that overrides print. So I have a detail box that has different fonts, or a logo, a header, leagal jargon etc. Each one of these has it's own class. I put them all in a big list and I call printThis(List); and it will take each print function and the coordinates and make me a form.
Inherited object
class formHdr : printObject
{
private string headerText;
public formHdr(string hText)
: base()
{
headerText = hText;
}
public override void printThis(System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString(headerText, FRHEADER, Brushes.Black, BaseX, BaseY);
}
}
Base class
abstract class printObject
{
protected Font FTHEADER;
protected Font NRML;
protected Font DETAIL;
protected Font FRHEADER;
protected Font DETHEADER;
protected Font LEGAL;
protected Font LEGAL2;
public int baseX, baseY;
public int boxSX, boxSY;
public printObject()
{
baseX = 0;
baseY = 0;
boxSX = 0;
boxSY = 0;
FTHEADER = new Font("Arial", 12, FontStyle.Bold);
NRML = new Font("Calibri", 10);
DETAIL = new Font("Consolas", 8);
FRHEADER = new Font("Arial", 16, FontStyle.Bold);
DETHEADER = new Font("Calibri", 10, FontStyle.Bold);
LEGAL = new Font("Arial", 8);
LEGAL2 = new Font("Arial", 10);
}
public virtual void printThis(PrintPageEventArgs e) { }
Object creation
mainHead = new formHdr("Bill of Lading/Weigh slip Original");
mainHead.BaseX = 225;
mainHead.BaseY = 20;
bol.Add(mainHead);
Maybe this can get you started? I'm still tweaking it and will be interested in other responses.

C# How to change font of a label

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;
}
Font.Name, Font.XYZProperty, etc are readonly as Font is an immutable object, so you need to specify a new Font object to replace it:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
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:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
You need to create a new Font
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
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
private void SetFont(Form f, string name, int size, FontStyle style)
{
Font replacementFont = new Font(name, size, style);
f.Font = replacementFont;
}
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.
/// To call the function do this.
/// e.g in the form load event etc.
public Form1()
{
InitializeComponent();
SetFont(this, "Arial", 8, FontStyle.Bold);
// This sets the whole form and
// everything below it.
// Shaun Cassidy.
}
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
/// and then import the namespace
using Droitech.TextFont;
/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);
Simple.
this.lblMessage.Font = new Font("arial", this.lblName.Font.Size);

Categories