dotnet / winforms

Windows Forms is a .NET UI framework for building Windows desktop applications.
MIT License
4.42k stars 985 forks source link

Enhance WinForms Application static class to get current application context #11971

Open CuteLeon opened 2 months ago

CuteLeon commented 2 months ago

Background and motivation

I have a complex winform application and made multiple forms run message loops on independent threads, I registered ThreadException on each form's thread, and hope to get current form thread's application context in ThreadException event callback, to show a dialog with current application context's MainForm as dialog's owner (ensure alert shows in front of current thread's main form).

API Proposal

namespace System.Windows.Forms;

public sealed partial class Application
{
    public static ApplicationContext GetCurrentApplicationContext()
        => ThreadContext.FromCurrent().ApplicationContext;
}

API Usage

var owner = Application.GetCurrentApplicationContext().MainForm;

Alternative Designs

No response

Risks

Add a new method, no clearly risk.

Will this feature affect UI controls?

No; No; No;

CuteLeon commented 2 months ago

Workaround:

var currentThreadContext = typeof(WinApplication).Assembly
    .GetType("System.Windows.Forms.Application+ThreadContext")
    .GetMethod("FromCurrent", BindingFlags.Static | BindingFlags.NonPublic)
    .Invoke(default, default);
var currentApplicationContext = currentThreadContext
    .GetType()
    .GetProperty("ApplicationContext")
    .GetValue(currentThreadContext) as ApplicationContext;
var mainForm = currentApplicationContext.MainForm;
MessageBox.Show(mainForm, "Message content");
JeremyKuhne commented 2 months ago

To be safer it would probably be better to just expose the MainForm on Application (as a getter only). Would this work for you @CuteLeon?

CuteLeon commented 2 months ago

yes, it works for me as I only desire MainForm on current thread. PR updated.

CuteLeon commented 1 month ago

Hi @JeremyKuhne, would you please help to have a review on pr https://github.com/dotnet/winforms/pull/11972 ?

JeremyKuhne commented 1 month ago

I’ll look as soon as I am able. I’ll also need to take this through API review.