Windowがクリックされたら自身のタイトルを変更するコード。
以下のコードをForm1.csに張り付ければ動くはず。
参照:
Detect active window changed using C# without polling
C#
1 using System ;
2 using System . Text ;
3 using System . Windows . Forms ;
4 using System . Runtime . InteropServices ;
5
6
7 namespace WindowsFormsApp1
8 {
9 public partial class Form1 : Form
10 {
11 public Form1 ( )
12 {
13 InitializeComponent ( ) ;
14 this . TopMost = true ;
15 dele = new WinEventDelegate ( WinEventProc ) ;
16 IntPtr m_hhook = SetWinEventHook ( EVENT_SYSTEM_FOREGROUND , EVENT_SYSTEM_FOREGROUND , IntPtr . Zero , dele , 0 , 0 , WINEVENT_OUTOFCONTEXT ) ;
17 }
18
19 WinEventDelegate dele = null ;
20
21 delegate void WinEventDelegate ( IntPtr hWinEventHook , uint eventType , IntPtr hwnd , int idObject , int idChild , uint dwEventThread , uint dwmsEventTime ) ;
22
23 [ DllImport ( "user32.dll" ) ]
24 static extern IntPtr SetWinEventHook ( uint eventMin , uint eventMax , IntPtr hmodWinEventProc , WinEventDelegate lpfnWinEventProc , uint idProcess , uint idThread , uint dwFlags ) ;
25
26 private const uint WINEVENT_OUTOFCONTEXT = 0 ;
27 private const uint EVENT_SYSTEM_FOREGROUND = 3 ;
28
29 [ DllImport ( "user32.dll" ) ]
30 static extern IntPtr GetForegroundWindow ( ) ;
31
32 [ DllImport ( "user32.dll" ) ]
33 static extern int GetWindowText ( IntPtr hWnd , StringBuilder text , int count ) ;
34
35 private string GetActiveWindowTitle ( )
36 {
37 const int nChars = 256 ;
38 IntPtr handle = IntPtr . Zero ;
39 StringBuilder Buff = new StringBuilder ( nChars ) ;
40 handle = GetForegroundWindow ( ) ;
41
42 if ( GetWindowText ( handle , Buff , nChars ) > 0 )
43 {
44 return Buff . ToString ( ) ;
45 }
46 return null ;
47 }
48
49 public void WinEventProc ( IntPtr hWinEventHook , uint eventType , IntPtr hwnd , int idObject , int idChild , uint dwEventThread , uint dwmsEventTime )
50 {
51 var windowTitle = GetActiveWindowTitle ( ) ;
52
53 if ( windowTitle != this . Text && windowTitle != null )
54 {
55 this . Text = windowTitle ;
56 }
57 }
58 }
59 }
60
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。