2

给定以下方法:

public static void ExecuteAsync( this EventHandler eH, object sender, EventArgs eA ) {
    eH.GetInvocationList( ).Cast<EventHandler>( ).ToList( ).ForEach( e => {         
        e.BeginInvoke( sender, eA, IAR =>
            ( ( IAR as AsyncResult ).AsyncDelegate as EventHandler ).EndInvoke( IAR ), null );
    } );
}

我注意到e有一个属性 Target。

当我进一步研究它时,我发现我可以检查 ife.Target is System.Windows.Controls.Controle.Target is System.Windows.Forms.Control.

这太棒了,因为在使用这个扩展的情况下,为了方便(而且我很懒),我希望能够判断委托目标是否需要调用委托(在 WinForms 的情况下:Control.Invoke( foo );在 WPF 的情况下:) Control.Dispatcher.Invoke( foo )

我不需要知道如何将对象转换为它的实际类型(我可以没有它):我只需要知道我是否可以转换对象以便我可以访问InvokeRequired属性和Invoke方法(在WinForms 控件的情况)或Dispatcher属性(用于访问Dispatcher.CheckAccess( )函数和Dispatcher.Invoke( )方法)。

这可能吗?我该怎么做呢?(我尝试将 e.Target 转换为System.Windows.Control.Control但结果没有Dispatcher属性)。

编辑

根据对铸造代码(和进口/参考)的要求:

要确定它是否是 WPF 控件:

( if e.Target is System.Windows.Controls.Control ){ //Fully Qualified
    ( e.Target as System.Windows.Controls.Control)./*...*/;
}

要确定它是否是 WinForms 控件:

( if e.Target is System.Windows.Forms.Control ){ //Fully Qualified
    ( e.Target as System.Windows.Forms.Control )./*...*/;
}

该项目引用了几个库:

Microsoft.CSharp
MySql.Data
PresentationFramework
System
System.Configuration
System.Configuration.Install
System.Core
System.Data
System.Data.DataSetExtensions
System.Drawing
System.Management
System.Windows.Forms
System.Xml
System.Xml.Linq
4

1 回答 1

1

这对你不起作用。这不是最优雅的方式,但可以检查目标是 WPF 还是 WinForms 控件:

if (e.Target is System.Windows.Controls.Control)
{
    var wpfTarget = ((System.Windows.Controls.Control)e.Target);
    if (wpfTarget.Dispatcher.CheckAccess()) // check if on dispatcher thread
    {
        wpfTarget.Dispatcher.Invoke(/*...*/);
    }

}
else if (e.Target is System.Windows.Forms.Control)
{
    var formsTarget = (System.Windows.Forms.Control)e.Target;
    if (formsTarget.InvokeRequired)
    {
        formsTarget.Invoke(/*...*/);
    }
}

Dispatcher在 VisualStudio 中,我有 Intelisense 支持wpfTarget

在此处输入图像描述

编辑

在我包含的参考资料下方

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

其中只有四个在使用:

using System;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Windows;
于 2015-12-10T02:48:08.830 回答