天天看点

WPF DispatcherTimer(定时器应用) 无人触摸60s自动关闭窗口

原文:

WPF DispatcherTimer(定时器应用) 无人触摸60s自动关闭窗口

如果无人触摸:60s自动关闭窗口

xmal:部分

<s:SurfaceWindow x:Class="SurfaceApplication1.SurfaceWindow1"

    xmlns="

http://schemas.microsoft.com/winfx/2006/xaml/presentation

"

    xmlns:x="

http://schemas.microsoft.com/winfx/2006/xaml

    xmlns:s="

http://schemas.microsoft.com/surface/2008

    Title="SurfaceApplication1"

                 TouchDown="SurfaceWindow_TouchDown"

    >

    <Grid  >

        <Button Width="80" Height="80" Background="Yellow" Click="Button_Click">OK</Button>

        <Label x:Name="lblSeconds"> 你好!</Label>

    </Grid>

</s:SurfaceWindow>

cs:部分

//60s无人操作自动关闭

        DispatcherTimer dTimer;

        private void Button_Click(object sender, RoutedEventArgs e)

        {

            //构造一个DispatcherTimer类实例

            dTimer = new System.Windows.Threading.DispatcherTimer();

            //设置事件处理函数

            dTimer.Tick += new EventHandler(dispatcherTimer_Tick);

        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)

            this.Close();

   //触摸后重新给“i”赋值

        private void SurfaceWindow_TouchDown(object sender, TouchEventArgs e)

            int i = 60;

            //定时器时间间隔1s

            if ( dTimer.Interval!=null)

            {

                dTimer.Interval = new TimeSpan(0, 0, i);

                dTimer.Start();

            }