0

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

    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;
        }
    }

我的问题是:
是否有可能使这个东西成为全局而不是在我创建的每个窗口中重写它?
有更好的方法吗?
谢谢!

4

2 回答 2

0

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

于 2013-04-25T20:14:49.480 回答
0

I would create a base window class and then have all of your Windows inherit from it. Once you have the new base class and you add a window or are updating existing windows to inherit from it, you have to also change the Xaml to reflect the new base class. So, here is an example base Window class.

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

    void WindowBase_Loaded(object sender, RoutedEventArgs e)
    {

    }
}

Here would be a window inheriting from it.

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

and then here the Xaml for the same window

<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>
于 2013-04-25T23:54:07.943 回答