当前位置:  开发笔记 > 编程语言 > 正文

使用互操作提升vb6事件

如何解决《使用互操作提升vb6事件》经验,为你挑选了1个好方法。

我有一个遗留的VB6组件,我使用tlbimp.exe导入到VS中以生成我的互操作程序集.VB6组件定义了一个允许我在VB6中传递消息的事件.

Public Event Message(ByVal iMsg As Variant, oCancel As Variant)

我真的希望能够在我的C#程序中提高它,但它作为事件导入,而不是委托或其他有用的东西.所以,我只能听,但从不开火.有谁知道如何触发VB6中包含的事件?C#事件看起来像

[TypeLibType(16)]
[ComVisible(false)]
 public interface __MyObj_Event
 {
     event __MyObj_MessageEventHandler Message;
 }

遗憾的是我无法更改VB6代码.谢谢.



1> Mike Spross..:

实际上,希望还没有消失.这可以从对象的类之外的COM对象引发事件.此功能实际上由COM本身提供,但是以间接方式提供.

在COM中,事件适用于发布/订阅模型.具有事件的COM对象("事件源")发布事件,并且一个或多个其他COM对象通过将事件处理程序附加到源对象来订阅事件(处理程序称为"事件接收器").通常,源对象通过简单地遍历所有事件接收器并调用适当的处理程序方法来引发事件.

那么这对你有什么帮助?恰好COM允许您查询事件源以获取当前订阅源对象事件的所有事件接收器对象的列表.获得事件接收器对象列表后,可以通过调用每个接收器对象的事件处理程序来模拟引发事件.

注意: 我过度简化了细节并且对某些术语持开放态度,但这是事件在COM中如何工作的简短(并且在某种程度上是政治上不正确的)版本.

您可以利用这些知识从外部代码引发COM对象上的事件.实际上,可以在C#中完成所有这些操作,System.Runtime.Interop并在System.Runtime.Interop.ComTypes命名空间和命名空间中提供COM互操作支持.


编辑

我编写了一个实用程序类,允许您从.NET引发COM对象上的事件.它非常易于使用.以下是使用您问题中的事件界面的示例:

MyObj legacyComObject = new MyObj();

// The following code assumes other COM objects have already subscribed to the 
// MyObj class's Message event at this point.
//
// NOTE: VB6 objects have two hidden interfaces for classes that raise events:
//
// _MyObj (with one underscore): The default interface.
// __MyObj (with two underscores): The event interface.
//
// We want the second interface, because it gives us a delegate
// that we can use to raise the event.
// The ComEventUtils.GetEventSinks method is a convenience method
// that returns all the objects listening to events from the legacy COM object.

// set up the params for the event
string messageData = "Hello, world!";
bool cancel = false;

// raise the event by invoking the event delegate for each connected object...
foreach(__MyObj sink in ComEventUtils.GetEventSinks<__MyObj>(legacyComObject))
{
    // raise the event via the event delegate
    sink.Message(messageData, ref cancel);

    if(cancel == true)
    {
        // do cancel processing (just an example)
        break;
    }
}

下面是ComEventUtils类的代码(以及帮助类,SafeIntPtr因为我是偏执狂,想要一个很好的方法来处理IntPtrCOM相关代码所需的S):

免责声明:我没有彻底测试下面的代码.代码在一些地方执行手动内存管理,因此可能会在代码中引入内存泄漏.另外,我没有在代码中添加错误处理,因为这只是一个例子.小心使用.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using COM = System.Runtime.InteropServices.ComTypes;

namespace YourNamespaceHere
{

/// 
/// A utility class for dealing with COM events.
/// Needs error-handling and could potentially be refactored
/// into a regular class. Also, I haven't extensively tested this code;
/// there may be a memory leak somewhere due to the rather
/// low-level stuff going on in the class, but I think I covered everything.
/// 
public static class ComEventUtils
{
    /// 
    /// Get a list of all objects implementing an event sink interface T
    /// that are listening for events on a specified COM object.
    /// 
    /// The event sink interface.
    /// The COM object whose event sinks you want to retrieve.
    /// A List of objects that implement the given event sink interface and which
    /// are actively listening for events from the specified COM object.
    public static List GetEventSinks(object comObject)
    {
        List sinks = new List();
        List connectionPoints = GetConnectionPoints(comObject);

        // Loop through the source object's connection points, 
        // find the objects that are listening for events at each connection point,
        // and add the objects we are interested in to the list.
        foreach(COM.IConnectionPoint connectionPoint in connectionPoints)
        {
            List connections = GetConnectionData(connectionPoint);

            foreach (COM.CONNECTDATA connection in connections)
            {
                object candidate = connection.pUnk;

                // I tried to avoid relying on try/catch for this
                // part, but candidate.GetType().GetInterfaces() kept
                // returning an empty array.
                try
                {
                    sinks.Add((T)candidate);
                }
                catch { }
            }

            // Need to release the interface pointer in each CONNECTDATA instance
            // because GetConnectionData implicitly AddRef's it.
            foreach (COM.CONNECTDATA connection in connections)
            {
                Marshal.ReleaseComObject(connection.pUnk);
            }
        }

        return sinks;
    }

    /// 
    /// Get all the event connection points for a given COM object.
    /// 
    /// A COM object that raises events.
    /// A List of IConnectionPoint instances for the COM object.
    private static List GetConnectionPoints(object comObject)
    {
        COM.IConnectionPointContainer connectionPointContainer = (COM.IConnectionPointContainer)comObject;
        COM.IEnumConnectionPoints enumConnectionPoints;
        COM.IConnectionPoint[] oneConnectionPoint = new COM.IConnectionPoint[1];
        List connectionPoints = new List();

        connectionPointContainer.EnumConnectionPoints(out enumConnectionPoints);
        enumConnectionPoints.Reset();

        int fetchCount = 0;
        SafeIntPtr pFetchCount = new SafeIntPtr();

        do
        {
            if (0 != enumConnectionPoints.Next(1, oneConnectionPoint, pFetchCount.ToIntPtr()))
            {
                break;
            }

            fetchCount = pFetchCount.Value;

            if (fetchCount > 0)
                connectionPoints.Add(oneConnectionPoint[0]);

        } while (fetchCount > 0);

        pFetchCount.Dispose();

        return connectionPoints;
    }

    /// 
    /// Returns a list of CONNECTDATA instances representing the current
    /// event sink connections to the given IConnectionPoint.
    /// 
    /// The IConnectionPoint to return connection data for.
    /// A List of CONNECTDATA instances representing all the current event sink connections to the 
    /// given connection point.
    private static List GetConnectionData(COM.IConnectionPoint connectionPoint)
    {
        COM.IEnumConnections enumConnections;
        COM.CONNECTDATA[] oneConnectData = new COM.CONNECTDATA[1];
        List connectDataObjects = new List();

        connectionPoint.EnumConnections(out enumConnections);
        enumConnections.Reset();

        int fetchCount = 0;
        SafeIntPtr pFetchCount = new SafeIntPtr();

        do
        {
            if (0 != enumConnections.Next(1, oneConnectData, pFetchCount.ToIntPtr()))
            {
                break;
            }

            fetchCount = pFetchCount.Value;

            if (fetchCount > 0)
                connectDataObjects.Add(oneConnectData[0]);

        } while (fetchCount > 0);

        pFetchCount.Dispose();

        return connectDataObjects;
    }
} //end class ComEventUtils

/// 
/// A simple wrapper class around an IntPtr that
/// manages its own memory.
/// 
public class SafeIntPtr : IDisposable
{
    private bool _disposed = false;
    private IntPtr _pInt = IntPtr.Zero;

    /// 
    /// Allocates storage for an int and assigns it to this pointer.
    /// The pointed-to value defaults to 0.
    /// 
    public SafeIntPtr()
        : this(0)
    {
        //
    }

    /// 
    /// Allocates storage for an int, assigns it to this pointer,
    /// and initializes the pointed-to memory to known value.
    /// The value this that this SafeIntPtr points to initially.
    /// 
    public SafeIntPtr(int value)
    {
        _pInt = Marshal.AllocHGlobal(sizeof(int));
        this.Value = value;
    }

    /// 
    /// Gets or sets the value this pointer is pointing to.
    /// 
    public int Value
    {
        get 
        {
            if (_disposed)
                throw new InvalidOperationException("This pointer has been disposed.");
            return Marshal.ReadInt32(_pInt); 
        }

        set 
        {
            if (_disposed)
                throw new InvalidOperationException("This pointer has been disposed.");
            Marshal.WriteInt32(_pInt, Value); 
        }
    }

    /// 
    /// Returns an IntPtr representation of this SafeIntPtr.
    /// 
    /// 
    public IntPtr ToIntPtr()
    {
        return _pInt;
    }

    /// 
    /// Deallocates the memory for this pointer.
    /// 
    public void Dispose()
    {
        if (!_disposed)
        {
            Marshal.FreeHGlobal(_pInt);
            _disposed = true;
        }
    }

    ~SafeIntPtr()
    {
        if (!_disposed)
            Dispose();
    }

} //end class SafeIntPtr

} //end namespace YourNamespaceHere

推荐阅读
吻过彩虹的脸_378
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有