• 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

    • Rufus 4.8 brings performance boost for Windows ISOs by Sayan Sen Rufus, perhaps the most popular bootable USB media creation utility, has received a significant update with version 4.8. That's because there is a major shift toward faster and more efficient processing of Windows installation media by switching to wimlib for all Windows Imaging (WIM) handlings. The Rufus author says that the change has led to a significant improvement in speed when opening Windows ISOs, and this should be great for such users who tend to work with Windows installation files fairly regularly. Rufus notes that Wimlib’s integration speeds up the Windows ISO processing, reducing waiting times during image analysis. This boost in speed is said to be particularly noticeable when creating Windows To Go drives, although if you have a "crap" drive, it is best not to expect "miracles". For those wondering, Wimlib is an open source library for creating, extracting, and modifying Windows Imaging (WIM) archives, and it is cross platform too. Another key update in Rufus 4.8 is the introduction of file splitting for files over 4GB using the Alt-E key, for managing larger installation files; however, performance gains in this area are still modest when compared to the UEFI:NTFS handling. On the development side, Rufus 4.8 has moved exclusively to Visual Studio binaries. The full changelog is given below: Switch to wimlib for all WIM image processing: Greatly speeds up image analysis when opening Windows ISOs Can speed up Windows To Go drive creation Might help with Parallels limitations on Mac (But Rufus on Parallels is still unsupported) Enables the splitting of >4GB files with Alt-E (But still WAY SLOWER than using UEFI:NTFS) Switch to using Visual Studio binaries everywhere, due to MinGW DLL delay-loading limitations Add more exceptions for Linux ISOs that restrict themselves to DD mode (Nobara, openSUSE, ...) Improve reporting of UEFI bootloaders in the log, with info on the Secure Boot status Fix an issue with size limitations when writing an uncompressed VHD back to the same drive Fix a crash when opening the log with the 32-bit MinGW compiled version Fix commandline parameters not being forwarded to original Windows setup.exe To download Rufus 4.8, head over to Neowin software stories page. You can also download it from the official website or from its GitHub repo.
    • That's very interesting, thanks for the link!
    • When I hear "shady" I assume there is some element of being dishonest. There is nothing directly dishonest about publishing a crappy book, people have done that long before AI...it just took a lot more time. I am not about the proliferation of AI slop, so I hate this, but I wouldn't call it shady.
    • Soon(TM). When Elon Musky claims something is coming soon, that means 4-5 years late, 50% more expensive and still buggy as hell. Why are people still drinking his Koolaid? Also how stupid are investors still throwing at Tesla and Elon for all these years while they deliver no god damn results? Where are ever promised Robotaxies? Where is the Semi? Where is the Roadster? We already know the outcome of the Cybercock garbage container. Like, how stupid you have to be to still invest ANY money into Elon Musks stupidities?
    • Google Workspace brings 10 free AI features for nonprofit organizations by Aditya Tiwari Google has announced several updates for nonprofit and charitable organizations that use its products and services. For starters, the search giant is expanding the Google for Nonprofits program to more than 100 countries globally. Google for Nonprofits has been around for over a decade, offering products and services to eligible nonprofits for free or at discounted rates. One of its verticals is Workspace for Nonprofits, a paid tier that provides nonprofits with no-cost access to Gmail, Calendar, Meet, and its AI apps, such as Gemini and NotebookLM. Google is bringing ten new AI features to the Workspace for Nonprofits tier as part of its new updates. The company surveyed over 9,000 nonprofit organizations earlier this year and said that about nine out of ten nonprofits reported positive productivity gains when using AI apps and features. However, only one out of five reported that at least half of their organization uses AI. That said, these are the new features coming to Workspace for Nonprofits without paying any money: Gems Audio Overviews in Gemini app Image generation with people in Gemini app Canvas and quizzes in Gemini app Deep Research in Gemini app Google Vids with custom video clips powered by Veo 2 Two-way conversations with Gemini Live NotebookLM with Summaries, Audio Overviews (50+ languages and length adjustment) and Q&A Mind Maps in NotebookLM Discover Sources in NotebookLM Most of these features are available in other Workspace plans intended for regular businesses. Google's Nonprofits tier supports up to 2,000 employees or volunteers at $0/user/month, who can have professional email addresses, take part in 150-participant video meetings, and share a pooled cloud storage capacity of 1TB. Additionally, nonprofits can also place ads in Google Maps to connect with people at a local level. The company said that it's "expanding Ad Grants to run on eligible Google Maps placements in Performance Max campaigns free of charge." These ads in Google Maps can appear above, below or beside search results.
  • Recent Achievements

    • Apprentice
      Cole Multipass went up a rank
      Apprentice
    • Posting Machine
      David Uzondu earned a badge
      Posting Machine
    • One Month Later
      Stokenking earned a badge
      One Month Later
    • One Month Later
      Kevin Jones earned a badge
      One Month Later
    • Week One Done
      Kevin Jones earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      526
    2. 2
      ATLien_0
      260
    3. 3
      +Edouard
      194
    4. 4
      +FloatingFatMan
      180
    5. 5
      snowy owl
      134
  • Tell a friend

    Love Neowin? Tell a friend!