让用户指定定时器时间?

时间:2013-04-15 18:17:08

标签: c# windows timer textbox dispatcher

我希望DispatcherTimer从文本框中读取时间值:objTextBox。 我试过这段代码,但似乎TimeSpan与字符串不兼容或者我做错了什么?

错误:参数1:无法从'string'转换为'long'

也;时间是否必须在文本框中显示如下:0,0,1或00:00:01?

代码在这里:

    private void testing()
    {
        string theText = objTextBox.Text;
        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(listjob3_Tick);
        dispatcherTimer.Interval = new TimeSpan(theText);
        dispatcherTimer.Start();
    }

4 个答案:

答案 0 :(得分:1)

要将字符串转换为TimeSpan,请使用TimeSpan.Parse(str)

答案 1 :(得分:1)

我猜你的例外就在这里:

dispatcherTimer.Interval = new TimeSpan(theText);

请改用:

dispatcherTimer.Interval = new TimeSpan(Convert.ToInt64(theText));

答案 2 :(得分:1)

要从TimeSpan转换为string,您可以使用TimeSpan.Parse,但您必须遵循以下格式[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

ws    is Optional white space.
-     is An optional minus sign, which indicates a negative TimeSpan. 
d     is Days, ranging from 0 to 10675199.
.     is A culture-sensitive symbol that separates days from hours. The invariant format uses a period (".") character.
hh    is Hours, ranging from 0 to 23. 
:     is The culture-sensitive time separator symbol. The invariant format uses a colon (":") character.
mm    is Minutes, ranging from 0 to 59. 
ss    is Optional seconds, ranging from 0 to 59. 
.     is A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (".") character.
ff    is Optional fractional seconds, consisting of one to seven decimal digits. 

所以转换几天你实际上可以使用TimeSpan.Parse并传入字符串 - 但是如果你想转换分钟,就需要对输入进行一些按摩:

var input = string.Format("00:{0}", objTextBox.Text.PadLeft(2, '0'));

然后您可以发布var timeSpan = TimeSpan.Parse(input);,因为您已正确格式化,Parse将成功。另一个选择是把分钟变成几天我想,但这需要一些浮点工作,而且真的,IMO,不是一个好的选择。

答案 3 :(得分:0)

@Sneakybastardd:你有阅读关于构造函数重载的TimeSpan documentation吗?你会注意到它们都不带字符串参数:需要整数类型。

阅读the documentation后,您可能会发现这些TimeSpan方法很有用:

  • Parse()
  • ParseExact()
  • TryParse()

关于格式,请参阅"Standard TimeSpan Format Strings""Custom TimeSpan Format Strings"。如果它发挥作用,也可以对不同文化的各种默认TimeSpan格式进行一些研究。