• 0

[C#] Is it possible to override the Form class?


Question

Sorry, forgot to say in the topic title that this is C#.

Let me explain what I want to do...

We all know that with Windows Vista brought a new UI font, Segoe UI, but XP still uses Tahoma as UI font. This doesn't help us programmers. I've searched in Google and what I found was to use SystemFonts.MessageBoxFont as the Form's font because all other controls Font properties will inherit from it.

Now, I could do this.font = SystemFonts.MessageBoxFont; before InitializeComponent(); on every single form I use but that will have 2 problems:

1) I'll have to repeat this line for every form.

2) The designer will not be updated accordingly.

If I moved this.font = SystemFonts.MessageBoxFont; into InitializeComponent() itself, then, the designer would be updated but I still would need to do it manually for every form.

My first solution:

Create a class (MyForm, for instance) that inherits from Form and change the properties I need in it's constructor. Then, every form I use in my application must be inherited from MyForm instead of Form. This is simpler than to place the line above in every InitializeComponent(), although, I still have to manually change every from to inherit from MyForm instead of Form.

To sum this up... I'm looking for a way (if possible) to change some default properties of Form without creating a new class that inherits from it, which allows me to make all the needed properties changes in one place and all my forms will still inherit from Form (as they are by default).

Is this possible?

Edited by Nazgulled

15 answers to this question

Recommended Posts

  • 0

What he means is create a class with static methods that you use to create instances of your forms:

public static class FormFactory
{
	public static TForm CreateForm<TForm>() where TForm : Form
	{
		TForm form = Activator.CreateInstance<TForm>();
		form.Font = SystemFonts.MessageBoxFont;

		return form;
	}
}

and then you would use it as such:

Form1 myForm = FormFactory.CreateForm<Form1>();

  • 0

Thanks for the suggestion and the whole code but that's almost like that I'm doing now... It's a different way of doing what I want but it's basically the same thing, what I mean is, I'll still need to manually create an instance for every form.

I may be looking for something that doesn't exist or it's not possible, but that's why I'm asking cause one doesn't know everything ;).

  • 0
  Nazgulled said:
Thanks for the suggestion and the whole code but that's almost like that I'm doing now... It's a different way of doing what I want but it's basically the same thing, what I mean is, I'll still need to manually create an instance for every form.

I may be looking for something that doesn't exist or it's not possible, but that's why I'm asking cause one doesn't know everything ;) .

  Quote
To sum this up... I'm looking for a way (if possible) to change some default properties of Form without creating a new class that inherits from it, which allows me to make all the needed properties changes in one place and all my forms will still inherit from Form (as they are by default).

Is this possible?

I'm confused... The method Antaris illustrated allows you to modify all your forms in one place, and have them all keep Form as their base. I don't know what else you're expecting it to do.

  • 0

Nazgulled, I think you might be getting confused with what is actually going on with your Form types.

Although the designer allows you to (as its name suggests) design the form, the form is still instantiated manually in code, its just that the program generates the code to do so. The factory method I illustrated could be used with your designed forms too. Just change the line of code that usually says:

Application.Run(new Form1());

which is generally found in the generated Program.cs, to this:

Application.Run(FormFactory.CreateForm<Form1>;());

All you are doing is using the factory method to apply any property changes ahead of the instance being returned. It doesn't matter if you use the designer, the Form is still being declared manually.

  • 0

But your method is not very different from my own (inheriting from a sub classed form) and that's not what I was looking for...

If I have 100 forms I'll have to do 100 modifications either using your method or mine and that's what I was looking to avoid... I was looking for a one time global change only, if there was one...

What I'm saying is, using my method, I'll have to inherit all my forms from the sub classed form. Using your method, I'll have to use the FormFactory for every form but there are the type of things I was looking to avoid.

Maybe that's not possible at all, but like I said, I don't know everything, so I just asked...

  • 0

Well, if thats the way you want to do it, do the following:

public class SubclassedForm : System.Windows.Forms.Form
{
	protected override void OnLoad(EventArgs e)
	{		
		base.OnLoad(e);
		this.Font = SystemFonts.MessageBoxFont;
	}
}

What you are doing is subclassing the form and overriding the OnLoad method (this is not the OnLoad event, but the method that will call any event subscribers). What will happen, is that any class that inherits from SubclassedForm will call the OnLoad method (unless the inheriting form overrides the OnLoad method itself, in which case it will need to make a call to base.OnLoad(e)).

To be honest, my personal preference is to go with the Factory pattern, as I believe it is much more flexible.

  • 0

You misunderstood the point... I already knew how to do it with inheritance but that's not what I want. Both solutions force me to do lots of code changes (depending on the number of forms) but that's not what I want. I was looking for a way to do one time change only, without needing to change their base class or how they are initialized.

Like I said, I'm probably looking for something that's not possible so just forget about it. Cause I don't know how to explain myself better than this.

Thanks for all your time guys.

  • 0

Its not that I misunderstood the point, the fact is there isn't a one time change. The Form type is sealed. The Designer type is sealed. VS uses that designer to generate code. It won't automatically set the font, because this is inherited from the base classes. You either need to inherit from the Form type, or follow the factory pattern and set your properties in the one place.

  • 0
  Nazgulled said:
You misunderstood the point... I already knew how to do it with inheritance but that's not what I want. Both solutions force me to do lots of code changes (depending on the number of forms) but that's not what I want. I was looking for a way to do one time change only, without needing to change their base class or how they are initialized.

Like I said, I'm probably looking for something that's not possible so just forget about it. Cause I don't know how to explain myself better than this.

Thanks for all your time guys.

If you have a refactoring tool, like Resharper, you should be able to accomplish the changes pretty easily, but I understand your apprehension. It's a lot of work manually, and a lot of regressions that could be introduced.

Good luck. :)

  • 0
  Antaris said:
Its not that I misunderstood the point, the fact is there isn't a one time change. The Form type is sealed. The Designer type is sealed. VS uses that designer to generate code. It won't automatically set the font, because this is inherited from the base classes. You either need to inherit from the Form type, or follow the factory pattern and set your properties in the one place.

That's exactly what I was asking :)

If that's how things works, I'm ok with it, I just wanted to know if it was or it wasn't possible.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Nice ad billboard for your living room...
    • Microsoft explains why Windows 10 users should upgrade to Windows 11 by Taras Buria Windows 10 reaches its end of support in four months, but not everyone is ready to move on. Some have unsupported hardware, some do not like its controversial parts, like the taskbar and Start menu, and others simply do not see a point. If you are one of those users who are unsure if they should leave Windows 10 behind, Microsoft has a list of reasons why Windows 11 is better and why you should upgrade. In the newly published blog post, Microsoft outlined several key features that make Windows 11 a better operating system, not just a poorly reskinned Windows 10, as some think. Microsoft quotes faster performance, simpler navigation, new features and experiences, and better security. Here are some of those reasons: Security: Making TPM 2.0 and implementing other security features like Smart App Control and VBS helped reduce security incidents. Microsoft claims "a reported 62% drop in security incidents and a 3x reported reduction in firmware attacks." Speed: Windows 11 features several Windows Update improvements that make update installation faster by up to 2.3 times than Windows 10. This is a pretty strong argument, considering how much people hate installing updates, especially on their PCs. Modernized user experience: Windows 11 has several productivity-boosting features like Snap Layouts, virtual desktop improvements, and more. Microsoft also mentions cleaner looks of the taskbar and Start menu, but we all know that those areas are the reason why many actually do not want to upgrade to Windows 11, even though some notable improvements are on the way. Accessibility improvements: This is legitimately a big reason to update if you rely on assistive technologies. Windows 11 is more accessible than its predecessor and features brand-new accessibility features like Voice Access, Focus Sessions for fewer distractions, Live Captions, Voice Typing, and more. You can check out an overview of all Windows 11 accessibility features here. New AI-powered features: Windows 11 has several exclusive AI features that are not available on Windows 10. They include Recall, Click to Do, AI-powered Windows Search, a Settings agent, Paint Cocreator, and more. However, these are only available on new devices, and you cannot get them when upgrading an existing PC from Windows 10 to 11. Still, some AI features work on all devices as well, such as the recently launched Copilot Vision. If those reasons are not enough, no worries. Microsoft lets users stay on Windows 10 even after the end of support. Today, Microsoft announced that the Extended Security Update program would be free for all customers. All you need to do is back up your PC settings in the Windows Backup app using your Microsoft Account (paid options are still present). You can learn more about that here. What about you? Do you think Windows 11 has enough solid reasons for you to switch and forget about Windows 10?
    • Without regulation, greed has no limits...If you go and post an ad on a billboard without permission, you'd be arrested for trespassing or vandalising private property, yet these companies keep doing it on our paid products scott-free. Be it "Smart" TVs, Phones in this case, displays/Tablets, Laptops, Desktops, etc. I'm eagerly waiting for the day the EU makes a regulation that requires these tech giants pay end users 50%+ for ANY form of further monetization on products users have paid for when that wasn't explicitly displayed on the product purchase page in normal 12pt sized font. Then and only then will all these nonsense "updates" introducing ads on our devices be put to an end.
    • The 75-inch Hisense U7 Series mini-LED TV drops to its all-time low price by Fiza Ali Amazon US is currently offering the 75-inch Hisense U7 Series Google Smart TV at its lowest price to date. So, if you are considering an upgrade to your home entertainment system, it may be worth a look. The U7 features Mini-LED Pro technology, providing a peak brightness of up to 1,500 nits alongside Full Array Local Dimming Pro for improved contrast. Its QLED Quantum Dot panel covers over a billion colours, delivering a wide colour gamut. Furthermore, the TV's Hi-View Engine PRO chipset uses deep-learning algorithms and technologies such as Dynamic Tone Mapping Pro, Face Detection, AI HDR Enhancement and AI Detail Enhancement to refine image quality. Its sound is handled by a 2.1 multi-channel system with three speakers, offering up to 40W of output and a built-in subwoofer. Moreover, the smart audio decoding supports a 2.1 surround-sound experience without the need for additional equipment. For gaming, the 144Hz Game Mode Pro offers a Variable Refresh Rate (VRR) from 48Hz to 144Hz, AMD FreeSync Premium Pro, Auto Low Latency Mode (ALLM), and Low Latency MEMC, helping to reduce screen tearing and input lag. When it comes to the connectivity options, this Google Smart TV includes two USB-A ports and two HDMI 2.1 ports which support 4K resolution at 60Hz. Additionally, it includes one HDMI 2.1 port with eARC technology and another HDMI 2.1 port, both supporting 4K resolution at 144Hz. 75-inch Hisense U7 Series Google Smart TV: $799.99 (Amazon US) - 11% off This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • Week One Done
      DrRonSr earned a badge
      Week One Done
    • Week One Done
      Sharon dixon earned a badge
      Week One Done
    • Dedicated
      Parallax Abstraction earned a badge
      Dedicated
    • First Post
      956400 earned a badge
      First Post
    • Week One Done
      davidfegan earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      618
    2. 2
      ATLien_0
      228
    3. 3
      +FloatingFatMan
      169
    4. 4
      Michael Scrip
      166
    5. 5
      Som
      146
  • Tell a friend

    Love Neowin? Tell a friend!