まず、最後に操作された時間を取得する方法にGetLastInputInfo
というAPIがあります。
VBNET
1Public Class Form1
2
3 'APIの定義
4 <DllImport("user32.dll")>
5 Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
6 End Function
7
8 <StructLayout(LayoutKind.Sequential)>
9 Structure LASTINPUTINFO
10 Public cbSize As UInteger
11 Public dwTime As UInteger
12 End Structure
13
14 Private timer1 As Timer
15 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
16 Timer1 = New Timer With {.Interval = 100, .Enabled = True}
17 AddHandler timer1.Tick, Sub()
18 Dim info As LASTINPUTINFO
19 Dim r As Boolean
20
21 info.cbSize = Marshal.SizeOf(info)
22 r = GetLastInputInfo(info)
23
24 Dim span = New TimeSpan((Environment.TickCount - info.dwTime) * 10000)
25 Me.Text = $"無操作時間 = {span}"
26 End Sub
27 End Sub
28End Class
29
こちらで動作の確認が行えるかと思います。
また、初期状態への戻し方ですが
実行されるソースの場所をMain_Loadにするという考え方ではなく、
・開いているフォームがあれば閉じる。
・最初の状態に表示されているフォームを表示する
・表示されているコントロール等を初期状態に戻す
といった処理を行う関数を作成し、それを実行するという形にするのがよろしいかと思います。
初期状態にするという関数を作成すれば、Main_Loadでもこれを呼べばいいことになります。
追記
MainFormというフォームを作り、ボタンとタイマーを配置してください。
ボタンを押すと、サブフォームが表示され、5秒後に元に戻ります。
VBNET
1Public Class MainForm
2
3 Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
4 InitializeApplication()
5 End Sub
6
7 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
8 InitializeApplication()
9 End Sub
10
11 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
12 Dim form As New Form() With {.Name = $"SubForm", .Text = "サブフォーム"}
13 form.Show()
14
15 Me.Hide()
16
17 Timer1.Interval = 5000
18 Timer1.Enabled = True
19 End Sub
20
21 Private Sub InitializeApplication()
22
23 '自分以外のフォームを閉じる
24 For Each frm As Form In New ArrayList(Application.OpenForms)
25 If frm IsNot Me Then
26 frm.Close()
27 End If
28 Next
29
30 Me.Show()
31
32 End Sub
33
34End Class
35
ただし、サブフォームなどで、ダイアログを連続で表示するような形になっている場合はダイアログが表示されてしまいます。
例)
VBNET
1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
2 MessageBox.Show("テスト")
3 MessageBox.Show("テスト2")
4 End Sub
とあった場合、"テスト"のダイアログで止めている場合、サブフォームが閉じた後に"テスト2"のダイアログが表示されます。