winforms icon indicating copy to clipboard operation
winforms copied to clipboard

Enhance WinForms Application static class to get current application context

Open CuteLeon opened this issue 1 year ago • 5 comments

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 avatar Aug 23 '24 09:08 CuteLeon

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");

CuteLeon avatar Aug 26 '24 02:08 CuteLeon

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?

JeremyKuhne avatar Sep 10 '24 19:09 JeremyKuhne

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

CuteLeon avatar Sep 11 '24 06:09 CuteLeon

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

CuteLeon avatar Oct 11 '24 02:10 CuteLeon

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

JeremyKuhne avatar Oct 11 '24 18:10 JeremyKuhne