2016-06-12 61 views
0

我將如何閱讀用戶輸入,處理com事件以及從控制檯應用程序中的用戶輸入調用com對象的某些功能?c#console - 呼叫和收聽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的[公寓線程模型(https://msdn.microsoft.com/en-us/library/ms809971的.aspx)。 – theB

回答

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 
    } 
} 

希望這可以幫助別人