各位大佬,
假設有程式A,程式A中通過點擊一個按鈕B可以打開另一個表單C,表單C中有很多控制元件,假設需要呼叫表單C中的按鈕元素D。我現在遇到的問題如下:
1)在一個方法test1中通過AutomationElement找到并可以控制按鈕D,但是在呼叫程序中需要關閉并重新打開A程式,重新打開后如果需要再控制按鈕D,則需要重新撰寫查找A->D的程序,并且需要重新命名才能再次控制。然而實際查找代碼的格式是完全一樣的,請問有什么方法可以簡化這個程序嗎?代碼如下面的
2)如果需要在另一個方法test2中操作按鈕D,目前我的做法是再次重新A->D查找一遍,然后再控制D,請問有什么方法可以直接在test2中直接控制test1已經找到的按鈕元素D嗎?
private void test1()
{
Process p = Process.Start(@"D:\Program Flie\A.exe");
AutomationElement root = AutomationElement.RootElement;
AutomationElement formA = null;
int numWait = 0;
do
{
formA = root.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "A"));
Thread.Sleep(50);
numWait++;
} while (numWait < 500 && null == formA);
if (null == formA)
{
throw new NullReferenceException("Could not find A");
}
else
{
AutomationElement buttonB = formA.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "B"));
UIA.ButtonClick(buttonB);//自己變了一個UIA.cs檔案,可以模擬點擊按鈕操作
AutomationElement formC = formA.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "C"));
AutomationElement btnD = formC.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "D"));
UIA.ButtonClick(btnD);
p.Kill();
p.Start();
AutomationElement root1 = AutomationElement.RootElement;
AutomationElement formA1 = null;
int numWait1 = 0;
do
{
formA = root.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "A"));
Thread.Sleep(50);
numWait1++;
} while (numWait < 500 && null == formA1);
if (null == formA1)
{
throw new NullReferenceException("Could not find A");
}
else
{
AutomationElement buttonB1 = formA.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "B"));
UIA.ButtonClick(buttonB1);//自己變了一個UIA.cs檔案,可以模擬點擊按鈕操作
AutomationElement formC1 = formA.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "C"));
AutomationElement btnD1 = formC.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "D"));
UIA.ButtonClick(btnD1);
}
}
}
uj5u.com熱心網友回復:
腦洞清奇啊你把原始需求說下吧,通常情況會有更好的方法來處理你的需求的.
uj5u.com熱心網友回復:
原始需求其實就是要實作自動化操作程式A。但因為程式A沒有已知的API,只能通過UIAutomation類實作控制,然后程序中需要關閉程式A再重新打開,在同一個方法里面重新查找程式A的UI元素就會存在很多重復性的代碼,所以想問問有沒有簡化代碼的辦法。另一個問題就是,如果要在同一個類一個方法test2中直接操作另一個方法test1中已找到的程式A中的UI元素,除了在test2中再寫一遍重新查找UI元素的代碼之外,是否有其他簡便的辦法能夠實作UI元素在不同方法中的傳遞。
uj5u.com熱心網友回復:
你把重復性的代碼整合成一個方法就得了,如果有不同的地方,就設計成不同的引數,類似函式多載。uj5u.com熱心網友回復:
那可以這樣: 程式A不要關閉,關閉時候隱藏表單,取消關閉,下次呼叫直接顯示就好了.這個A程式的演算法很難嗎?最好還是逆向下或者查資料自己實作下.
uj5u.com熱心網友回復:
你對要操控的控制元件做個封裝,程式第一次啟動的時候,把找到元素放到封裝類里,然后把封裝類放到一個公共的集合中,后邊無論你回圈都少次都只訪問這個集合就行了。轉載請註明出處,本文鏈接:https://www.uj5u.com/net/9855.html
標籤:C#
