通过AutomationElement设置DateTimePicker元素

时间:2012-02-17 16:12:17

标签: c# .net datetimepicker ui-automation automationelement

我希望能够通过DateTimePickerAutomationElement元素设置为特定时间。它将时间存储为“hh:mm:ss tt”(即下午10:45:56)。

我得到了这样的元素:

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)。第二个选项告诉我该元素是只读的,如何更改状态以使其不是只读的?或者更简单地说,我怎样才能改变时间:(?

1 个答案:

答案 0 :(得分: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);
    }
}