gpt4 book ai didi

c# - 检查应用程序是否在一段时间内空闲并锁定它

转载 作者:太空狗 更新时间:2023-10-29 19:59:13 24 4
gpt4 key购买 nike

在我的项目中,我需要一个应用程序锁(与 Windows 锁相同)。如果应用程序在一段时间内处于空闲状态,则应用程序应被锁定,即应用程序的登录窗口将出现。我如何在 WPF C# 应用程序中执行此操作?

最佳答案

你可以使用这些函数

看到这段代码,你必须在你的表单中添加一个计时器,并设置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();
}
}
}

关于c# - 检查应用程序是否在一段时间内空闲并锁定它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1541981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com