The Entry point method of C# Winform application looks as below,
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Here [STAThread] attribute decoration is essential to mark your application state as single-threaded apartment style.For details of STAThread attribute read What STAThread Attribute does?
Also check what is SetCompatibleTextRenderingDefault(false) ?
Here we look into Application.EnableVisualStyles()
What is EnableVisualStyles()?
Application.EnableVisualStyle() method empowers the app’s visual presentation with new visual appearance features of Operating systems such as Windows XP and later.. Colors, fonts, and other graphical elements come together to form a visual style for an OS. If both the control and the operating system permit it, controls will draw using visual styles.
Why Application.EnableVisualStyle Method Required?
This section explains about the need of Application.EnableVisualStyles() method. If you comment this line Application.EnableVisualStyles() and run the application you will see all the controls in your form are rendered with the classic Windows look only.
If you uncomment Application.EnableVisualStyles() and run the application you can see all your controls rendered with current operating system theme settings.
Means, If your operating system is Windows it will use the built-in Windows theming to style controls and classic Windows look and feel if EnableVisualStyle() is commented.
So it is not a method which if commented will cause the application to crash or stop working. It is essential to apply the visual styles like colors, fonts, and other visual elements to your form controls from the current operating system theme. If the control and the operating system support this controls will draw with visual styles if this method is used.
Also Application.EnableVisualStyles() method must be called as the first line in the Main method before calling any controls in the application to have the effect.
Summary
This post covered the relevance of Application.EnableVisualStyles() method. Application.EnableVisualStyles() must be called as the first line in Main() before invoking any controls.Your comments and feedback are valuable for us. So please provide your suggestions in the comments section below.
What is Application.SetCompatibleTextRenderingDefault(false)?
Reader Interactions
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
System.Windows.Forms.Application.EnableVisualStyles()
Here are the examples of the csharp api class System.Windows.Forms.Application.EnableVisualStyles() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
200 Examples
1. Example
Project: StarryEyes
Source File: Application.cs
public static void EnableVisualStyles() { WinForms.Application.EnableVisualStyles(); }
2. Example
Project: My-FyiReporting
Source File: MainWindow.xaml.cs
private void Window_Loaded_1(object sender, RoutedEventArgs e) { System.Windows.Forms.Application.EnableVisualStyles(); reportDesigner.OpenFile(@"C:\Users\Peter\Projects\My-FyiReporting\Examples\Examples\FileDirectoryTest.rdl"); }
3. Example
Project: FileHelpers
Source File: Main.cs
[STAThread] public static void Main(string[] args) { string destFile = null; if (args.Length > 1) destFile = args[0]; Application.EnableVisualStyles(); frmWizard frm = new frmWizard(); frm.ShowDialog(); frm.Dispose(); }
4. Example
Project: NetOffice
Source File: COMAddinBase.cs
protected internal virtual void EnableVisualStyles() { lock (_lock) { if (System.Windows.Forms.Application.VisualStyleState == System.Windows.Forms.VisualStyles.VisualStyleState.NoneEnabled) System.Windows.Forms.Application.EnableVisualStyles(); } }
5. Example
Project: QTTabBar
Source File: QTTabBarClass.cs
private static void InitializeStaticFields() { fInitialized = true; Application.EnableVisualStyles(); }
6. Example
Project: BloomDesktop
Source File: NewCollectionWizardTests.cs
[Test, Ignore("by hand")] public void RunWithoutWelcome() { Application.EnableVisualStyles(); Browser.SetUpXulRunner(); using (var dlg = new NewCollectionWizard(false)) { dlg.ShowDialog(); } }
7. Example
Project: BloomDesktop
Source File: NewCollectionWizardTests.cs
[Test, Ignore("by hand")] public void RunWithWelcome() { Application.EnableVisualStyles(); Browser.SetUpXulRunner(); using (var dlg = new NewCollectionWizard(true)) { dlg.ShowDialog(); } }
8. Example
Project: ClearCanvas
Source File: ChangePasswordDialog.cs
public bool Show() { System.Windows.Forms.Application.EnableVisualStyles(); if (_form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { return true; } else { return false; } }
9. Example
Project: ClearCanvas
Source File: LoginDialog.cs
public bool Show() { System.Windows.Forms.Application.EnableVisualStyles(); // if location was not set manually, centre the dialog in the screen _form.StartPosition = _form.Location == Point.Empty ? FormStartPosition.CenterScreen : FormStartPosition.Manual; return _form.ShowDialog() == DialogResult.OK; }
10. Example
Project: CSMSL
Source File: Examples.cs
[STAThread] private static void GuiExamples() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Peptide Calculator GUI Example //Application.Run(new PeptideCalculatorForm()); }
11. Example
Project: PassiveX
Source File: Program.cs
[STAThread] private static void Main(string[] args) { Application.EnableVisualStyles(); Application.Run(new MainForm()); }
12. Example
Project: mptanks2d
Source File: Program.cs
[STAThread] static void Main( string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (var g = new GameBuilder()) g.Run(); }
13. Example
Project: winappdriver
Source File: Overlay.cs
private void Start() { Application.EnableVisualStyles(); Application.Run(this.form); }
14. Example
Project: halcyon
Source File: GCHForm.cs
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new TesterForm()); }
15. Example
Project: bedrock
Source File: Program.cs
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Bootstrapper bootstrapper = new Bootstrapper(); bootstrapper.Run(); }
16. Example
Project: bedrock
Source File: Program.cs
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); QuickStartBootstrapper bootstrapper = new QuickStartBootstrapper(); bootstrapper.Run(); }
17. Example
Project: bedrock
Source File: Program.cs
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); UiCompositionBootstrapper bootstrapper = new UiCompositionBootstrapper(); bootstrapper.Run(); }
18. Example
Project: mutefm
Source File: Class1.cs
static void Main(string[] args) { Application.EnableVisualStyles(); Application.Run(new Form1()); }
19. Example
Project: dgrok
Source File: Program.cs
[STAThread] public static void Main(string[] args) { Application.EnableVisualStyles(); Application.Run(new MainForm()); }
20. Example
Project: Rainbow
Source File: Program.cs
[STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Form form = args.Length > 0 ? new MainForm(args[0]) : new MainForm(); form.StartPosition = FormStartPosition.CenterScreen; Application.Run(form); }
21. Example
Project: csla
Source File: Form1.cs
[STAThread] public static void Main() { Application.EnableVisualStyles(); Form1 newForm1 = new Form1(); Application.Run(newForm1); }
22. Example
Project: csla
Source File: Form2.cs
[STAThread] public static void RunForm2() { Application.EnableVisualStyles(); Form2 newForm2 = new Form2(); Application.Run(newForm2); }
23. Example
Project: nmqtt
Source File: .Main~.cs
[STAThread] public static void Main (string[] args) { Application.EnableVisualStyles(); Application.Run(new Shell()); }
24. Example
Project: nmqtt
Source File: Program.cs
[STAThread] public static void Main (string[] args) { Application.EnableVisualStyles(); Application.Run(new ShellForm(new ShellViewModel())); }
25. Example
Project: WinLess
Source File: Program.cs
[STAThread] static void Main(string[] args) { CommandArguments commandLineArguments = new CommandArguments(args); if (!commandLineArguments.ConsoleExit) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SingleInstanceController controller = new SingleInstanceController(); controller.Run(args); } }
26. Example
Project: WPF-Samples
Source File: MainWindow.cs
private void WindowLoaded(object sender, RoutedEventArgs e) { // Comment out the following line to disable visual // styles for the hosted Windows Forms control. Application.EnableVisualStyles(); // Create a WindowsFormsHost element to host // the Windows Forms control. var host = new WindowsFormsHost(); // Create a Windows Forms tab control. var tc = new TabControl(); tc.TabPages.Add("Tab1"); tc.TabPages.Add("Tab2"); // Assign the Windows Forms tab control as the hosted control. host.Child = tc; // Assign the host element to the parent Grid element. grid1.Children.Add(host); }
27. Example
Project: WPF-Samples
Source File: Program.cs
[STAThread] private static void Main() { //Run the application Application.EnableVisualStyles(); //System.Windows.Forms.Application.EnableRTLMirroring(); Application.Run(new Form1()); }
28. Example
Project: WPF-Samples
Source File: Program.cs
[STAThread] private static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); }
29. Example
Project: MvvmFx
Source File: Program.cs
[STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); new AppBootstrapper().Run(); }
30. Example
Project: RatioMaster.NET
Source File: Program.cs
[STAThread] internal static void Main() { Application.EnableVisualStyles(); //// Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); }
31. Example
Project: eve-o-preview
Source File: Program.cs
private static void InitializeWinFormsGui() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); }
32. Example
Project: Troschuetz.Random
Source File: FormMain.cs
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new FormMain()); }
33. Example
Project: scada
Source File: FrmMain.cs
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new FrmMain()); }
34. Example
Project: antipwny
Source File: Program.cs
static void Main(string[] args) { Application.EnableVisualStyles(); Application.Run(new AntiPwny()); }
35. Example
Project: NBi
Source File: Program.cs
[STAThread] static void Main(params string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += OnUnhandledException; var bootstrapper = new Bootstrapper(); bootstrapper.Boot(args); }
36. Example
Project: SpotifyToaster
Source File: MainSpotify.cs
public static void Main() { Application.EnableVisualStyles(); Application.Run(new ToastForm()); }
37. Example
Project: ShareX
Source File: Program.cs
private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Launcher.Run(args); }
38. Example
Project: cleanCore
Source File: Program.cs
[STAThread] static void Main() { Offsets.Initialize(); Pulse.OnFrame += OnFrame; Application.EnableVisualStyles(); Application.Run(new Form1()); }
39. Example
Project: swicli
Source File: Program.cs
[STAThread] static void Main() { Thread.CurrentThread.Name = "Client (STA)"; Application.EnableVisualStyles(); Application.Run(new FormClient()); }
40. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); _form = new formMain { ClientSize = new Size(640, 480) }; // Get the initial time. _lastTime = GorgonTiming.MillisecondsSinceStart; // Run the application with an idle loop. // // The form will still control the life time of the application (i.e. the close button will end the application). // However, you may specify only the idle method and use that to control the application life time, similar to // standard windows application in C++. // Other overloads allow using only the form and assigning the idle method at another time (if at all), or setting // up an application context object to manage the life time of the application (with or without an idle loop // method). Gorgon.Run(_form, Idle); } catch (Exception ex) { // Catch all exceptions here. If we had logging for the application enabled, then this // would record the exception in the log. GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(null, ex)); } }
41. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Get the initial time. _lastTime = GorgonTiming.MillisecondsSinceStart; // Run the application context with an idle loop. // // Here we specify that we want to run an application context and an idle loop. The idle loop // will kick in after the main form displays. Gorgon.Run(new Context(), Idle); } catch (Exception ex) { // Catch all exceptions here. If we had logging for the application enabled, then this // would record the exception in the log. GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(null, ex)); } }
42. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Gorgon.Run(new MainForm()); } catch (Exception ex) { GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(null, ex)); } }
43. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Gorgon.Run(new MainForm()); } catch (Exception ex) { GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(null, ex)); } }
44. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Gorgon.Run(new FormMain()); } catch (Exception ex) { GorgonDialogs.ErrorBox(null, ex); } }
45. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Gorgon.Run(new MainForm()); } catch (Exception ex) { GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(null, ex)); } }
46. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Gorgon.Run(new formMain()); } catch (Exception ex) { GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(null, ex)); } }
47. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Gorgon.Run(new formMain()); } catch (Exception ex) { GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(null, ex)); } }
48. Example
Project: Gorgon
Source File: Program.cs
[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Settings.Load(); Gorgon.PlugIns.AssemblyResolver = (appDomain, e) => appDomain.GetAssemblies() .FirstOrDefault(assembly => assembly.FullName == e.Name); Gorgon.Run(new AppContext()); } catch (Exception ex) { GorgonDialogs.ErrorBox(null, ex); } finally { Gorgon.PlugIns.AssemblyResolver = null; ContentManagement.UnloadCurrentContent(); // Clean up the plug-ins. foreach (var plugInItem in PlugIns.ContentPlugIns) { plugInItem.Value.Dispose(); } foreach (var plugInItem in PlugIns.WriterPlugIns) { plugInItem.Value.Dispose(); } // Shut down the graphics interface. if (ContentObject.Graphics != null) { ContentObject.Graphics.Dispose(); ContentObject.Graphics = null; } // Clean up temporary files in scratch area. if (Settings != null) { ScratchArea.DestroyScratchArea(); } EditorLogging.Close(); } }
49. Example
Project: RocketBot
Source File: Program.cs
[STAThread] private static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); }
50. Example
Project: ZetaResourceEditor
Source File: SkinHelper.cs
public static void InitializeAll() { DesignModeHelper.TurnOffDesignMode(); SkinManager.Default.RegisterAssembly(typeof(ZetaTestSkin).Assembly); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Below Windows Vista, use form skins. SkinManager.EnableFormSkinsIfNotVista(); //UserLookAndFeel.Default.ActiveLookAndFeel.SetSkinStyle(SkinNameDialogForms); UserLookAndFeel.Default.SetSkinStyle(SkinNameDialogForms); AppearanceObject.DefaultFont = StandardFont; _badc = new MyDefaultBarAndDockingController(); _badc.Apply(); }
Размещение в пользовательском окне элементов управления
Будем называть наш класс, наследующий от Form, пользовательским окном. Разместим в окне элемент управления типа кнопки, которая порождается классом Button. Все элементы управления являются визуальными и наследуют от класса Control. В следующей программе показано, как создать объект Button, поместить его на поверхность формы и подключить обработчик к событию Click этой кнопки. Продемонстрированы разные способы настройки и управления кнопками.
using System; using System.Windows.Forms; using System.Drawing; namespace MyApp { // Наследует библиотечному классу class MyForm : Form { // Конструктор с настройками public MyForm() { // Начальная настройка окна this.Text = "Форма с кнопками"; // Создание и настройка первой кнопки Button btn = new Button(); // Создаем первую объект-кнопку btn.Text = "Кнопка 1"; // Надпись на первой кнопке btn.AutoSize = true; // Подстройка размеров под надпись int left = (this.ClientSize.Width - btn.Width) / 2; int top = (this.ClientSize.Height - btn.Height) / 2; btn.Location = new Point(left, top); // Координаты кнопки в // клиентской области формы btn.Click += ButtonOnClick;// Подключение обработчика к событию Click btn.Parent = this; // Присоединяем к форме первую кнопку // и освобождаем ссылочную переменную // Создание и настройка второй кнопки btn = new Button(); // Используем освободившуюся адресную переменную btn.Text = "Кнопка 2"; btn.AutoSize = true; top += (this.ClientSize.Height - top) / 2; // Расположим ниже btn.Location = new Point(left, top); btn.Click += ButtonOnClick; // Присоединяем тот же обработчик btn.Enabled = false; // Сначала недоступна this.Controls.Add(btn); // Другой способ присоединения к форме btn = null; // Освобождаем ссылку } // Флаг состояния доступности (закрытое поле класса) private bool enableButton = true; void ButtonOnClick(object sender, EventArgs e) { if (enableButton) MessageBox.Show("Произошел щелчок на первой кнопке!"); else MessageBox.Show("Произошел щелчок на второй кнопке!"); // Перебираем коллекцию из двух кнопок и меняем доступность foreach (Control ctrl in this.Controls) ctrl.Enabled = !ctrl.Enabled; enableButton = !enableButton; } } }
Листинг
6.15 .
Код файла MyForm.cs
using System.Windows.Forms; // Лишние пространства имен удалили namespace MyApp { class EntryPoint { public static void Main() { Application.EnableVisualStyles(); Application.Run(new MyForm()); } } }
Листинг
6.16 .
Код файла Program.cs
Использованный в функции Main() метод Application.EnableVisualStyles() класса позволяет задать современный внешний вид для некоторых элементов управления. Созданная форма с кнопками будет такой
Размещенные на форме кнопки являются ее дочерними объектами и размещаются в коллекции Controls. Учитывая, что в нашем примере дочерними элементами являются только две кнопки, мы не принимали специальные меры для их распознавания. Но в более сложных случаях элементам нужно присваивать имена в их свойстве Name и распознавать уже по значению этого свойства. Для поиска конкретного объекта Control годится как простой перебор всех элементов коллекции Controls формы, так и метод System.Windows.Forms.Control.ControlCollection.Find(string, bool).
Все дочерние элементы формы располагаются в Z-порядке ( Z -последовательности), определяющим их видимость на экране, и могут перекрывать друг друга. Начальный Z -порядок определается порядком добавления элементов к форме и противоположен индексам элементов в коллекции формы: более поздние элементы отображаются верхними. Для изменения Z -порядка в процессе выполнения программы используются методы BringToFront() и SendToBack() класса Control.
Создание расширений элементов управления
В объектно-ориентированном программировании существует два способа передачи кода одного класса другому: это композиция и наследование. Композицией называется создание экземпляра одного класса внутри другого с последующим использованием объекта, а наследование передает код базового класса в производный неявно, сливая вместе два или целую цепочку классов.
Наследование применяют обычно к формам, а композицию — при размещении на форме библиотечных элементов управления. Но библиотечные элементы управления также можно использовать как базовые при наследовании, расширяя их производным классом.
Для примера создадим класс, расширяющий библиотечный класс Button, в котором определим такое поведение кнопки, что если надпись на ней не превышает заданную длину, то она остается недоступной на форме. Для изменения надписи кнопки предусмотрим текстовое поле ввода типа TextBox.
using System; using System.Windows.Forms; using System.Drawing; namespace MyApp { // Наследует библиотечному классу class MyForm : Form { // Локальные поля формы TextBox txtbox; ExtensionButton btn; // Конструктор с настройками public MyForm() { // Начальная настройка окна this.Text = "Форма с \"умной\" кнопкой"; // Создание и настройка объекта TextBox txtbox = new TextBox(); txtbox.Text = "Кнопка"; txtbox.CharacterCasing = CharacterCasing.Upper; txtbox.Width = 150; int left = (this.ClientSize.Width - txtbox.Width) / 2; int top = (this.ClientSize.Height - txtbox.Height) / 3; txtbox.Location = new Point(left, top); txtbox.Focus(); txtbox.Parent = this; // Подписка объекта TextBox на событие txtbox.TextChanged += new EventHandler(txtbox_TextChanged); // Создание и настройка объекта умной кнопки btn = new ExtensionButton(); // Создаем умную кнопку btn.StrTextBox = txtbox.Text; // Начальная надпись на кнопке btn.AutoSize = true; // Подстройка размеров под надпись left = (this.ClientSize.Width - btn.Width) / 2; top += (this.ClientSize.Height - top) / 2; btn.Location = new Point(left, top); btn.Parent = this; // Присоединяем кнопку к форме } void txtbox_TextChanged(object sender, EventArgs e) { // Меняем значение надписи на кнопке // с одновременным контролем доступности btn.StrTextBox = txtbox.Text; } } // Класс расширения кнопки class ExtensionButton : Button { // Локальное поле-константа private const int MIN_DISABLED = 5; // Публичное свойство public string StrTextBox { set { this.Text = value; bool enabled = value != null && value.Length > MIN_DISABLED; this.Enabled = enabled; } } } }
Листинг
6.17 .
Код файла MyForm.cs
using System.Windows.Forms; // Лишние пространства имен удалили namespace MyApp { class EntryPoint { public static void Main() { Application.EnableVisualStyles(); Application.Run(new MyForm()); } } }
Листинг
6.18 .
Код файла Program.cs
Результат выполнения программы будет таким
Автоматическое масштабирование окон
Проектируя приложение, разработчик не знает, на экранах с каким разрешением оно будет работать. Если не принять специальных мер, то при установке малых разрешений окно будет казаться большим, а при установке больших — маленьким относительно экрана. Для автоматического масштабирования окон приложения в зависимости от разрешения экрана в классе Form имеются два свойства: AutoScaleDimensions и AutoScaleMode, наследуемые от класса ContainerControl, которые и решают эту задачу.
Свойства должны задаваться точно в указанном ниже порядке:
AutoScaleDimensions = new Size(4, 8); AutoScaleMode = AutoScaleMode.Font;
или
AutoScaleDimensions = new SizeF(96, 96); AutoScaleMode = AutoScaleMode.Dpi
или
AutoScaleDimensions = new SizeF(120, 120); AutoScaleMode = AutoScaleMode.Dpi
Перечисление AutoScaleMode имеет значения: Dpi, Font, Inherit, None. Значение Font устанавливает привязку к размерам стандартного значения шрифта Windows, значение Dpi — к разрешению экрана.
Для правильного масштабирования приведенный код нужно располагать ближе к концу конструктора, когда уже задан размер клиентской области формы, созданы все элементы управления и назначены дочерними для формы.