Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

c# - Check if an application is idle for a time period and lock it

In my project I need an application lock (same as windows lock). If the application is idle for a time period the application should be locked i.e, the login window for the application will appear. How can I do it in a WPF C# application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use these functions

see this code, you must add a timer to your form, and set this.timer1.Enabled = true;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication9
{
  internal struct LASTINPUTINFO
  {
    public uint cbSize;    
    public uint dwTime;
  }

  public partial class Form1 : Form
  {

    [DllImport("User32.dll")]
    public static extern bool LockWorkStation();
    [DllImport("User32.dll")]
    private static extern bool GetLastInputInfo(ref LASTINPUTINFO Dummy);
    [DllImport("Kernel32.dll")]
    private static extern uint GetLastError();

public static uint GetIdleTime()
{
  LASTINPUTINFO LastUserAction = new LASTINPUTINFO();
  LastUserAction.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastUserAction);
  GetLastInputInfo(ref LastUserAction);
  return ((uint)Environment.TickCount - LastUserAction.dwTime);
}

public static long GetTickCount()
{
  return Environment.TickCount;
}

public static long GetLastInputTime()
{
  LASTINPUTINFO LastUserAction = new LASTINPUTINFO();
  LastUserAction.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastUserAction);
  if (!GetLastInputInfo(ref LastUserAction))
  {
    throw new Exception(GetLastError().ToString());
  }

  return LastUserAction.dwTime;
}

    public Form1()
    {
      InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
      if (GetIdleTime() > 10000)  //10 secs, Time to wait before locking
        LockWorkStation();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      timer1.Start();
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...