2016-12-17 17 views
0

我有一個要求,如果用戶從他/她的硬盤驅動器打開任何辦公文件它應該打開一個exe文件(贏得表格應用程序)作爲模式窗口來捕獲有關文檔的詳細信息。打開一個exe文件(Windows應用程序)作爲模式,同時打開從硬盤驅動器的辦公文件

爲此,我開發了一個控制檯應用程序,該應用程序在客戶端計算機下運行,以監視是否有任何辦公室文檔文件正在打開。請找到下面的代碼

static void Main(string[] args) 
{ 
    var UIAEventHandler = new AutomationEventHandler(OnUIAEvent); 
    Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, 
          AutomationElement.RootElement, 
          TreeScope.Children, UIAEventHandler); 
    Console.ReadLine(); 

    Automation.RemoveAllEventHandlers(); 
} 

public static void OnUIAEvent(object src, AutomationEventArgs args) 
{ 
    AutomationElement element; 

    try 
    { 
     element = src as AutomationElement; 
    } 
    catch 
    { 
     return; 
    } 
    string name = ""; 
    if (element == null) 
     name = "null"; 
    else 
    { 
     name = element.GetCurrentPropertyValue(
       AutomationElement.NameProperty) as string; 
    } 
    if (name.Length == 0) name = "<NoName>"; 
    string guid = Guid.NewGuid().ToString("N"); 
    string str = string.Format("{0} : {1}", name, args.EventId.Id); 
    if ((element.Current.ClassName.Equals("XLMAIN", StringComparison.InvariantCultureIgnoreCase) == true && name.Contains(".xlsx")) || (element.Current.ClassName.Equals("OpusApp", StringComparison.InvariantCultureIgnoreCase) == true && name.Contains(".docx"))) 
    { 

     Process.Start(@"E:\experiment\TestingWindowsService\UserInfomation\bin\Debug\UserInfomation.exe", element.Current.Name); 
     //Automation.AddAutomationEventHandler(
     //  WindowPattern.WindowClosedEvent, 
     //  element, TreeScope.Element, (s, e) => UIAEventHandler1(s, e, guid, name)); 
     Console.WriteLine(guid + " : " + name); 
     // Environment.Exit(1234); 
    } 
} 

,如果你在我使用Process.Start像預期的那樣打開exe.It的工作的OnUIAEvent事件處理程序見。但我希望這個exe應該以打開的文檔模式打開。下面的代碼是exe的表單加載。

private void Form1_Load(object sender, EventArgs e) 
{ 
    this.TopMost = true; 
    this.CenterToScreen(); 
} 

是否可以打開windows應用程序打開爲打開的文檔模態?

+1

UI自動化還允許您禁用窗口,用戶無法重新啓用它。這使得你的應用程序模式。不要忘記重新啓用它。 –

回答

0

除非已將外部應用程序考慮在內,否則將會很困難。 如果您有權訪問代碼(您似乎擁有該代碼),則可以將該表單包含在控制檯應用程序中(請參見how to run a winform from console application?)。

最簡單的選擇是啓動一個windows窗體項目,然後將 的輸出類型更改爲控制檯應用程序。另外,只需添加一個 參考對System.Windows.Forms.dll,並開始編碼:

using System.Windows.Forms; 

[STAThread] static void Main() { 
    Application.EnableVisualStyles(); 
    Application.Run(new Form()); // or whatever 
} 

最重要的一點是[STAThread]在您的Main()方法,完全支持COM要求。

您可以覆蓋創建者,並添加匹配文檔的參數,或者任何您需要登錄/監控的參數。

相關問題