1# Component ID
2
3**id** identifies a component uniquely within an application. This module provides APIs for obtaining the attributes of or sending events to the component with the specified ID.
4
5>  **NOTE**
6>
7> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8
9## Attributes
10
11### id
12
13id(value: string): T
14
15Sets a unique identifier for this component, with uniqueness guaranteed by the user.
16
17**Widget capability**: This API can be used in ArkTS widgets since API version 9.
18
19**Atomic service API**: This API can be used in atomic services since API version 11.
20
21**System capability**: SystemCapability.ArkUI.ArkUI.Full
22
23**Parameters**
24
25| Name  | Type     | Mandatory| Description                      |
26| ------ | -------- | -----|---------------------- |
27| value  | string   |  Yes | Unique identifier for the component, with uniqueness guaranteed by the user.<br>Default value: **''**<br>|
28
29### key<sup>12+</sup>
30
31key(value: string): T
32
33Sets a unique identifier for this component, with uniqueness guaranteed by the user.
34
35This API is used only for test purposes. When this attribute is used in conjunction with **id**, the value assigned later will override the one assigned earlier. You are advised to set only **id**.
36
37**System capability**: SystemCapability.ArkUI.ArkUI.Full
38
39**Parameters**
40
41| Name  | Type     | Mandatory| Description                      |
42| ------ | -------- | -----|---------------------- |
43| value   | string   | Yes| Unique identifier for the component, with uniqueness guaranteed by the user.<br>Default value: **''**<br>|
44
45
46## APIs
47
48
49### getInspectorByKey<sup>9+</sup>
50
51getInspectorByKey(id: string): string
52
53Obtains all attributes of the component with the specified ID, excluding the information about child components.
54
55This API is used only for test purposes. It is time consuming and not recommended.
56
57**Atomic service API**: This API can be used in atomic services since API version 11.
58
59**Parameters**
60
61| Name  | Type     | Mandatory    | Description       |
62| ---- | -------- | ---- | -------------|
63| id   | string   | Yes   | ID of the component whose attributes are to be obtained.|
64
65**Return value**
66
67| Type       | Description            |
68| -------| -------------- |
69| string | JSON string of the component attribute list.<br>**NOTE**<br> The string includes the tag, ID, location (relative to the coordinates in the upper left corner of the window), and other information of the component used for testing.|
70
71### getInspectorTree<sup>9+</sup>
72
73getInspectorTree(): Object
74
75Obtains the component tree and component attributes.
76
77This API is used only for test purposes. It is time consuming and not recommended.
78
79**Atomic service API**: This API can be used in atomic services since API version 11.
80
81**Return value**
82
83| Type    | Description                           |
84| ------ | --------------------------- |
85| Object | JSON object of the component tree and component attribute list.|
86
87### sendEventByKey<sup>9+</sup>
88
89sendEventByKey(id: string, action: number, params: string): boolean
90
91Sends an event to the component with the specified ID.
92
93This API is used only for test purposes. It is time consuming and not recommended.
94
95**Atomic service API**: This API can be used in atomic services since API version 11.
96
97**Parameters**
98
99| Name      | Type     | Mandatory      | Description                        |
100| ------ | -------| ---- | -------------------------- |
101| id     | string | Yes   | ID of the component to which the event is to be sent.                     |
102| action | number | Yes   | Type of the event to be sent. The options are as follows:<br>- **10**: click event.<br>- **11**: long-click event.|
103| params | string | Yes   | Event parameters. If there is no parameter, pass an empty string **""**.           |
104
105**Return value**
106
107| Type         | Description                        |
108| -------- | --------------------------|
109| boolean  | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
110
111### sendTouchEvent<sup>9+</sup>
112
113sendTouchEvent(event: TouchObject): boolean
114
115Sends a touch event.
116
117This API is used only for test purposes. It is time consuming and not recommended.
118
119**Atomic service API**: This API can be used in atomic services since API version 11.
120
121**Parameters**
122
123| Name     | Type           | Mandatory | Description                                                        |
124| ----- | ----------- | ---- | ------------------------------------------------------------ |
125| event | [TouchObject](ts-universal-events-touch.md#touchobject) | Yes   | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
126
127**Return value**
128
129| Type     | Description                        |
130| ------- | ---------------------------|
131| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
132
133### sendKeyEvent<sup>9+</sup>
134
135sendKeyEvent(event: KeyEvent): boolean
136
137Sends a key event.
138
139This API is used only for test purposes. It is time consuming and not recommended.
140
141**Atomic service API**: This API can be used in atomic services since API version 11.
142
143**Parameters**
144
145| Name   | Type    | Mandatory     | Description                                                        |
146| ----- | -------- | ----  | ------------------------------------------------------------ |
147| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Yes    | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
148
149**Return value**
150
151| Type     | Description                          |
152| ------- | ------------------------------|
153| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
154
155### sendMouseEvent<sup>9+</sup>
156
157sendMouseEvent(event: MouseEvent): boolean
158
159Sends a mouse event.
160
161This API is used only for test purposes. It is time consuming and not recommended.
162
163**Atomic service API**: This API can be used in atomic services since API version 11.
164
165**Parameters**
166
167| Name    | Type      | Mandatory      | Description                                    |
168| ----- | ---------- | ----  | --------------------------------------- |
169| event | [MouseEvent](ts-universal-mouse-key.md#mouseevent) | Yes   | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
170
171**Return value**
172
173| Type     | Description                                |
174| ------- | ---------------------------------- |
175| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
176
177## Example
178
179```ts
180// xxx.ets
181import { IntentionCode } from '@kit.InputKit'
182
183class Utils {
184  static rect_left: number
185  static rect_top: number
186  static rect_right: number
187  static rect_bottom: number
188  static rect_value: Record<string, number>
189
190  // Obtain the coordinates of the rectangular area occupied by the component.
191  static getComponentRect(key:string):Record<string, number> {
192    let strJson = getInspectorByKey(key)
193    let obj:Record<string, string> = JSON.parse(strJson)
194    console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj))
195    let rectInfo:string[] = JSON.parse('[' + obj.$rect + ']')
196    console.info("[getInspectorByKey] rectInfo is: " + rectInfo)
197    Utils.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0]
198    Utils.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1]
199    Utils.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0]
200    Utils.rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1]
201    return Utils.rect_value = {
202      "left": Utils.rect_left, "top": Utils.rect_top, "right": Utils.rect_right, "bottom": Utils.rect_bottom
203    }
204  }
205}
206
207@Entry
208@Component
209struct IdExample {
210  @State text: string = ''
211
212  build() {
213    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
214
215      Button() {
216        Text('onKeyTab').fontSize(25).fontWeight(FontWeight.Bold)
217      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
218      .onKeyEvent(() => {
219        this.text = "onKeyTab"
220      })
221
222      Button() {
223        Text('click to start').fontSize(25).fontWeight(FontWeight.Bold)
224      }.margin({ top: 20 })
225      .onClick(() => {
226        console.info(getInspectorByKey("click"))
227        console.info(JSON.stringify(getInspectorTree()))
228        this.text = "Button 'click to start' is clicked"
229        setTimeout(() => {
230          sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick".
231        }, 2000)
232      }).id('click')
233
234      Button() {
235        Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
236      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
237      .gesture(
238      LongPressGesture().onActionEnd(() => {
239        console.info('long clicked')
240        this.text = "Button 'longClick' is longclicked"
241        setTimeout(() => {
242          let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch".
243          let touchPoint: TouchObject = {
244            id: 1,
245            type: TouchType.Down,
246            x: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the component.
247            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate relative to the upper left corner of the component.
248            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowX instead.
249            screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowY instead.
250            windowX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window.
251            windowY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window.
252            displayX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the device screen.
253            displayY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the device screen.
254          }
255          sendTouchEvent(touchPoint) // Send a touch event.
256          touchPoint.type = TouchType.Up
257          sendTouchEvent(touchPoint) // Send a touch event.
258        }, 2000)
259      })).id('longClick')
260
261      Button() {
262        Text('onTouch').fontSize(25).fontWeight(FontWeight.Bold)
263      }.type(ButtonType.Capsule).margin({ top: 20 })
264      .onClick(() => {
265        console.info('onTouch is clicked')
266        this.text = "Button 'onTouch' is clicked"
267        setTimeout(() => {
268          let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse".
269          let mouseEvent: MouseEvent = {
270            button: MouseButton.Left,
271            action: MouseAction.Press,
272            x: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the component.
273            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate relative to the upper left corner of the component.
274            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowX instead.
275            screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowY instead.
276            windowX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window.
277            windowY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window.
278            displayX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the device screen.
279            displayY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the device screen.
280            stopPropagation: () => {
281            },
282            timestamp: 1,
283            target: {
284              area: {
285                width: 1,
286                height: 1,
287                position: {
288                  x: 1,
289                  y: 1
290                },
291                globalPosition: {
292                  x: 1,
293                  y: 1
294                }
295              }
296            },
297            source: SourceType.Mouse,
298            pressure: 1,
299            tiltX: 1,
300            tiltY: 1,
301            sourceTool: SourceTool.Unknown
302          }
303          sendMouseEvent(mouseEvent) // Send a mouse event.
304        }, 2000)
305      }).id('onTouch')
306
307      Button() {
308        Text('onMouse').fontSize(25).fontWeight(FontWeight.Bold)
309      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
310      .onMouse(() => {
311        console.info('onMouse')
312        this.text = "Button 'onMouse' in onMouse"
313        setTimeout(() => {
314          let keyEvent: KeyEvent = {
315            type: KeyType.Down,
316            keyCode: 2049,
317            keyText: 'tab',
318            keySource: 4,
319            deviceId: 0,
320            metaKey: 0,
321            timestamp: 0,
322            stopPropagation: () => {
323            },
324            intentionCode: IntentionCode.INTENTION_DOWN
325          }
326          sendKeyEvent(keyEvent) // Send a key event.
327        }, 2000)
328      }).id('onMouse')
329
330      Text(this.text).fontSize(25).padding(15)
331    }
332    .width('100%').height('100%')
333  }
334}
335```
336