Перейти к содержимому

Фотография

Определение компонента.


  • Авторизуйтесь для ответа в теме
Сообщений в теме: 23

#1 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 26 сентября 2006 - 04:01

Здравствуйте!
Возникла небольшая пробелам с определением компонента.
Ситуация:
При нажатие на кнопку у меня возможны два вариант развития события 1) запускается необходимый процесс и всё чики - пики; 2) выдаётся сообщение, после чего необходимо произвести необходимый выбор, для продолжения операции.

Так вот, мой вопрос в том, как определить (по каким свойствам, методам) появляется ли это сообщение или нет?

ПыСь: Пишу на DelphiScript.
  • 0

#2 Dmitry N

Dmitry N

    Профессионал

  • Members
  • PipPipPipPipPipPip
  • 1 742 сообщений
  • ФИО:Николаев Дмитрий
  • Город:Где-то в России

Отправлено 26 сентября 2006 - 07:39

Здравствуйте.

Запишите скрипт, который будет выполнять нужный выбор в этом окошке. Получится что-то типа:
// DelphiScript
...
  w := p.VCLObject('Dialog');
  w.VCLObject('OKButton').ClickButton;
...
Измените скрипт, чтобы вместо VCLObject использовался WaitVCLObject и проверяйте значение свойства Exists полученного объекта.
// DelphiScript
...
  w := p.WaitVCLObject('Dialog', 10000);
  if w.Exists then
  begin
    w.VCLObject('OKButton').ClickButton;
  end;
...

  • 0
С уважением,
Дмитрий

#3 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 27 сентября 2006 - 08:59

Здравствуйте, Дима.
Попробывал предложенный вами вариант, всё равно возникает ошибочка:

Cannot obtain the window with the window class 'SunAwtDialog', window caption 'Ошибка' and index 1.

Possible reasons:
- The window with the specified attributes does not exist.
- The current object tree model differs from the tree model that was active during the recording.

Possible solutions:
To avoid this error message, you can check whether the window exists before you address it. To do this, get a reference to the object using the WaitWindow method and check the Exists property of the returned object.

В коде писал:
if Sys.Process('javaw', 2).Window('SunAwtDialog', 'Ошибка', 1).Exists = true then ...
  • 0

#4 Brain

Brain

    Новый участник

  • Members
  • Pip
  • 4 сообщений

Отправлено 27 сентября 2006 - 13:30

if Sys.Process('javaw', 2).Window('SunAwtDialog', 'Ошибка', 1).Exists = true then  ...

w := Sys.Process('javaw', 2).WaitWindow('SunAwtDialog', 'Ошибка', -1, 5000);
if w.Exists then...
  • 0

#5 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 28 сентября 2006 - 08:23

if Sys.Process('javaw', 2).Window('SunAwtDialog', 'Ошибка', 1).Exists = true then   ...

w := Sys.Process('javaw', 2).WaitWindow('SunAwtDialog', 'Ошибка', -1, 5000);
if w.Exists then...

Просмотр сообщения

Спасибо! Работает :help: :diablo:
  • 0

#6 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 29 сентября 2006 - 05:43

Здравствуйте!

Возникла ещё одна проблема:
Есть необходимость найти компонент по его Лэйблу (кэпшену, тому что на нём написано). Как это можно осуществить?
Пробывал найти по ID, но это вариант мне не подходит, так как компонентов много и интервал ID'шников у них тоже очень велик.
  • 0

#7 Scorp-13

Scorp-13

    Co-Moderator: Спорт, Кино и музыка

  • Members
  • PipPipPipPip
  • 285 сообщений
  • ФИО:Евгений
  • Город:Украина, Запорожье

Отправлено 29 сентября 2006 - 07:37

w := Sys.Process('javaw', 2).WaitWindow('SunAwtDialog', 'Ошибка', -1, 5000);



в этом примере "Ошибка" и есть искомый caption
  • 0
Ab altero expectes, alteri quod feceris

#8 Gala

Gala

    Новый участник

  • Members
  • Pip
  • 34 сообщений
  • ФИО:-

Отправлено 29 сентября 2006 - 07:42

Приветствую!
Здесь все зависит от того, в каком свойстве находится написанный на компоненте текст. Если этот текст виден в Object Browser'е в свойстве WndCaption, то можно сделать так:
w := Sys.Process('javaw', 2).WaitWindow('*', 'Ошибка', -1, 5000);
Т.е., второй параметр метода WaitWindow - это WndCaption окна (текст на контроле), а класс окна здесь заменен на '*' - любое количество любых символов. Почитать об этом можно в топике Window.WaitWindow или Process.WaitWindow.
Если текст, написаный на контроле, находится в другом свойстве, видимом в Object Browser'е, то надо делать перебор контролов "вручную".
  • 0

#9 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 29 сентября 2006 - 08:21

// Scorp-13, Gala

Спасибо за то что откликнулись!
Но это уже другая ситуация! к примеру у меня есть кнопки называются они "1", "2", "3" и т.д. мне надно нажать на ту кнопку значение которой к примеру выдаст рандомайз. Как это сделать?
  • 0

#10 Scorp-13

Scorp-13

    Co-Moderator: Спорт, Кино и музыка

  • Members
  • PipPipPipPip
  • 285 сообщений
  • ФИО:Евгений
  • Город:Украина, Запорожье

Отправлено 29 сентября 2006 - 09:07

Посмотрите в Object Browser'е в каком свойстве хранится это название (кнопки), и через него добирайтесь до кнопки, устанавливая значение свойства равным тому, что выдает рэндом.
  • 0
Ab altero expectes, alteri quod feceris

#11 Gala

Gala

    Новый участник

  • Members
  • Pip
  • 34 сообщений
  • ФИО:-

Отправлено 29 сентября 2006 - 09:15

Приветствую!
Если создать дефолтное приложение Delphi, положить на его форму 4 кнопки и дать им имена (Caption) "1", "2", "3" и "4", то кликнуть по рандомной кнопке можно таким кодом:
procedure ClickRandomButton;
var
  w;
begin
  w := Sys.Process('Project1').Window('TForm1', 'Form1');
  w.Window('TButton', IntToStr(Random(4) + 1)).ClickButton;
end;

  • 0

#12 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 29 сентября 2006 - 11:05

// Scorp-13
Можно поподробнее! если конечно не затруднит.
  • 0

#13 Brain

Brain

    Новый участник

  • Members
  • Pip
  • 4 сообщений

Отправлено 29 сентября 2006 - 11:27

Можно поподробнее! если конечно не затруднит.


w := Sys.Process('javaw', 2).Window('MyClass', 'MyName').WaitWindow('*', 'MyCaption', -1, 5000);

Будет ждать произвольный контрол с кэпшеном 'MyCaption' 5 секунд. Это может быть и кнопка, и едит -- что угодно. Строку 'MyCaption' (как собственно и 'MyClass', 'MyName') можно сформировать из кода. Например, так:

var
lol;
begin
lol := 'blah-blah' + MyFunc(123, 'blah-blah-blah');
w := Sys.Process('javaw', 2).Window(MyFunc1('MyClass'), MyFunc2('MyName')).WaitWindow('*', lol, -1, 5000);
end;

Единственное -- надо будет потом как-то понять, какой именно контрол получен. :)
  • 0

#14 Dmitry N

Dmitry N

    Профессионал

  • Members
  • PipPipPipPipPipPip
  • 1 742 сообщений
  • ФИО:Николаев Дмитрий
  • Город:Где-то в России

Отправлено 29 сентября 2006 - 13:31

Здравствуйте.

Если текст контрола храниться в каком-то свойстве, не используемым для доступа к объекту (т.е. не в WndCaption), то можно использовать метод Find для того, чтобы найти объект по произвольному значению этого свойства. Смотрите раздел справки 'Find Object'.
  • 0
С уважением,
Дмитрий

#15 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 30 сентября 2006 - 12:22

Такая проблема ....
Пытаюсь сгенерировать регистрацию на сайте ... при попытке присвоить полю значению какойто переменной т.е блаблабла.value(Gener) , которая обьявленна глобально ... а он плюется и ругается ..

Sys.Process('iexplore').Window('IEFrame', 'Начало - blabla - Microsoft Internet Explorer', 1).Window('Shell DocObject View', '', 1).Window('Internet Explorer_Server', '', 1).Page('http://192.168.1.17/efno/').document.all.Item(42).click;
Sys.Process('iexplore').Window('IEFrame', ',blabla - Microsoft Internet Explorer', 1).Window('Shell DocObject View', '', 1).Window('Internet Explorer_Server', '', 1).Page('http://192.168.1.17/efno/?p=registrate').document.all.Item('new_user_login').value(gener);

есть идеи подскажите.
  • 0

#16 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 02 октября 2006 - 05:07

Здравствуйте.

Если текст контрола храниться в каком-то свойстве, не используемым для доступа к объекту (т.е. не в WndCaption), то можно использовать метод Find для того, чтобы найти объект по произвольному значению этого свойства. Смотрите раздел справки 'Find Object'.

Просмотр сообщения

Здравствуйте, Дмитрий!

Значение по которму мне необходимо найти объект храниться в свойствах "Label" и "Text", как возможно осуществить поиск объект по этим свойствам?

ПыСь: В справке раздела 'Find Object' не обнаружил. :hi:
  • 0

#17 Scorp-13

Scorp-13

    Co-Moderator: Спорт, Кино и музыка

  • Members
  • PipPipPipPip
  • 285 сообщений
  • ФИО:Евгений
  • Город:Украина, Запорожье

Отправлено 02 октября 2006 - 07:34

Вот описание метода Find из help'а

Find Method
Returns an object by the values of the specified properties.

Declaration
testObj.Find(PropNames, PropValues, Depth) Parameters testObj    A tested object 
PropNames [in] Required Variant 
PropValues [in] Required Variant 
Depth [in] Optional Integer Default value: 1
Result    A tested object 

Description
An object can have one or more child objects. For instance, processes are children of the Sys object; windows are children of processes, etc. This method searches for a child object with the specified values of the specified properties.

Parameters
The method has the following parameters:

PropNames

An array of strings containing the names of properties or a single property name. The method returns an object by the values of these properties (property).

PropValues

The array containing the values of the specified properties or a single property value.

Depth

Specifies the level of child objects where Find will search for the desired object. By default, Depth is 1 and means that the method will search in the child objects of the testObj object. If Depth is 2, Find will search in child and grandchild objects, if Depth is 3, Find will search in child, grandchild and great-grandchild objects, and so on. To search in the whole hierarchy of child objects, use an integer value (for example, 20000) that is greater than the number of child levels in the hierarchy.
Return Value
The object that has the specified values of the specified properties.

Remarks
The implementation of arrays in JScript, C++Script and C#Script (the binary implementation used by the scripting engine) differs from the arrays used in VBScript or DelphiScript (see Supported Scripting Languages - Peculiarities of Usage). In order to use the Find method, you need to convert the JScript array to the format adopted in VBScript or DelphiScript. Without the conversion you can still use Find, but the search for an object will only use one property. For example, the PropNames parameter is a string specifying the name of the desired property and the PropValues parameter contains the value of this property.

To create arrays of properties and values in VBScript, use the CreateVariantArray built-in routine. VBScript arrays declared in the standard way are not supported.

Example
The following code searches for a visible window with the caption “Font style” among all child objects of the Notepad process (the window is part of the Font dialog that is displayed when selecting Format | Font from Notepad’s main menu).

[VBScript]

Sub MainTest
  Dim PropArray, ValuesArray, p, res
  
  ' Creates arrays of properties and values
  PropArray = CreateVariantArray(0, 1)
  ValuesArray = CreateVariantArray(0, 1)
  
  ' Specifies property names
  PropArray(0) = "WndCaption"
  PropArray(1) = "Visible"
  
  ' Specifies the property values
  ValuesArray(0) = "Font style:"
  ValuesArray(1) = True
  
  ' Searches for the window
  Set p = Sys.Process("Notepad")
  Set res = p.Find(PropArray, ValuesArray, 1000)
  
  ' Processes the search results
  If res.Exists Then
    Log.Message "Found: " + res.FullName
  Else
    Log.Message "Not found"
  End If
End Sub

[JScript]

function ConvertArray(AArray)
{
  // Uses the Dictionary object to convert a JScript array
  var objDict = new ActiveXObject("Scripting.Dictionary");
  objDict.RemoveAll();
  for (var j in AArray)
    objDict.Add(j, AArray[j]);
  return objDict.Items();
}
  
function MainTest()
{
  var PropArray, ValuesArray, ConvertedPropArray, ConvertedValuesArray, p, res;
  
  // Creates arrays of properties and values
  PropArray = new Array(2);
  ValuesArray = new Array(2);
  
  // Specifies property names
  PropArray[0] = "WndCaption";
  PropArray[1] = "Visible";
  
  // Specifies the property values
  ValuesArray[0] = "Cancel";
  ValuesArray[1] = true;
  
  // Coverts arrays
  ConvertedPropArray = ConvertArray(PropArray);
  ConvertedValuesArray = ConvertArray(ValuesArray);
  
  // Searches for the window
  p = Sys.Process("Notepad");
  res = p.Find(ConvertedPropArray, ConvertedValuesArray, 1000);
  
  if (res.Exists)
    Log.Message("Found: " + res.FullName);
  else
    Log.Message("Not found");
}
[DelphiScript]

procedure MainTest;
var
  PropArray, ValuesArray, p, res;
begin
  // Creates arrays of properties and values
  PropArray := CreateVariantArray(0, 1);
  ValuesArray := CreateVariantArray(0, 1);
  
  // Specifies property names
  PropArray[0] := 'WndCaption';
  PropArray[1] := 'Visible';
  
  // Specifies the property values
  ValuesArray[0] := 'Font style:';
  ValuesArray[1] := True;
  
  // Searches for the window
  p := Sys.Process('Notepad');
  res := p.Find(PropArray, ValuesArray, 1000);
  
  // Processes the search results
  if res.Exists then
    Log.Message('Found: ' + res.FullName)
  else
    Log.Message('Not found');
end;
[C++Script, C#Script]

function ConvertArray(AArray)
{
  // Uses the Dictionary object to convert a JScript array
  var objDict = new ActiveXObject("Scripting.Dictionary");
  objDict["RemoveAll"]();
  for (var j in AArray)
    objDict["Add"](j, AArray[j]);
  return objDict["Items"]();
}
  
function MainTest()
{
  var PropArray, ValuesArray, ConvertedPropArray, ConvertedValuesArray, p, res;
  
  // Creates arrays of properties and values
  PropArray = new Array(2);
  ValuesArray = new Array(2);
  
  // Specifies property names
  PropArray[0] = "WndCaption";
  PropArray[1] = "Visible";
  
  // Specifies the property values
  ValuesArray[0] = "Cancel";
  ValuesArray[1] = true;
  
  // Coverts arrays
  ConvertedPropArray = ConvertArray(PropArray);
  ConvertedValuesArray = ConvertArray(ValuesArray);
  
  // Searches for the window
  p = Sys.Process("Notepad");
  res = p["Find"](ConvertedPropArray, ConvertedValuesArray, 1000);
  
  if (res["Exists"])
    Log["Message"]("Found: " + res["FullName"]);
  else
    Log["Message"]("Not found");
}


  • 0
Ab altero expectes, alteri quod feceris

#18 Dmitry N

Dmitry N

    Профессионал

  • Members
  • PipPipPipPipPipPip
  • 1 742 сообщений
  • ФИО:Николаев Дмитрий
  • Город:Где-то в России

Отправлено 02 октября 2006 - 12:22

Здравствуйте.

Sys.Process('iexplore').Window('IEFrame', ',blabla - Microsoft Internet Explorer', 1).Window('Shell DocObject View', '', 1).Window('Internet Explorer_Server', '', 1).Page('http://192.168.1.17/efno/?p=registrate').document.all.Item('new_user_login').value(gener);

value - это свойство, с ним надо работать соответственно.
Sys.Process('iexplore').Window('IEFrame', ',blabla - Microsoft Internet Explorer', 1).Window('Shell DocObject View', '', 1).Window('Internet Explorer_Server', '', 1).Page('http://192.168.1.17/efno/?p=registrate').document.all.Item('new_user_login').value = gener;
PS. Find - это метод, не объект.
  • 0
С уважением,
Дмитрий

#19 Sudo -NAT

Sudo -NAT

    Новый участник

  • Members
  • Pip
  • 21 сообщений
  • ФИО:Афонин Игорь Валодьевич

Отправлено 06 октября 2006 - 09:12

[DelphiScript]

procedure MainTest;
var
  PropArray, ValuesArray, p, res;
begin
  // Creates arrays of properties and values
  PropArray := CreateVariantArray(0, 1);
  ValuesArray := CreateVariantArray(0, 1);
  
  // Specifies property names
  PropArray[0] := 'WndCaption';
  PropArray[1] := 'Visible';
  
  // Specifies the property values
  ValuesArray[0] := 'Font style:';
  ValuesArray[1] := True;
  
  // Searches for the window
  p := Sys.Process('Notepad');
  res := p.Find(PropArray, ValuesArray, 1000);
  
  // Processes the search results
  if res.Exists then
    Log.Message('Found: ' + res.FullName)
  else
    Log.Message('Not found');
end;

По подобию пишу:
procedure Main;
var
 p, res;
begin
p := Sys.Process('javaw').Window('SunAwtWindow', '', 1).JRootPane.null_layeredPane.null_contentPane.JCalendar.JPanel;
 res := p.Find(text, 10, 1000); //Text - свойство которое содержит значение по которому я буду искать; 10 - значение которое я ищу.

 if res.Exists then
   Log.Message('Found')
 else
   Log.Message('Not found');
end;
В результате у меня всегда в логах записывается "Not found", хотя этот объект "передо мной". Что делаю не так?
  • 0

#20 Scorp-13

Scorp-13

    Co-Moderator: Спорт, Кино и музыка

  • Members
  • PipPipPipPip
  • 285 сообщений
  • ФИО:Евгений
  • Город:Украина, Запорожье

Отправлено 06 октября 2006 - 11:24

1: У Вас во время исполнения скрипта не вылетает никаких ошибок? У Вас в коде название и значение искомого св-ва без кавычек. По идее при выполнении должны выскакивать ошибки.
2: Какой тип у св-ва Text. Насколько я могу понять - строковый. Если да:
3: 10 это полное значение этого св-ва или подстрока?
  • 0
Ab altero expectes, alteri quod feceris


Количество пользователей, читающих эту тему: 0

0 пользователей, 0 гостей, 0 анонимных