# 【Tutorial】透過 Venom 操作應用程式
## 簡介
Venom 是一個專為操作應用程式設計的工具,透過其強大的 `host-object-model` API,開發者可以精準地與目標應用程式進行交互。本教學將帶領您了解如何利用 Venom 的功能來實現應用程式的自動化操作。
Venom 提供兩種主要的操作方式:
- **模擬滑鼠與鍵盤操作**:適用於基於物理互動的 UI 操作。
- **利用 UI Pattern 進行操作**:基於標準化行為的操作方式,可用於檢查、設定或觸發特定功能。
以下將透過具體範例進一步說明。
## 模擬滑鼠與鍵盤操作
這是一種直接模擬用戶行為的操作方式,例如滑鼠移動、點擊以及鍵盤輸入。
### 範例:模擬滑鼠移動與點擊
#### 模擬滑鼠移動
```typescript
const filesExplorerDescriptor = require('./descriptor/filesExplorer.json') as DescriptorDTO;
const filesExplorer = await host.getElementsByDescriptor(filesExplorerDescriptor, UITreeScope.Element);
const elements = filesExplorer.getHomElements();
// 移動滑鼠至第一個元素的中心
await elements[0].mouseMoveIn();
```
#### 模擬滑鼠點擊
```typescript
// 點擊第一個元素
await elements[0].mouseClick({ key: 'left' });
```
## 利用 UI Pattern 進行操作
UI Pattern 是基於標準化行為的操作方式,例如檢查某元素是否支持特定功能,或執行其標準化操作。
### 確認 UI Pattern 支援
開發者可以檢查某個 UI 元素是否支援特定的 Pattern。
```typescript
const elementDescriptor = require('./descriptor/element.json') as DescriptorDTO;
const elements = await host.getElementsByDescriptor(elementDescriptor, UITreeScope.Subtree);
const element = elements.getHomElements()[0];
// 更新屬性以確認元素是否支援 Invoke Pattern
await element.updateCurrentIsInvokable();
if (element.isInvokable) {
await element.invoke();
console.log('Element invoked successfully');
}
```
### 設置元素的值
```typescript
await element.updateCurrentHasValue();
if (element.hasValue) {
await element.setValue('New Value');
console.log('Value set successfully');
}
```
### 確認支持的屬性
```typescript
// 檢查支持的 Pattern
await element.updateAllCurrentProperty();
console.log('Is Invokable:', element.isInvokable);
console.log('Has Value:', element.hasValue);
console.log('Is Scrollable:', element.isScrollable);
```
:::danger
**在使用 Pattern 操作前,務必確認目標元素是否支援該 Pattern。**
:::
## 批量操作範例
以下展示如何利用 Venom 完成文件管理器中的批量操作。
### 批量點擊文件
```typescript
const filesExplorerDescriptor = require('./descriptor/filesExplorer.json') as DescriptorDTO;
const filesExplorer = await host.getElementsByDescriptor(filesExplorerDescriptor, UITreeScope.Children);
// 批量點擊文件
for (const file of filesExplorer.getHomElements()) {
await file.mouseClick({ key: 'left' });
console.log(`Clicked on file: ${file.id}`);
}
```