将事件重定向到自定义控件内的处理程序

本文关键字:处理 程序 自定义控件 事件 重定向 | 更新日期: 2023-09-27 18:19:41

我有一个自定义控件。我需要重定向事件处理程序。我已经大幅削减了代码,试图阐明我想做什么。

public class RemoteDesktop : WindowsFormsHost
{
    public event OnConnectingEventHandler OnConnecting;
    public delegate void OnConnectingEventHandler(object sender, EventArgs Arguments);
    public event OnDisconnectingEventHandler OnDisconnecting;
    public delegate void OnDisconnectingEventHandler(Object sender, IMsTscAxEvents_OnDisconnectedEvent Arguments);
    private AxMsRdpClient7NotSafeForScripting RDPUserControl = new AxMsRdpClient7NotSafeForScripting();
    public RemoteDesktop()
    {
        this.RDPUserControl.BeginInit();
        this.RDPUserControl.SuspendLayout();
        base.Child = RDPUserControl;
        this.RDPUserControl.ResumeLayout();
        this.RDPUserControl.EndInit();
    }
}
public class RemoteDesktopViewModel
{
    public RemoteDesktopViewModel()
    {
        RemoteDesktop newRDC = new RemoteDesktop();
        newRDC.OnConnecting += new RemoteDesktop.OnConnectingEventHandler(newRDC_OnConnecting);
    }
    void newRDC_OnConnecting(object sender, EventArgs Arguments)
    {
        //DoStuff
    }
}

基本上一切都正常,我可以连接和断开与远程计算机的连接,但我无法在我的视图模型中发生激发的事件。

有人能帮我弄清楚如何正确地指出我的事件吗。非常感谢。

多亏了一些帮助,我下定决心了步骤1:在类外部(命名空间内)声明委托第2步:声明要为控件调用的事件。第3步:使用控件的事件处理程序来重用您创建的的委托

已完成代码

 public delegate void OnConnectingEventHandler(object sender, EventArgs Arguments);
 public delegate void OnDisconnectingEventHandler(Object sender,IMsTscAxEvents_OnDisconnectedEvent Arguments);
public class RemoteDesktop : WindowsFormsHost
{
    public event OnConnectingEventHandler IsConnecting;
    public event OnDisconnectingEventHandler IsDisconnecting;
    private AxMsRdpClient7NotSafeForScripting RDPUserControl = new AxMsRdpClient7NotSafeForScripting();
    public RemoteDesktop()
    {
        this.RDPUserControl.BeginInit();
        this.RDPUserControl.SuspendLayout();
        base.Child = RDPUserControl;
        this.RDPUserControl.ResumeLayout();
        this.RDPUserControl.EndInit();
        RDPUserControl.OnConnecting += RemoteDesktop_OnConnecting;
        RDPUserControl.OnDisconnected += RDPUserControl_OnDisconnected;
    }
    void RDPUserControl_OnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)
    {
        IsDisconnecting(sender, e);
    }
    void RemoteDesktop_OnConnecting(object sender, EventArgs Arguments)
    {
        IsConnecting(sender, Arguments);
    }
}
public class RemoteDesktopViewModel
{
    public RemoteDesktopViewModel()
    {
        RemoteDesktop newRDC = new RemoteDesktop();
        newRDC.IsConnecting += new RemoteDesktop.OnConnectingEventHandler(newRDC_OnConnecting);
    }
    void newRDC_OnConnecting(object sender, EventArgs Arguments)
    {
        //DoStuff
    }
}

将事件重定向到自定义控件内的处理程序

//at the constractor of the class
OnConnecting+=RDC_OnConnecting;

然后您可以在方法newRDC_OnConnecting中编写您的逻辑。确保OnConnectingEventHandler具有与newRDC_OnConnecting相同的方法签名。