程序自我检查是否正在运行进程或空闲

时间:2014-01-04 04:12:37

标签: vb.net

我想知道应用程序是否有办法检查它正在运行的进程(线程)(自检)并使用该信息执行某些操作。作为一个例子,我想按一个按钮来做某事,但如果程序已经做了其他事情,我想有或没有选择,运行该按钮后面的其余程序。希望有道理。我没有运行多线程应用程序所以我需要知道主线程是否正在运行或应用程序是否处于空闲状态。

1 个答案:

答案 0 :(得分:1)

如果我了解您的要求 - 您可以使用GetLastInputInfo API。

Option Strict On
Option Explicit On
Imports System.Runtime.InteropServices

Public Class Form1

Dim lastInput As New LASTINPUTINFO()

<StructLayout(LayoutKind.Sequential)> Structure LASTINPUTINFO
    <MarshalAs(UnmanagedType.U4)> Public Size As Integer
    <MarshalAs(UnmanagedType.U4)> Public Time As Integer
End Structure

<DllImport("user32.dll")> Shared Function GetLastInputInfo(ByRef lii As LASTINPUTINFO) As Boolean
End Function

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Timer1.Interval = 1000
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    lastInput.Size = Marshal.SizeOf(lastInput)
    lastInput.Time = 0
    GetLastInputInfo(lastInput)
    Label1.Text = Convert.ToInt32((Environment.TickCount - lastInput.Time) / 1000).ToString
    If CInt((Environment.TickCount - lastInputInf.Time) / 1000) > {your amount in sec.} Then  
        Timer1.Stop()
        'run some code when this happens
    End If
End Sub
End Class