通过AutomationElement设置DateTimePicker元素

本文关键字:元素 DateTimePicker 设置 AutomationElement 通过 | 更新日期: 2023-09-27 18:24:55

我希望能够通过AutomationElementDateTimePicker元素设置为某个时间。它将时间存储为"hh:mm:ss tt"(即10:45:56 PM)。

我得到这样的元素:

ValuePattern p = AECollection[index].GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

我相信我有两个选择:

p.SetValue("9:41:22 AM");

p.Current.Value = "9:41:22 AM";

然而,第一个选项根本不起作用(我在某个地方读到这可能在.NET 2.0中被破坏了?,不过我使用的是.NET 3.0)。第二个选项告诉我元素是只读的,我如何更改状态使其不是只读的?或者更简单地说,我如何更改时间:(?

通过AutomationElement设置DateTimePicker元素

您可以获得本机窗口句柄并发送DTM_SETSYSTEMTIME消息来设置DateTimePicker控件的选定日期。

要做到这一点,我想你已经找到了元素,然后你可以使用以下代码:

var date =  new DateTime(1998, 1, 1);
DateTimePickerHelper.SetDate((IntPtr)element.Current.NativeWindowHandle, date);

DateTimePickerHelper

这是DateTimePickerHelper的源代码。该类有一个公共静态SetDate方法,允许您为日期-时间选择器控件设置日期:

using System;
using System.Runtime.InteropServices;
public class DateTimePickerHelper {
    const int GDT_VALID = 0;
    const int DTM_SETSYSTEMTIME = (0x1000 + 2);
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    struct SYSTEMTIME {
        public short wYear;
        public short wMonth;
        public short wDayOfWeek;
        public short wDay;
        public short wHour;
        public short wMinute;
        public short wSecond;
        public short wMilliseconds;
    }
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, int msg, 
        int wParam, SYSTEMTIME lParam);
    public static void SetDate(IntPtr handle, DateTime date) {
        var value = new SYSTEMTIME() {
            wYear = (short)date.Year,
            wMonth = (short)date.Month,
            wDayOfWeek = (short)date.DayOfWeek,
            wDay = (short)date.Day,
            wHour = (short)date.Hour,
            wMinute = (short)date.Minute,
            wSecond = (short)date.Second,
            wMilliseconds = 0
        };
        SendMessage(handle, DTM_SETSYSTEMTIME, 0, value);
    }
}

此解决方案适用于基于Wpf的应用

object patternObj = AECollection[index].GetCurrentPattern(UIA.UIA_PatternIds.UIA_ValuePatternId);
if (patternObj != null) {
 (UIA.IUIAutomationValuePattern)patternObj.SetValue(itemVal);
}