views:

351

answers:

5

I would like to modify the way my C#/.NET application works internally. I have dug into the .NET framework with Reflector and found a pretty good place where I could use a different implementation of a method. This is an internal class in the System.Windows.Forms namespace. You obviously cannot alter the code of this class with the usual means so I thought it would be possible to replace a method in there through reflection at runtime. The method I would like to entirely replace for my application is this:

public static WindowsFontQuality WindowsFontQualityFromTextRenderingHint(Graphics g)

in the class:

internal sealed class System.Windows.Forms.Internal.WindowsFont

Is there any way to load that type and replace the method at runtime, not affecting any other applications that are currently running or started afterwards? I have tried to load the type with Type.GetType() and similar things but failed so far.

+8  A: 

You may be able to do this with the debugger API - but it's a really, really bad idea.

For one thing, running with the debugger hooks installed may well be slower - but more importantly, tampering with the framework code could easily lead to unexpected behaviour. Do you know exactly how this method is used, in all possible scenarios, even within your own app?

It would also quite possibly have undesirable legal consequences, although you should consult a lawyer about that.

I would personally abandon this line of thinking and try to work out a different way to accomplish whatever it is you're trying to do.

Jon Skeet
+3  A: 
  1. Anything you do to make this happen would be an unsupported, unreliable hack that could break with any .NET Framework update
  2. There's another, more correct, way to do what you are trying to accomplish (and I don't need to know what you're trying to do to know this for certain).

Edit: If editing core Framework code is your interest, feel free to experiment with Mono, but don't expect to redistribute your modifications if they are application-specific. :)

280Z28
A: 

Though I cannot comment on Myra, because of reputation. Using extension methods is not the case here, as the TS is trying to replace a whole .Net function, which is indeed a very bad idea.

Try inherit the class you want to modify, and override the corresponding properties.

Jan Jongboom
The class is sealed.
Colin
A: 

Make a feature request to Microsoft, if your change is from general interest.

Christian13467
+1  A: 

I realy think, this is not good idea. But if you realy need it, you can use a Mono Cecil and change the assembly content. Then you need setup a config file for Redirecting Assembly Versions.

And last but not least, your advance will be propable illegal.

TcKs