Pergunta

I have a need to shutdown my application if the user haven't used it for certain period of time. The method I use now works great on a single window but i can't seem to make it global. this is how i do it now:

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

My questions are:
is it possible to make this thing global instead of rewriting it in every window i create?
is there a better way to do it?
Thanks!

Foi útil?

Solução

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>

Outras dicas

Make a singleton class and move most of the functionality over there. That way all your timer or thread can reside there, and all your windows or user controls can call the singleton class, and that alone will shut down the application.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top