I try Defining a Font Fallback Sequence in Code , i refer at here
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FontFamily f = new FontFamily("Comic Sans MS, Verdana");
}
}
but i have i error: "Additional information: Font 'Comic Sans MS, Verdana' cannot be found."
how to Defining a Font Fallback Sequence in Code.
Because "Comic Sans MS, Verdana" is no font name. You can define a font name array.And you can add names to this array.
string[] fontName = new string[] { "Comic Sans MS", "Verdana" };
FontFamily f = new FontFamily(fontName[0]);
I think FontFamily is not intended for that task, and I afraid there is no automatic fallback font for Windows Forms.
Take note that the sample is for System.Windows.Media from PresentationCore assy and not from System.Drawing.FontFamily.
You must try to load a Font manually and then check Name property before trying to assign to Form.Font
You can try this:
Font font = null;
string[] fontNames = {"Comic Sans MS","Verdana"};
foreach (var fontName in fontNames)
{
font = new Font(fontName, 12.0f);
if (font.Name == fontName) break;
}
this.Font = font;
You are using WinForms, but looking at the WPF documentation. The WinForms FontFamily class constructor doesn't support explicit fallback fonts. Only one font's face name can be specified for the FontFamily constructor. If it can't find that specified font, the operating system automatically selects a fallback, based on various heuristics (this article is very old, so some of these details have changed, but many of them are the same).
In general, WinForms applications should not hardcode a particular font. What you want to use in your UI is the standard, system dialog font, which you can obtain using SystemFonts.MessageBoxFont. Set it in the constructor for each of your forms, so that all child controls automatically pick it up, as advised here. This not only ensures that the font will be available, but it allows your UI to adapt to the user's preferences.
If you absolutely must hard-code a font, then you will need to enumerate the installed fonts and use a manual fallback algorithm—see if the font face you want exists in the enumerated list, and if not, fall back to an alternative. Note that "Comic Sans MS" and "Verdana" are both "safe" fonts; they'll be there on any Windows system that the .NET Framework can run on, unless the user has explicitly removed them. (And they might have. Comic Sans is an abomination.)
Perhaps an even better alternative (again, if you absolutely must have custom, non-standard fonts) would be to bundle the font(s) you need with your application. You can do this by creating a private font collection, which maintains fonts specifically for your application. A private font collection can include font files provided by the application vendor that are not installed on the system.
Related
I'm trying to replicate (not an exact replica) the CharMap program from windows in my program for inserting and adding symbols. Problem is that the symbols would work on a machine with Windows 7, 8 10 but some symbols wouldn't show on Windows XP.
Windows XP
Windows 7, 8, 10
I'm currently using the below to generate my symbols:
public static string CharToHex(char c)
{
return ((ushort)c).ToString("X4");
}
string x = CharToHex(Convert.ToChar(defaultSymbolsCollection[i]));
int value = int.Parse(x, System.Globalization.NumberStyles.HexNumber);
string symbol = char.ConvertFromUtf32(value).ToString();
AddSymbol(Convert.ToString((char)value);
Void AddSymbol(string _symbolText)
{
Button symbolButton = new Button()
{
Text = _symbolText,
Size = new Size(32, 32),
Font = new Font("Arial Unicode MS", 9),
Tag = _symbolText,
UseMnemonic = false,
};
symbolButton.Click += SymbolButton_Click;
pnl_SymbolHolder.Controls.Add(symbolButton);
}
This ends up working only on Windows 7, 8, 10 but not on Windows XP. some symbols don't show, instead is represented by a square and others do.
How do I go about solving this problem? my other alternative was to draw the symbols at the center of the button that way it's always there regardless because it was drawn but I would like to see other alternatives, perhaps a solution to this problem
The font "Arial Unicode MS" is not included with Windows XP/7/8/10, but is included with some Microsoft Office products. Windows XP is likely using "Tahoma" instead (the default UI font), which does not include glyphs for those symbols (whereas "Segoe UI", the default UI font on Windows 7/8/10, does).
For the characters to appear correctly, you will need to find/install/use a font that has glyphs for those characters.
I have an application and I need to use two languages in that application.
For example :
English
Arabic
But I don't know how could I do that. Anybody can help me for this?
I need some examples in C# Windows Forms.
Using Localizable and Language Property of Form
Form class have Localizable and Language Property. If you set Localizable property to true, you can add controls to form for default language and set properties for default language. Then you can select another languages and change properties for those languages. This way, value or localizable properties will store in separate resource files for different cultures.
Note: A property is considered as localizable if it's decorated with [Localizable(true)] attribute. For example BackColor property is not localizable, but Text property is localizable.
Localizing Messages and Images using Resx Resource Files
The project has a Rseources.Resx file under Properties folder which you can use for localizing images and messages. Also you can add .resx Resource files to project. For example you can create a Strings.resx file and add some string key and values to it, then copy it as strings.en.resx and strings.fa.resx and edit values for those languages. Then you can use those resource values, For example:
MessageBox.Show(Properties.Resources.AreYouSure);
Will show the value of AreYouSure from Resources.Resx file with the current UI culture language.
If a resource key not found for a culture or the specified culture not found for the resource file, value of the key in neutral culture of the Resx file will be used.
Change the language at Run-time
You can set the culture of a application to Persian using:
System.Threading.Thread.CurrentThread.CurrentCulture =
System.Globalization.CultureInfo.GetCultureInfo("fa");
System.Threading.Thread.CurrentThread.CurrentUICulture =
System.Globalization.CultureInfo.GetCultureInfo("fa");
You should put the above code at start of your application or before showing a form.
More information
For more information and Example:
Globalizing Windows Forms
Walkthrough: Localizing Windows Forms
How to: Set the Culture and UI Culture for Windows Forms Globalization
Using a resource file might be easier in some cases.
Add a new resource file to the project in Visual Studio.
eg. en_local.resxfor english fr_local.resx for french.
Open the resource file, in the strings, name your string and put different translation in the value cell. For example: next station's value inen_local.resx is next station but in fr_local.resx can be Prochaine station.
example as below:
In the code, use public static ResourceManager rm = new ResourceManager("WindowsFormsApp1.en_local", Assembly.GetExecutingAssembly());
to select the language resource.
When you need to output any string to the application, use function GetString(), for example label1.Text = rm.GetString("welcome");
There are some missing parts in wwjih123's answer.
In VS2017
1-First of all create resource in projects root folder (Not in Resources folder). Name it like lang_en, lang_tr, lang_fr etc...
2-then object properties window leave Build action as Embedded Resource
3-inside the lang_tr.resx file add new string lbl_error and value "Hata" in turkish (whatever you like)
4- inside the class define variables as:
ResourceManager res_man; // declare Resource manager to access to specific cultureinfo
5-in class initialization after InitializeComponent();
Console.WriteLine("You are speaking {0}",
System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName);
res_man = new ResourceManager("MyApp.lang_"+ System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, Assembly.GetExecutingAssembly());
lblError.Text = res_man.GetString("lbl_error");
if your ui language is Turkish it will automatically load the lang_tr.resx,
if english the lang_en.resx file will be loaded
etc...
good luck
Create an extension class and do as the following:
public static class TranslateToKurdish
{
public static void ToKurdish(this Control control,string kurdishText,float fontSize=10)
{
switch (control)
{
case TextBox textBox:
textBox.PlaceholderText = kurdishText;
textBox.RightToLeft = RightToLeft.Yes;
textBox.PlaceholderText = kurdishText;
textBox.Font = new Font("Calibri", fontSize, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
break;
case Label label:
label.Text = kurdishText;
label.RightToLeft = RightToLeft.Yes;
label.Font = new Font("Calibri", fontSize, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
break;
case Button button:
button.Text = kurdishText;
button.RightToLeft = RightToLeft.Yes;
button.Font = new Font("Calibri", fontSize, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
break;
}
}
}
then you can use in Form
if (userLanguage == stringLanguage)
{
isKurdishLanguage = true;
RightToLeft = RightToLeft.Yes;
RightToLeftLayout = true;
btnTruckTracking.Font = new Font("Calibri", 13.5F, FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
btnTruckTracking.ToKurdish(#"بارههڵگرهكان",12);
btnSearch.ToKurdish(#"گـــهڕان",12);
BtnProduct.ToKurdish(#"بـــهرهــهم",12);
btnCompany.ToKurdish(#"كــۆمپـانیـایهكـان",12);
btnUsers.ToKurdish(#"بهكارهێنهران",12);
btnClose.ToKurdish(#"داخســـتن",12);
}
In the code snippet below, i am trying to embed the rupee symbol in the generated pdf document, but the pdf is rendering it as a square box instead of the symbol.
Using MigraDoc, i have set the unicode property to 'true' and fontembedding to 'always', but it still does not work. Can anyone help me out with a solution to this?
string value = "1000";
dataRow.Cells[4].AddParagraph("₹");
I tried the HelloWorld MigraDoc sample, just changed the line const bool unicode = true; to true (was false) and added some Rupee signs to this line paragraph.AddFormattedText("Hello, World! ₹₹₹", TextFormat.Bold);.
It worked as expected.
Please note that MigraDoc uses the Verdana font by default. To see the Rupee sign, MigraDoc has to use a font that has the Rupee sign. With older Windows versions you will have to use another font, not Verdana.
Remarks on Neville's answer: you do not have to use XPrivateFontCollection if you use fonts that are installed on the computer.
If a program is deployed to many computers, XPrivateFontCollection can be used to avoid installing fonts on all those computers.
If you use a program only on one computer, just install the font and use it without the font collection.
Finally figured out a way for this , below is my solution for all those who are also facing the same problem:
Download and install the Rupee Font here
Next, set it as the default font in your Visual Studio project using these instructions
Create a fonts folder in your Visual Studio and add the downloaded font in step 1.
Now add the following code
XPrivateFontCollection pfc = XPrivateFontCollection.Global;
Uri myuri = new Uri(#"D:\Test
Projects\SampleProjects\PdfGeneration\fonts\Rupee_Foradian.ttf");
pfc.Add(myuri, "./#Rupee Foradian");
double value = 1000;
dataRow.Cells[4].Format.Font.Name = "Rupee Foradian";
CultureInfo cinfo = new CultureInfo("hi-IN");
NumberFormatInfo numinfo = cinfo.NumberFormat;
numinfo.CurrencySymbol = "₹";
dataRow.Cells[4].AddParagraph(value.ToString("C", numinfo));
Note: To type the '₹" symbol, use the tilde key
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Test if a Font is installed
let say Im using an installed font on the system:
new System.Drawing.Font("Arial", 120F);
everything is fine. Now if I would use a not existing font:
new System.Drawing.Font("IdoNotExistHaHa", 120F);
I dont get any exception. As I see, if I use a font that doesnt exist I get a standard font (arial?, not sure). Whatever, I would like to throw an exception if there is a not found font. How to?
MSDN says as following :
For more information about how to construct fonts, see How to:
Construct Font Families and Fonts. Windows Forms applications support
TrueType fonts and have limited support for OpenType fonts. If you
attempt to use a font that is not supported, or the font is not
installed on the machine that is running the application, the
Microsoft Sans Serif font will be substituted.
You can check the if the font is correct by doing as following :
var myFont = new Font(fontName)
if (myFont.Name != fontName )
{
throw new Exception()
}
You can see it in documentation itself, Font Constructor (String, Single)
Windows Forms applications support TrueType fonts and have limited
support for OpenType fonts. If the familyName parameter specifies a
font that is not installed on the machine running the application or
is not supported, Microsoft Sans Serif will be substituted.
In short, default font is Microsoft Sans Serif
You could check and see if the font is installed first.
From Jeff Hillman's answer here: Test if a Font is installed
string fontName = "Consolas";
float fontSize = 12;
Font fontTester = new Font(
fontName,
fontSize,
FontStyle.Regular,
GraphicsUnit.Pixel );
if ( fontTester.Name == fontName )
{
// Font exists
}
else
{
// Font doesn't exist
}
Obviously, you could then throw an exception if you wanted(as that is your original question), although I would recommend not to, throwing an exception is an expensive operation if you can handle the issue more gracefully without.
I'm trying to send khmer script(unicode) string to printer using PrintDocument provided by the .NET framework.
Unfortunately it seems to me that the Graphics.DrawString() does not render khmer script correctly.
Platform: Windows 7 Ultimate
IDE: VS 2010 Ultimate
Here is the sample code:
void printDoc_PrintPage(object sender, PrintPageEventArgs e)
{
var font = new Font("Khmer UI", 12);
var text = "សួស្តី"; // "Hello"
e.Graphics.DrawString(text, font, Brushes.Black, 100, 100);
}
mann,
I tested your code on a Form_Paint() handler, and I got exactly what you said.
But when I used this instead:
TextRenderer.DrawText(e.Graphics, text, font, new Point(100, 100), Color.Black);
It gave me the text the way you wanted it.
Try that on your printDoc_PrintPage().
Thanks Albin and Beemer for your active response.
After a few posts in c# google group. It's been confirmed that there is a bug in GDI+ that incorrectly show certain script ("Khmer" in this case) to a different wording.
A native win32 test application was created to verify the issue with GDI+ DrawString().
A bug report has been submitted to Microsoft Connect: http://connect.microsoft.com/VisualStudio/feedback/details/620081/