Windows Forms Application Exits after Changing Theme
I am creating an application that has a RichTextBox
that has text of varying colors based on what the information represents (red for errors, black for standard messages, etc). I am attempting to support Windows themes, and the possible variance of system colors. To do this, I created a method of changing the default text colors based on the Window
system color, by making each color either lighter or darker, so it contrasts well.
However, while testing this system, I found that if I change the theme while the program is running, it silently exits, without any explanation or even an exception. It just exits. I tried placing a breakpoint after the call to Application.Run
, and Windows hung at the "Please wait..." screen Explorer puts up while it modifies the theme. After a minute, the screen went away, and, sure enough, the breakpoint had been hit, which means that it doesn't kill the process outright.
My question is, why does it do this, and开发者_开发问答 is there a way I can stop it from doing this?
Thanks.
The better way to debug this is to add a FormClosing event handler to your form and set a breakpoint on it. When it breaks, the callstack reveals what code is calling the Close() method.
One classic failure mode with the SystemEvents.UserPreferenceChanged event you are using is forgetting to unregister your event handler when a form closes. It is a static event, it will prevent the form that wires the event from getting garbage collected. When the event fires, you're very likely to get an ObjectDisposedException. But that's just a guess.
The surprising thing to me when I started doing winforms after a long time doing ASP.NET was that it just ate exceptions without a word. You have to wrap you Application.Run(new MDIParent1()) in a try catch block.
Also, do you have:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
精彩评论