通过AutomationElement设置DateTimePicker元素

4
我希望能够通过AutomationElement设置DateTimePicker元素的特定时间。它将时间存储为"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)。第二个选项告诉我该元素是只读的,如何更改状态以使其非只读?更简单地说,如何更改时间?
2个回答

1
你可以获取本地窗口句柄,并发送 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 XAML框架的解决方案? - Rajesh

0

这个解决方案适用于基于 Wpf 的应用程序

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接