c#console - 调用并收听com事件

时间:2016-06-12 08:42:26

标签: c# .net com activex

如何从控制台应用程序中的用户输入读取用户输入,处理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 个答案:

答案 0 :(得分:1)

我得到了我想要使用以下代码的内容。我首先将activex控件导入到Windows窗体应用程序中,以创建我在控制台应用程序中使用的dll包装器。 https://msdn.microsoft.com/en-us/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
    }
}

希望这有助于某人