2013-04-25 127 views
0

如果用户在一段时间内没有使用过它,我需要关闭我的应用程序。 我现在使用的方法在单个窗口上效果很好,但我似乎无法使其成为全局。 这是我要做的事现在:自动关闭WPF应用程序

DispatcherTimer dt; 
    public Window3() 
    { 
     InitializeComponent(); 
     //initialize the timer 
     dt = new DispatcherTimer(); 
     dt.Interval = TimeSpan.FromSeconds(1); 
     dt.Start(); 
     dt.Tick += new EventHandler(dt_Tick); 
    } 

    long ticks = 0; 
    void dt_Tick(object sender, EventArgs e) 
    { 
     ticks++; 
     //close the application if 10 seconds passed without an event 
     if (ticks > 10) 
     { 
      Close(); 
     } 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     //Initialize a hook 
     ((HwndSource)PresentationSource.FromVisual(this)).AddHook(myHook); 
    } 


    private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) 
    { 
     //reset counter 
     ticks = 0; 
     switch (msg) 
     { 
      // process messages here 
      default: 
       return IntPtr.Zero; 
     } 
    } 

我的问题是:
是有可能使这件事情,而不是全球每一个窗口,我创造改写呢?
有没有更好的方法来做到这一点?
谢谢!

回答

0

我会创建一个基本窗口类,然后让所有的Windows继承它。一旦你有了新的基类,你添加一个窗口或者更新现有的窗口以继承它,你还必须更改Xaml以反映新的基类。所以,这里是一个基本的Window类的例子。

public class WindowBase : Window 
{ 
    public WindowBase() 
    { 
     //initialize timer and hook loaded event 
     this.Loaded += WindowBase_Loaded; 
    } 

    void WindowBase_Loaded(object sender, RoutedEventArgs e) 
    { 

    } 
} 

这里是一个从它继承的窗口。

public partial class MainWindow : WindowBase 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 
} 

,然后在这里的XAML同一窗口

<local:WindowBase x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfApplication1" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 

    </Grid> 
</local:WindowBase> 
0

创建一个单例类并将大部分功能移到那里。这样,所有的计时器或线程都可以驻留在那里,并且所有的窗口或用户控件都可以调用单例类,并且单独关闭该应用程序。