dotnet / winforms

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

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

Open CuteLeon opened 3 weeks ago

CuteLeon commented 3 weeks 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 3 weeks 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 1 week 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 1 week ago

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