@@ -20,7 +20,7 @@ class _MyAppState extends State<MyApp> {
2020 @override
2121 void initState () {
2222 super .initState ();
23- _registerDelegate ();
23+ // Removed auto-registration - use buttons to register/unregister
2424 }
2525
2626 @override
@@ -33,7 +33,12 @@ class _MyAppState extends State<MyApp> {
3333
3434 // Register a WindowProc delegate to intercept messages
3535 void _registerDelegate () {
36- _delegateId = registerWindowProcDelegate ((hwnd, message, wParam, lParam) {
36+ if (_delegateId != null ) {
37+ // Already registered
38+ return ;
39+ }
40+
41+ final id = registerWindowProcDelegate ((hwnd, message, wParam, lParam) {
3742 // Example: Log WM_ACTIVATEAPP (0x001C) messages
3843 if (message == 0x001C ) {
3944 setState (() {
@@ -55,6 +60,28 @@ class _MyAppState extends State<MyApp> {
5560 // Return null to let other handlers process the message
5661 return null ;
5762 });
63+
64+ setState (() {
65+ _delegateId = id;
66+ _messages.insert (0 , 'Delegate registered with ID: $id ' );
67+ if (_messages.length > 10 ) {
68+ _messages.removeLast ();
69+ }
70+ });
71+ }
72+
73+ // Unregister the WindowProc delegate
74+ void _unregisterDelegate () {
75+ if (_delegateId != null ) {
76+ unregisterWindowProcDelegate (_delegateId! );
77+ setState (() {
78+ _messages.insert (0 , 'Delegate unregistered (ID: $_delegateId )' );
79+ _delegateId = null ;
80+ if (_messages.length > 10 ) {
81+ _messages.removeLast ();
82+ }
83+ });
84+ }
5885 }
5986
6087 @override
@@ -67,6 +94,29 @@ class _MyAppState extends State<MyApp> {
6794 child: Column (
6895 crossAxisAlignment: CrossAxisAlignment .start,
6996 children: [
97+ // Control buttons
98+ Row (
99+ children: [
100+ ElevatedButton (
101+ onPressed: _delegateId == null ? _registerDelegate : null ,
102+ child: const Text ('Register Delegate' ),
103+ ),
104+ const SizedBox (width: 8 ),
105+ ElevatedButton (
106+ onPressed: _delegateId != null ? _unregisterDelegate : null ,
107+ child: const Text ('Unregister Delegate' ),
108+ ),
109+ ],
110+ ),
111+ const SizedBox (height: 8 ),
112+ Text (
113+ 'Status: ${_delegateId != null ? "Registered (ID: $_delegateId )" : "Not Registered" }' ,
114+ style: Theme .of (context).textTheme.bodyMedium? .copyWith (
115+ color: _delegateId != null ? Colors .green : Colors .red,
116+ fontWeight: FontWeight .bold,
117+ ),
118+ ),
119+ const SizedBox (height: 16 ),
70120 Text (
71121 'WindowProc Messages:' ,
72122 style: Theme .of (context).textTheme.titleMedium,
@@ -76,7 +126,7 @@ class _MyAppState extends State<MyApp> {
76126 child: _messages.isEmpty
77127 ? const Center (
78128 child: Text (
79- 'No messages intercepted yet.\n Try switching to another window and back.' ,
129+ 'No messages intercepted yet.\n Register the delegate and try switching to another window and back.' ,
80130 textAlign: TextAlign .center,
81131 ),
82132 )
0 commit comments