LoginSignup
5
6

More than 1 year has passed since last update.

C# PC画面ロック 検出

Last updated at Posted at 2021-10-09

みなさんこんにちは。

本日紹介する内容は、WindowsPCが検知されたことを検出する方法です。
画面ロック中は〇〇、解除中は〇〇したい。という機能が実現できます。

仕組み

画面のロック検知をするためには、画面の状態を通知する必要があります。
通知をする仕組みとして、「WTSRegisterSessionNotification」
という「wtsapi32」の機能を利用します。

通知を受けた後、画面のステータスを確認し、
ロック状態のステータスコードと等しい場合、PCがロックされたと認定します。

開発環境

Windows10 
※他のOSでは動作確認しておりませんが、恐らく問題なく動作します

コード紹介

Form1.cs
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace LockDetect
{
    public partial class Form1 : Form
    {
        [DllImport("WtsApi32.dll")]
        private static extern bool WTSRegisterSessionNotification(IntPtr hWnd, [MarshalAs(UnmanagedType.U4)] int dwFlags);
        [DllImport("WtsApi32.dll")]
        private static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);

        const int NOTIFY_FOR_THIS_SESSION = 0;

        const int WM_WTSSESSION_CHANGE = 0x2b1;

        const int WTS_SESSION_LOCK = 0x7;
        const int WTS_SESSION_UNLOCK = 0x8;
        const int WTS_SESSION_REMOTE_CONTROL = 0x9;

        public Form1()
        {
            InitializeComponent();

            // 画面状態の通知に必要
            WTSRegisterSessionNotification(this.Handle, NOTIFY_FOR_THIS_SESSION);
        }

        protected override void WndProc(ref Message m)
        {
            // 画面状態が変更された
            if (m.Msg == WM_WTSSESSION_CHANGE)
            {
                int value = m.WParam.ToInt32();

                switch (value)
                {
                    case WTS_SESSION_LOCK:
                        Console.WriteLine("PCがロックされました");
                        break;

                    case WTS_SESSION_UNLOCK:
                        Console.WriteLine("PCのロックが解除されました");
                        break;

                    case WTS_SESSION_REMOTE_CONTROL:
                        Console.WriteLine("PCがRDP制御されました");
                        break;
                    default:
                        break;
                }
            }

            base.WndProc(ref m);
        }
    }
}

以上がコード紹介となります。
是非、ご参考ください。

今回はステータスコードとして、
ロック、アンロック、RDPのみ紹介していますが、他にも何種類かあるので
興味がある方は色々調べてみてください。
面白いステータスがあれば是非、共有いただけると幸いです。

参考

MicroSoft : WTSRegisterSessionNotification

pinvoke.net : wtsregistersessionnotification (wtsapi32)

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6