win_wrap/uia/pattern/
value.rs

1/*
2 * Copyright (c) 2024. The RigelA open source project team and
3 * its contributors reserve all rights.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and limitations under the License.
12 */
13
14use crate::uia::pattern::{PatternCreator, PatternError};
15use std::fmt::{Debug, Formatter};
16use windows::{
17    core::BSTR,
18    Win32::UI::Accessibility::{IUIAutomationValuePattern, UIA_ValuePatternId, UIA_PATTERN_ID},
19};
20
21/// ValuePattern
22/// 提供对控件的访问,该控件包含一个值,该值不跨越范围,并且可以表示为字符串。此字符串可能是可编辑的,也可能是不可编辑的,具体取决于控件及其设置。
23pub struct UiAutomationValuePattern(IUIAutomationValuePattern);
24
25impl TryFrom<IUIAutomationValuePattern> for UiAutomationValuePattern {
26    type Error = PatternError;
27
28    fn try_from(value: IUIAutomationValuePattern) -> Result<Self, Self::Error> {
29        Ok(Self(value))
30    }
31}
32
33impl PatternCreator<IUIAutomationValuePattern> for UiAutomationValuePattern {
34    const PATTERN: UIA_PATTERN_ID = UIA_ValuePatternId;
35}
36
37/// <https://learn.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationvaluepattern>
38impl UiAutomationValuePattern {
39    /**
40    查询元素的值。
41    */
42    pub fn get_value(&self) -> Result<String, String> {
43        let value = unsafe { self.0.CurrentValue() };
44        match value {
45            Ok(v) => Ok(v.to_string()),
46            Err(ee) => Err(format!("Can't get the value. ({})", ee)),
47        }
48    }
49
50    /**
51    设置元素的值。
52    */
53    pub fn set_value(&self, value: &str) -> Result<(), String> {
54        let value = BSTR::from(value);
55        let value = unsafe { self.0.SetValue(&value) };
56        if let Err(e) = value {
57            return Err(format!("Can't set the value. ({})", e));
58        }
59        Ok(())
60    }
61
62    /**
63    判断元素的值是否为只读。
64    */
65    pub fn is_readonly(&self) -> Result<bool, String> {
66        let value = unsafe { self.0.CurrentIsReadOnly() };
67        match value {
68            Ok(v) => Ok(v.0 != 0),
69            Err(ee) => Err(format!("Can't get the value. ({})", ee)),
70        }
71    }
72}
73
74impl Debug for UiAutomationValuePattern {
75    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
76        write!(f, "UiAutomationValuePattern()")
77    }
78}
79
80unsafe impl Send for UiAutomationValuePattern {}
81
82unsafe impl Sync for UiAutomationValuePattern {}