C#控制台 - 调用和监听COM事件

3

我该如何在控制台应用程序中读取用户输入、处理COM事件并从用户输入中调用COM对象的某些函数?

我正在尝试整合以下内容:

static void Main(string[] args)
{
    // Read user input
    string input;

    do
    {
        // Start thread for com here??

        input = Console.ReadLine();

        if (input == "Function1")
        {
            // Call Function1 on Com object
        }

        if (input == "Function2")
        {
            // Call Function2 on Com object
        }

    } while (input != null);

    // Exit app
}

--

// Call com on separate thread
Thread thread = new Thread(MessagePumpThread);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

--

void MessagePumpThread()
{
    var activex = new activeXObject();
    activex.CreateControl();

    // Subscribe to events...

    Application.Run();
}

我想在控制台中完成类似于Windows窗体应用程序中容易实现的功能。

非常感谢您的帮助,谢谢。


1
如果你还没有,你可能应该查看COM的公寓线程模型 - theB
1个回答

3

我通过以下代码实现了所需功能。我首先将ActiveX控件导入Windows窗体应用程序中,以创建dll封装器,然后在控制台应用程序中使用它。

https://msdn.microsoft.com/zh-cn/library/ms973200.aspx
class Program
{
    private static activeXControl _acx = new activeXControl();

    [STAThread]
    static void Main(string[] args)
    {
        // User input loop thread, use Ctrl + Z to exit loop
        Thread thread = new Thread((ThreadStart)
        delegate
        {
            string input;

            do
            {
                input = Console.ReadLine();

                if (string.IsNullOrEmpty(input))
                {
                    continue;
                }

                switch (input)
                {
                    case "Function1":
                        acx.Invoke(new Action(() => _acx.Function1()));
                        break;

                    case "Function2":
                        acx_.Invoke(new Action(() => acx_.Function2()));
                        break;

                    default:
                        Console.WriteLine("Method not found");
                        break;
                }
            } while (input != null);
        });
        thread.IsBackground = true;
        thread.Start();

        // Create control and subscribe to events
        _acx.CreateControl();

        _acx.Event1 += new System.EventHandler(acx_Event1);
        _acx.Event2 += new System.EventHandler(acx_Event2);

        // Start message loop
        Application.Run();
    }

    private static void acx_Event1(object sender, EventArgs e)
    {
        // Write event output to console
    }

    private static void acx_Event2(object sender, EventArgs e)
    {
        // Write event output to console
    }
}

希望这能对某些人有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接