C#调用COM(ocx)控件问题

2025-04-24 01:53:17
推荐回答(1个)
回答1:

//(1) 为事件处理声明一个委托
public delegate void MyEventDelegate(_AFunctionCompleteEven e);

public class Test
{
        private AxActiveComLib.ActiveComLibClass m_active;
        
        //(2)在为Test 定义一个事件:将COM.A的执行结果以事件方式传到外边
        public event MyEventDelegate MyEvent;
        
        public Test()
        {
            m_active = new ActiveComLibClass();
            m_active.CreateControl();
            //事件
            m_active.AFunctionComplete += 
                new AxActiveComLib._AFunctionCompleteEventHandler(m_active_AFunctionComplete);
        }

        //执行AFunction后响应事件---告知AFunction执行结果
        private void m_active_AFunctionComplete(object obj, _AFunctionCompleteEvent e)
        {
            // (4)引发事件:将调用结果传出去(见下面一段代码)
            if(MyEvent!=null)
            {
                MyEvent(e);
            }
        }
       
        //public int BtempFunction(string xxx)
        public void BtempFunction(string xxx)
        {
            //int ret = m_active.AFunction(xxx);
            //(3)调用COM函数
            m_active.AFunction(xxx);
            
            //不需要等待m_active.AFunction(xxx)的执行结果
            //因为COM控件执行完后会调用上面的
            // m_active_AFunctionComplete事件
        }
  }

在Form1后台代码Form1.cs中

……
using AxActiveComLib;
using ActiveComLib;

namespace TestApi 
{
    public partial Form1 :  Form
    {
          // 使用Test类
          Test test = new Test( );

           public Form1()
           {
                InitializeComponent();
                test.MyEvent += test_MyEvent
           }
           
           private void test_MyEvent(_AFunctionCompleteEven e)
           {
                  //在此处理调用结果
           }
           
           private void button1_Click(object send, EventArgs e)
           {
               //调用
               test.BtempFunction(……);
           }
  }