Форум программистов, компьютерный форум, киберфорум
C# .NET
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.62/13: Рейтинг темы: голосов - 13, средняя оценка - 4.62
 Аватар для desys
-7 / 12 / 1
Регистрация: 01.09.2012
Сообщений: 60

Код по управлению внешним процессом, исправить ошибки

14.09.2012, 09:09. Показов 2566. Ответов 5
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Выкладываю код по управлению внешним процессом, но есть ошибки... Может разберемся?

Код С#: Warning, bidlocodes!!!
Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
 
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        bool installed;
        IntPtr hWinEventhook;
 
        [DllImport("user32.dll")]
        private static extern int SetForegroundWindow(IntPtr hWnd);
        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMAXIMIZED = 3;
        private const int SW_RESTORE = 9;
 
        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
 
        public Form1()
        {
            InitializeComponent();
        }
 
 
        private void closeHandlerParagraf(object sender, EventArgs e)
        {
            label1.Text ="Закрываю Блакнот";
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            var processes = Process.GetProcessesByName("notepad");
 
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = "notepad";
            proc.EnableRaisingEvents = true;
            proc.SynchronizingObject = this;
 
            proc.Exited += new EventHandler(closeHandlerParagraf);
            
            Wait();
            if (processes.Any())
            {
                var handle = processes.First().MainWindowHandle;
                ShowWindow(handle, SW_RESTORE);
                SetForegroundWindow(handle);
                label1.Text = "Разворачиваю Блокнот"; 
            }
 
            else 
            { 
                proc.Start();
                label1.Text = "Запускаю Блокнот";
                
                
            }
            
            if (installed && pinvoke.User32.UnhookWinEvent(hWinEventhook))
                installed = false;
            else if (!installed)
            {
                var procs = Process.GetProcessesByName("notepad");
 
                if (procs.Length > 0)
                    hWinEventhook = pinvoke.User32.SetWinEventHook(pinvoke.User32.EVENT_SYSTEM_MINIMIZESTART, pinvoke.User32.EVENT_SYSTEM_MINIMIZEEND, IntPtr.Zero, WinEventProc, procs[0].Id, 0, pinvoke.User32.WINEVENT_OUTOFCONTEXT);
 
                if (hWinEventhook != IntPtr.Zero)
                    installed = true;
                else { }//MessageBox.Show("Can't install winevent hook, err " +Marshal.GetLastWin32Error());
            }
        }
 
        void WinEventProc(IntPtr hWinEventHook,uint dwEvent,IntPtr hWnd,int idObject,int idChild,uint dwEventThread,uint dwmsEventTime)
        {
            Debug.WriteLine(string.Format("Event: {0}\r\n\tHWND: 0x{1:X8}\r\n\tidObject: {2}\r\n\tidChild: {3}\r\n\tdwEventThread: 0x{4:X8}\r\n\tTime: {5}\r\n",dwEvent, hWnd,idObject,idChild, dwEventThread, dwmsEventTime));
 
            switch (dwEvent)
            {
                case pinvoke.User32.EVENT_SYSTEM_MINIMIZEEND:
                    label1.Text = "Разворачиваю Блокнот";
                    break;
                case pinvoke.User32.EVENT_SYSTEM_MINIMIZESTART:
                    label1.Text = "Сворачиваю Блокнот";
                    break;
            }
        }
 
        private static void Wait()
        {
            Process myProcess = Process.GetProcessesByName("notepad").FirstOrDefault();
            if (myProcess != null)
            {
                myProcess.EnableRaisingEvents = true;
                myProcess.Exited += (sender, e) =>
                {
 
                };
            }
 
            
        }
   
    }     
}

Используемый класс pinvoke.cs
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Runtime.InteropServices;
 
namespace pinvoke
{
    static class User32
    {
        const string USER32 = "user32.dll";
 
        public const uint EVENT_SYSTEM_MINIMIZESTART = 0x16;
        public const uint EVENT_SYSTEM_MINIMIZEEND = 0x17;
        public const uint WINEVENT_OUTOFCONTEXT = 0x0;
 
        public delegate void WINEVENTPROC (
            IntPtr hWinEventHook,
            uint dwEvent,
            IntPtr hWnd,
            int idObject,
            int idChild,
            uint dwEventThread,
            uint dwmsEventTime
            );
 
        [DllImport( USER32, SetLastError = true )]
        public static extern IntPtr SetWinEventHook (
            [In] uint eventMin,
            [In] uint eventMax,
            [In] IntPtr hmodWinEventProc,
            [MarshalAs( UnmanagedType.FunctionPtr )]
            [In] WINEVENTPROC lpfnWinEventProc,
            [In] int idProcess,
            [In] int idThread,
            [In] uint dwflags
            );
 
        [DllImport( USER32, SetLastError = true )]
        [return: MarshalAs( UnmanagedType.Bool )]
        public static extern bool UnhookWinEvent (
            [In]  IntPtr hWinEventHook
            );
 
        [StructLayout( LayoutKind.Sequential )]
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }
 
        [StructLayout( LayoutKind.Sequential )]
        public struct POINT
        {
            public int x;
            public int y;
        }
 
        [StructLayout( LayoutKind.Sequential )]
        public struct WINDOWPLACEMENT
        {
            public int length;
            public uint flags;
            public uint showCmd;
            public POINT ptMinPosition;
            public POINT ptMaxPosition;
            public RECT  rcNormalPosition;
        }
 
        [DllImport( USER32, SetLastError = true )]
        [return: MarshalAs( UnmanagedType.Bool )]
        public static extern bool GetWindowPlacement (
            [In] IntPtr hWnd,
            [In, Out] ref WINDOWPLACEMENT lpwndpl
            );
    }
}



Ошибка, после попытки развернуть щелкнув на панели, а не на кнопке...
Это наработка, если доделать уверен всем понадобится...
Прошу не пинать, а по Дзенски наставить на верный путь!
А еще попробовать сделать из этого class типа
ProcHook processNote = new ProcHook();
ProcHook processPaint = new ProcHook();
ProcHook processCalc = new ProcHook();
И как то передать имя процесса.
Лэйбл в принципе можно использовать один...

Добавлено через 11 часов 44 минуты
Что никому не интересно?
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
14.09.2012, 09:09
Ответы с готовыми решениями:

Исправить ошибки / код
1) Лесенки с if, else if в цикле while не меняються елементы массива 2) И как можно передать масив из функции Words класса LIbary в...

Ошибки с регистрацией, исправить код
Добрый день, написал скрипт регистрации. При установке чата в базу добавился админ пользователь, далее при регистрации пользователи не...

Есть код нужно исправить ошибки
есть задача: ввести размер квадратной матрицы и ее элементы. Элементы матрицы расположить в динамической памяти. Определить номер...

5
Почетный модератор
Эксперт .NET
 Аватар для NickoTin
8729 / 3681 / 404
Регистрация: 14.06.2010
Сообщений: 4,513
Записей в блоге: 9
14.09.2012, 20:01
pinvoke.cs
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Runtime.InteropServices;
 
namespace pinvoke
{
    static class User32
    {
        const string USER32 = "user32.dll";
 
        public const uint WINEVENT_OUTOFCONTEXT = 0x0;
 
        public delegate void WINEVENTPROC (
            IntPtr hWinEventHook,
            uint dwEvent,
            IntPtr hWnd,
            int idObject,
            int idChild,
            uint dwEventThread,
            uint dwmsEventTime
            );
 
        [DllImport( USER32, SetLastError = true )]
        public static extern IntPtr SetWinEventHook (
            [In] uint eventMin,
            [In] uint eventMax,
            [In] IntPtr hmodWinEventProc,
            [MarshalAs( UnmanagedType.FunctionPtr )]
            [In] WINEVENTPROC lpfnWinEventProc,
            [In] int idProcess,
            [In] int idThread,
            [In] uint dwflags
            );
 
        [DllImport( USER32, SetLastError = true )]
        [return: MarshalAs( UnmanagedType.Bool )]
        public static extern bool UnhookWinEvent (
            [In]  IntPtr hWinEventHook
            );
    }
}
EventType.cs
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
namespace WindowsEvents
{
    #region ~ EVENT DEFINITION (from WinUser.h) ~
    ///*
    // * EVENT DEFINITION
    // */
    //#define EVENT_MIN           0x00000001
    //#define EVENT_MAX           0x7FFFFFFF
 
    ///*
    // *  EVENT_SYSTEM_SOUND
    // *  Sent when a sound is played.  Currently nothing is generating this, we
    // *  this event when a system sound (for menus, etc) is played.  Apps
    // *  generate this, if accessible, when a private sound is played.  For
    // *  example, if Mail plays a "New Mail" sound.
    // *
    // *  System Sounds:
    // *  (Generated by PlaySoundEvent in USER itself)
    // *      hwnd            is NULL
    // *      idObject        is OBJID_SOUND
    // *      idChild         is sound child ID if one
    // *  App Sounds:
    // *  (PlaySoundEvent won't generate notification; up to app)
    // *      hwnd + idObject gets interface pointer to Sound object
    // *      idChild identifies the sound in question
    // *  are going to be cleaning up the SOUNDSENTRY feature in the control panel
    // *  and will use this at that time.  Applications implementing WinEvents
    // *  are perfectly welcome to use it.  Clients of IAccessible* will simply
    // *  turn around and get back a non-visual object that describes the sound.
    // */
    //#define EVENT_SYSTEM_SOUND              0x0001
 
    ///*
    // * EVENT_SYSTEM_ALERT
    // * System Alerts:
    // * (Generated by MessageBox() calls for example)
    // *      hwnd            is hwndMessageBox
    // *      idObject        is OBJID_ALERT
    // * App Alerts:
    // * (Generated whenever)
    // *      hwnd+idObject gets interface pointer to Alert
    // */
    //#define EVENT_SYSTEM_ALERT              0x0002
 
    ///*
    // * EVENT_SYSTEM_FOREGROUND
    // * Sent when the foreground (active) window changes, even if it is changing
    // * to another window in the same thread as the previous one.
    // *      hwnd            is hwndNewForeground
    // *      idObject        is OBJID_WINDOW
    // *      idChild    is INDEXID_OBJECT
    // */
    //#define EVENT_SYSTEM_FOREGROUND         0x0003
 
    ///*
    // * Menu
    // *      hwnd            is window (top level window or popup menu window)
    // *      idObject        is ID of control (OBJID_MENU, OBJID_SYSMENU, OBJID_SELF for popup)
    // *      idChild         is CHILDID_SELF
    // *
    // * EVENT_SYSTEM_MENUSTART
    // * EVENT_SYSTEM_MENUEND
    // * For MENUSTART, hwnd+idObject+idChild refers to the control with the menu bar,
    // *  or the control bringing up the context menu.
    // *
    // * Sent when entering into and leaving from menu mode (system, app bar, and
    // * track popups).
    // */
    //#define EVENT_SYSTEM_MENUSTART          0x0004
    //#define EVENT_SYSTEM_MENUEND            0x0005
 
    ///*
    // * EVENT_SYSTEM_MENUPOPUPSTART
    // * EVENT_SYSTEM_MENUPOPUPEND
    // * Sent when a menu popup comes up and just before it is taken down.  Note
    // * that for a call to TrackPopupMenu(), a client will see EVENT_SYSTEM_MENUSTART
    // * followed almost immediately by EVENT_SYSTEM_MENUPOPUPSTART for the popup
    // * being shown.
    // *
    // * For MENUPOPUP, hwnd+idObject+idChild refers to the NEW popup coming up, not the
    // * parent item which is hierarchical.  You can get the parent menu/popup by
    // * asking for the accParent object.
    // */
    //#define EVENT_SYSTEM_MENUPOPUPSTART     0x0006
    //#define EVENT_SYSTEM_MENUPOPUPEND       0x0007
 
 
    ///*
    // * EVENT_SYSTEM_CAPTURESTART
    // * EVENT_SYSTEM_CAPTUREEND
    // * Sent when a window takes the capture and releases the capture.
    // */
    //#define EVENT_SYSTEM_CAPTURESTART       0x0008
    //#define EVENT_SYSTEM_CAPTUREEND         0x0009
 
    ///*
    // * Move Size
    // * EVENT_SYSTEM_MOVESIZESTART
    // * EVENT_SYSTEM_MOVESIZEEND
    // * Sent when a window enters and leaves move-size dragging mode.
    // */
    //#define EVENT_SYSTEM_MOVESIZESTART      0x000A
    //#define EVENT_SYSTEM_MOVESIZEEND        0x000B
 
    ///*
    // * Context Help
    // * EVENT_SYSTEM_CONTEXTHELPSTART
    // * EVENT_SYSTEM_CONTEXTHELPEND
    // * Sent when a window enters and leaves context sensitive help mode.
    // */
    //#define EVENT_SYSTEM_CONTEXTHELPSTART   0x000C
    //#define EVENT_SYSTEM_CONTEXTHELPEND     0x000D
 
    ///*
    // * Drag & Drop
    // * EVENT_SYSTEM_DRAGDROPSTART
    // * EVENT_SYSTEM_DRAGDROPEND
    // * Send the START notification just before going into drag&drop loop.  Send
    // * the END notification just after canceling out.
    // * Note that it is up to apps and OLE to generate this, since the system
    // * doesn't know.  Like EVENT_SYSTEM_SOUND, it will be a while before this
    // * is prevalent.
    // */
    //#define EVENT_SYSTEM_DRAGDROPSTART      0x000E
    //#define EVENT_SYSTEM_DRAGDROPEND        0x000F
 
    ///*
    // * Dialog
    // * Send the START notification right after the dialog is completely
    // *  initialized and visible.  Send the END right before the dialog
    // *  is hidden and goes away.
    // * EVENT_SYSTEM_DIALOGSTART
    // * EVENT_SYSTEM_DIALOGEND
    // */
    //#define EVENT_SYSTEM_DIALOGSTART        0x0010
    //#define EVENT_SYSTEM_DIALOGEND          0x0011
 
    ///*
    // * EVENT_SYSTEM_SCROLLING
    // * EVENT_SYSTEM_SCROLLINGSTART
    // * EVENT_SYSTEM_SCROLLINGEND
    // * Sent when beginning and ending the tracking of a scrollbar in a window,
    // * and also for scrollbar controls.
    // */
    //#define EVENT_SYSTEM_SCROLLINGSTART     0x0012
    //#define EVENT_SYSTEM_SCROLLINGEND       0x0013
 
    ///*
    // * Alt-Tab Window
    // * Send the START notification right after the switch window is initialized
    // * and visible.  Send the END right before it is hidden and goes away.
    // * EVENT_SYSTEM_SWITCHSTART
    // * EVENT_SYSTEM_SWITCHEND
    // */
    //#define EVENT_SYSTEM_SWITCHSTART        0x0014
    //#define EVENT_SYSTEM_SWITCHEND          0x0015
 
    ///*
    // * EVENT_SYSTEM_MINIMIZESTART
    // * EVENT_SYSTEM_MINIMIZEEND
    // * Sent when a window minimizes and just before it restores.
    // */
    //#define EVENT_SYSTEM_MINIMIZESTART      0x0016
    //#define EVENT_SYSTEM_MINIMIZEEND        0x0017
 
 
    //#if(_WIN32_WINNT >= 0x0600)
    //#define EVENT_SYSTEM_DESKTOPSWITCH      0x0020
    //#endif /* _WIN32_WINNT >= 0x0600 */
 
 
    //#if(_WIN32_WINNT >= 0x0602)
    //// AppGrabbed: HWND = hwnd of app thumbnail, objectID = 0, childID = 0
    //#define EVENT_SYSTEM_SWITCHER_APPGRABBED    0x0024
    //// OverTarget: HWND = hwnd of app thumbnail, objectID =
    ////            1 for center
    ////            2 for near snapped
    ////            3 for far snapped
    ////            4 for prune
    ////            childID = 0
    //#define EVENT_SYSTEM_SWITCHER_APPOVERTARGET 0x0025
    //// Dropped: HWND = hwnd of app thumbnail, objectID = <same as above>, childID = 0
    //#define EVENT_SYSTEM_SWITCHER_APPDROPPED    0x0026
    //// Cancelled: HWND = hwnd of app thumbnail, objectID = 0, childID = 0
    //#define EVENT_SYSTEM_SWITCHER_CANCELLED     0x0027
    //#endif /* _WIN32_WINNT >= 0x0602 */
 
 
    //#if(_WIN32_WINNT >= 0x0602)
 
    ///*
    // * Sent when an IME's soft key is pressed and should be echoed,
    // * but is not passed through the keyboard hook.
    // * Must not be sent when a key is sent through the keyboard hook.
    // *     HWND             is the hwnd of the UI containing the soft key
    // *     idChild          is the Unicode value of the character entered
    // *     idObject         is a bitfield
    // *         0x00000001: set if a 32-bit Unicode surrogate pair is used
    // */
    //#define EVENT_SYSTEM_IME_KEY_NOTIFICATION  0x0029
 
    //#endif /* _WIN32_WINNT >= 0x0602 */
 
 
    //#if(_WIN32_WINNT >= 0x0601)
    //#define EVENT_SYSTEM_END        0x00FF
 
    //#define EVENT_OEM_DEFINED_START     0x0101
    //#define EVENT_OEM_DEFINED_END       0x01FF
 
    //#define EVENT_UIA_EVENTID_START         0x4E00
    //#define EVENT_UIA_EVENTID_END           0x4EFF
 
    //#define EVENT_UIA_PROPID_START          0x7500
    //#define EVENT_UIA_PROPID_END            0x75FF
    //#endif /* _WIN32_WINNT >= 0x0601 */
 
    //#if(_WIN32_WINNT >= 0x0501)
    //#define EVENT_CONSOLE_CARET             0x4001
    //#define EVENT_CONSOLE_UPDATE_REGION     0x4002
    //#define EVENT_CONSOLE_UPDATE_SIMPLE     0x4003
    //#define EVENT_CONSOLE_UPDATE_SCROLL     0x4004
    //#define EVENT_CONSOLE_LAYOUT            0x4005
    //#define EVENT_CONSOLE_START_APPLICATION 0x4006
    //#define EVENT_CONSOLE_END_APPLICATION   0x4007
 
    ///*
    // * Flags for EVENT_CONSOLE_START/END_APPLICATION.
    // */
    //#if defined(_WIN64)
    //#define CONSOLE_APPLICATION_16BIT       0x0000
    //#else
    //#define CONSOLE_APPLICATION_16BIT       0x0001
    //#endif
 
    ///*
    // * Flags for EVENT_CONSOLE_CARET
    // */
    //#define CONSOLE_CARET_SELECTION         0x0001
    //#define CONSOLE_CARET_VISIBLE           0x0002
    //#endif /* _WIN32_WINNT >= 0x0501 */
 
    //#if(_WIN32_WINNT >= 0x0601)
    //#define EVENT_CONSOLE_END       0x40FF
    //#endif /* _WIN32_WINNT >= 0x0601 */
 
    ///*
    // * Object events
    // *
    // * The system AND apps generate these.  The system generates these for
    // * real windows.  Apps generate these for objects within their window which
    // * act like a separate control, e.g. an item in a list view.
    // *
    // * When the system generate them, dwParam2 is always WMOBJID_SELF.  When
    // * apps generate them, apps put the has-meaning-to-the-app-only ID value
    // * in dwParam2.
    // * For all events, if you want detailed accessibility information, callers
    // * should
    // *      * Call AccessibleObjectFromWindow() with the hwnd, idObject parameters
    // *          of the event, and IID_IAccessible as the REFIID, to get back an
    // *          IAccessible* to talk to
    // *      * Initialize and fill in a VARIANT as VT_I4 with lVal the idChild
    // *          parameter of the event.
    // *      * If idChild isn't zero, call get_accChild() in the container to see
    // *          if the child is an object in its own right.  If so, you will get
    // *          back an IDispatch* object for the child.  You should release the
    // *          parent, and call QueryInterface() on the child object to get its
    // *          IAccessible*.  Then you talk directly to the child.  Otherwise,
    // *          if get_accChild() returns you nothing, you should continue to
    // *          use the child VARIANT.  You will ask the container for the properties
    // *          of the child identified by the VARIANT.  In other words, the
    // *          child in this case is accessible but not a full-blown object.
    // *          Like a button on a titlebar which is 'small' and has no children.
    // */
 
    ///*
    // * For all EVENT_OBJECT events,
    // *      hwnd is the dude to Send the WM_GETOBJECT message to (unless NULL,
    // *          see above for system things)
    // *      idObject is the ID of the object that can resolve any queries a
    // *          client might have.  It's a way to deal with windowless controls,
    // *          controls that are just drawn on the screen in some larger parent
    // *          window (like SDM), or standard frame elements of a window.
    // *      idChild is the piece inside of the object that is affected.  This
    // *          allows clients to access things that are too small to have full
    // *          blown objects in their own right.  Like the thumb of a scrollbar.
    // *          The hwnd/idObject pair gets you to the container, the dude you
    // *          probably want to talk to most of the time anyway.  The idChild
    // *          can then be passed into the acc properties to get the name/value
    // *          of it as needed.
    // *
    // * Example #1:
    // *      System propagating a listbox selection change
    // *      EVENT_OBJECT_SELECTION
    // *          hwnd == listbox hwnd
    // *          idObject == OBJID_WINDOW
    // *          idChild == new selected item, or CHILDID_SELF if
    // *              nothing now selected within container.
    // *      Word '97 propagating a listbox selection change
    // *          hwnd == SDM window
    // *          idObject == SDM ID to get at listbox 'control'
    // *          idChild == new selected item, or CHILDID_SELF if
    // *              nothing
    // *
    // * Example #2:
    // *      System propagating a menu item selection on the menu bar
    // *      EVENT_OBJECT_SELECTION
    // *          hwnd == top level window
    // *          idObject == OBJID_MENU
    // *          idChild == ID of child menu bar item selected
    // *
    // * Example #3:
    // *      System propagating a dropdown coming off of said menu bar item
    // *      EVENT_OBJECT_CREATE
    // *          hwnd == popup item
    // *          idObject == OBJID_WINDOW
    // *          idChild == CHILDID_SELF
    // *
    // * Example #4:
    // *
    // * For EVENT_OBJECT_REORDER, the object referred to by hwnd/idObject is the
    // * PARENT container in which the zorder is occurring.  This is because if
    // * one child is zordering, all of them are changing their relative zorder.
    // */
    //#define EVENT_OBJECT_CREATE                 0x8000  // hwnd + ID + idChild is created item
    //#define EVENT_OBJECT_DESTROY                0x8001  // hwnd + ID + idChild is destroyed item
    //#define EVENT_OBJECT_SHOW                   0x8002  // hwnd + ID + idChild is shown item
    //#define EVENT_OBJECT_HIDE                   0x8003  // hwnd + ID + idChild is hidden item
    //#define EVENT_OBJECT_REORDER                0x8004  // hwnd + ID + idChild is parent of zordering children
    ///*
    // * NOTE:
    // * Minimize the number of notifications!
    // *
    // * When you are hiding a parent object, obviously all child objects are no
    // * longer visible on screen.  They still have the same "visible" status,
    // * but are not truly visible.  Hence do not send HIDE notifications for the
    // * children also.  One implies all.  The same goes for SHOW.
    // */
 
 
    //#define EVENT_OBJECT_FOCUS                  0x8005  // hwnd + ID + idChild is focused item
    //#define EVENT_OBJECT_SELECTION              0x8006  // hwnd + ID + idChild is selected item (if only one), or idChild is OBJID_WINDOW if complex
    //#define EVENT_OBJECT_SELECTIONADD           0x8007  // hwnd + ID + idChild is item added
    //#define EVENT_OBJECT_SELECTIONREMOVE        0x8008  // hwnd + ID + idChild is item removed
    //#define EVENT_OBJECT_SELECTIONWITHIN        0x8009  // hwnd + ID + idChild is parent of changed selected items
 
    ///*
    // * NOTES:
    // * There is only one "focused" child item in a parent.  This is the place
    // * keystrokes are going at a given moment.  Hence only send a notification
    // * about where the NEW focus is going.  A NEW item getting the focus already
    // * implies that the OLD item is losing it.
    // *
    // * SELECTION however can be multiple.  Hence the different SELECTION
    // * notifications.  Here's when to use each:
    // *
    // * (1) Send a SELECTION notification in the simple single selection
    // *     case (like the focus) when the item with the selection is
    // *     merely moving to a different item within a container.  hwnd + ID
    // *     is the container control, idChildItem is the new child with the
    // *     selection.
    // *
    // * (2) Send a SELECTIONADD notification when a new item has simply been added
    // *     to the selection within a container.  This is appropriate when the
    // *     number of newly selected items is very small.  hwnd + ID is the
    // *     container control, idChildItem is the new child added to the selection.
    // *
    // * (3) Send a SELECTIONREMOVE notification when a new item has simply been
    // *     removed from the selection within a container.  This is appropriate
    // *     when the number of newly selected items is very small, just like
    // *     SELECTIONADD.  hwnd + ID is the container control, idChildItem is the
    // *     new child removed from the selection.
    // *
    // * (4) Send a SELECTIONWITHIN notification when the selected items within a
    // *     control have changed substantially.  Rather than propagate a large
    // *     number of changes to reflect removal for some items, addition of
    // *     others, just tell somebody who cares that a lot happened.  It will
    // *     be faster an easier for somebody watching to just turn around and
    // *     query the container control what the new bunch of selected items
    // *     are.
    // */
 
    //#define EVENT_OBJECT_STATECHANGE            0x800A  // hwnd + ID + idChild is item w/ state change
    ///*
    // * Examples of when to send an EVENT_OBJECT_STATECHANGE include
    // *      * It is being enabled/disabled (USER does for windows)
    // *      * It is being pressed/released (USER does for buttons)
    // *      * It is being checked/unchecked (USER does for radio/check buttons)
    // */
    //#define EVENT_OBJECT_LOCATIONCHANGE         0x800B  // hwnd + ID + idChild is moved/sized item
 
    ///*
    // * Note:
    // * A LOCATIONCHANGE is not sent for every child object when the parent
    // * changes shape/moves.  Send one notification for the topmost object
    // * that is changing.  For example, if the user resizes a top level window,
    // * USER will generate a LOCATIONCHANGE for it, but not for the menu bar,
    // * title bar, scrollbars, etc.  that are also changing shape/moving.
    // *
    // * In other words, it only generates LOCATIONCHANGE notifications for
    // * real windows that are moving/sizing.  It will not generate a LOCATIONCHANGE
    // * for every non-floating child window when the parent moves (the children are
    // * logically moving also on screen, but not relative to the parent).
    // *
    // * Now, if the app itself resizes child windows as a result of being
    // * sized, USER will generate LOCATIONCHANGEs for those dudes also because
    // * it doesn't know better.
    // *
    // * Note also that USER will generate LOCATIONCHANGE notifications for two
    // * non-window sys objects:
    // *      (1) System caret
    // *      (2) Cursor
    // */
 
    //#define EVENT_OBJECT_NAMECHANGE             0x800C  // hwnd + ID + idChild is item w/ name change
    //#define EVENT_OBJECT_DESCRIPTIONCHANGE      0x800D  // hwnd + ID + idChild is item w/ desc change
    //#define EVENT_OBJECT_VALUECHANGE            0x800E  // hwnd + ID + idChild is item w/ value change
    //#define EVENT_OBJECT_PARENTCHANGE           0x800F  // hwnd + ID + idChild is item w/ new parent
    //#define EVENT_OBJECT_HELPCHANGE             0x8010  // hwnd + ID + idChild is item w/ help change
    //#define EVENT_OBJECT_DEFACTIONCHANGE        0x8011  // hwnd + ID + idChild is item w/ def action change
    //#define EVENT_OBJECT_ACCELERATORCHANGE      0x8012  // hwnd + ID + idChild is item w/ keybd accel change
 
    //#if(_WIN32_WINNT >= 0x0600)
    //#define EVENT_OBJECT_INVOKED                0x8013  // hwnd + ID + idChild is item invoked
    //#define EVENT_OBJECT_TEXTSELECTIONCHANGED   0x8014  // hwnd + ID + idChild is item w? test selection change
 
    ///*
    // * EVENT_OBJECT_CONTENTSCROLLED
    // * Sent when ending the scrolling of a window object.
    // *
    // * Unlike the similar event (EVENT_SYSTEM_SCROLLEND), this event will be
    // * associated with the scrolling window itself. There is no difference
    // * between horizontal or vertical scrolling.
    // *
    // * This event should be posted whenever scroll action is completed, including
    // * when it is scrolled by scroll bars, mouse wheel, or keyboard navigations.
    // *
    // *   example:
    // *          hwnd == window that is scrolling
    // *          idObject == OBJID_CLIENT
    // *          idChild == CHILDID_SELF
    // */
    //#define EVENT_OBJECT_CONTENTSCROLLED        0x8015
    //#endif /* _WIN32_WINNT >= 0x0600 */
 
    //#if(_WIN32_WINNT >= 0x0601)
    //#define EVENT_SYSTEM_ARRANGMENTPREVIEW      0x8016
    //#endif /* _WIN32_WINNT >= 0x0601 */
 
    //#if(_WIN32_WINNT >= 0x0602)
 
    ///*
    // * EVENT_OBJECT_CLOAKED / UNCLOAKED
    // * Sent when a window is cloaked or uncloaked.
    // * A cloaked window still exists, but is invisible to
    // * the user.
    // */
    //#define EVENT_OBJECT_CLOAKED                0x8017
    //#define EVENT_OBJECT_UNCLOAKED              0x8018
 
    ///*
    // * EVENT_OBJECT_LIVEREGIONCHANGED
    // * Sent when an object that is part of a live region
    // * changes.  A live region is an area of an application
    // * that changes frequently and/or asynchronously, so
    // * that an assistive technology tool might want to pay
    // * special attention to it.
    // */
    //#define EVENT_OBJECT_LIVEREGIONCHANGED      0x8019
 
    ///*
    // * EVENT_OBJECT_HOSTEDOBJECTSINVALIDATED
    // * Sent when a window that is hosting other Accessible
    // * objects changes the hosted objects.  A client may
    // * wish to requery to see what the new hosted objects are,
    // * especially if it has been monitoring events from this
    // * window.  A hosted object is one with a different Accessibility
    // * framework (MSAA or UI Automation) from its host.
    // *
    // * Changes in hosted objects with the *same* framework
    // * as the parent should be handed with the usual structural
    // * change events, such as EVENT_OBJECT_CREATED for MSAA.
    // * see above.
    // */
    //#define EVENT_OBJECT_HOSTEDOBJECTSINVALIDATED 0x8020
 
    ///*
    // * Drag / Drop Events
    // * These events are used in conjunction with the
    // * UI Automation Drag/Drop patterns.
    // *
    // * For DRAGSTART, DRAGCANCEL, and DRAGCOMPLETE,
    // * HWND+objectID+childID refers to the object being dragged.
    // *
    // * For DRAGENTER, DRAGLEAVE, and DRAGDROPPED,
    // * HWND+objectID+childID refers to the target of the drop
    // * that is being hovered over.
    // */
 
    //#define EVENT_OBJECT_DRAGSTART              0x8021
    //#define EVENT_OBJECT_DRAGCANCEL             0x8022
    //#define EVENT_OBJECT_DRAGCOMPLETE           0x8023
 
    //#define EVENT_OBJECT_DRAGENTER              0x8024
    //#define EVENT_OBJECT_DRAGLEAVE              0x8025
    //#define EVENT_OBJECT_DRAGDROPPED            0x8026
 
    ///*
    // * EVENT_OBJECT_IME_SHOW/HIDE
    // * Sent by an IME window when it has become visible or invisible.
    // */
    //#define EVENT_OBJECT_IME_SHOW               0x8027
    //#define EVENT_OBJECT_IME_HIDE               0x8028
 
    ///*
    // * EVENT_OBJECT_IME_CHANGE
    // * Sent by an IME window whenever it changes size or position.
    // */
    //#define EVENT_OBJECT_IME_CHANGE             0x8029
 
    //#endif /* _WIN32_WINNT >= 0x0602 */
 
    //#if(_WIN32_WINNT >= 0x0601)
    //#define EVENT_OBJECT_END                    0x80FF
 
    //#define EVENT_AIA_START                     0xA000
    //#define EVENT_AIA_END                       0xAFFF
    //#endif /* _WIN32_WINNT >= 0x0601 */
    #endregion
 
    enum EventType : uint
    {
        #region ~ Min/Max ~
        Min = 0x00000001,
        Max = 0x7FFFFFFF,
        #endregion
 
        #region ~ System events ~
        System_Sound = 0x0001,
        System_Alert,
        System_Foreground,
        System_MenuStart,
        System_MenuEnd,
        System_MenuPopupStart,
        System_MenuPopupEnd,
        System_CaptureStart,
        System_CaptureEnd,
        System_MoveSizeStart,
        System_MoveSizeEnd,
        System_ContextHelpStart,
        System_ContextHelpEnd,
        System_DragDropStart,
        System_DragDropEnd,
        System_DialogStart,
        System_DialogEnd,
        System_ScrollingStart,
        System_ScrollingEnd,
        System_SwitchStart,
        System_SwitchEnd,
        System_MinimizeStart,
        System_MinimizeEnd,
        /// <summary>
        /// WinVersion >= 0x0600
        /// </summary>
        System_DesktopSwitch = 0x0020,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        System_Switcher_AppGrabbed = 0x0024,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        System_Switcher_AppOverTarget,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        System_Switcher_AppDropped,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        System_Switcher_Cancelled,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        System_ImeKey_Notification = 0x0029,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        System_End = 0x00FF,
        #endregion
 
        #region ~ OEM events ~
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Oem_Start = 0x0101,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Oem_End = 0x01FF,
        #endregion
 
        #region ~ UI Automation events ~
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Uia_EventId_Start = 0x4E00,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Uia_EventId_End = 0x4EFF,
        #endregion
 
        #region ~ UI Automation property-changed events ~
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Uia_PropId_Start = 0x7500,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Uia_PropId_End = 0x75FF,
        #endregion
 
        #region ~ Console events ~
        /// <summary>
        /// WinVersion >= 0x0501
        /// </summary>
        Console_Caret = 0x4001,
        /// <summary>
        /// WinVersion >= 0x0501
        /// </summary>
        Console_UpdateRegion,
        /// <summary>
        /// WinVersion >= 0x0501
        /// </summary>
        Console_UpdateSimple,
        /// <summary>
        /// WinVersion >= 0x0501
        /// </summary>
        Console_UpdateScroll,
        /// <summary>
        /// WinVersion >= 0x0501
        /// </summary>
        Console_Layout,
        /// <summary>
        /// WinVersion >= 0x0501
        /// </summary>
        Console_StartApplication,
        /// <summary>
        /// WinVersion >= 0x0501
        /// </summary>
        Console_EndApplication,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Console_End = 0x40FF,
        #endregion
 
        #region ~ Object events ~
        Object_Create = 0x8000,
        Object_Destroy,
        Object_Show,
        Object_Hide,
        Object_Reorder,
        Object_Focus,
        Object_Selection,
        Object_SelectionAdd,
        Object_SelectionRemove,
        Object_SelectionWithin,
        Object_StateChange,
        Object_LocationChange,
        Object_NameChange,
        Object_DescriptionChange,
        Object_ValueChange,
        Object_ParentChange,
        Object_HelpChange,
        Object_DefActionChange,
        Object_AcceleratorChange,
        /// <summary>
        /// WinVersion >= 0x0600
        /// </summary>
        Object_Invoked,
        /// <summary>
        /// WinVersion >= 0x0600
        /// </summary>
        Object_TextSelectionChanged,
        /// <summary>
        /// WinVersion >= 0x0600
        /// </summary>
        Object_ContentScrolled,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Object_System_ArrangmentPreview,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_Cloaked,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_Uncloked,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_LiveRegionChanged,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_HostedObjectsInvalidated = 0x8020,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_DragStart,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_DragCancel,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_DragComplete,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_DragEnter,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_DragLeave,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_DragDropped,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_Ime_Show,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_Ime_Hide,
        /// <summary>
        /// WinVersion >= 0x0602
        /// </summary>
        Object_Ime_Change,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Object_End = 0x80FF,
        #endregion
 
        #region ~ Accessibility Interoperability Alliance (AIA) events ~
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Aia_Start = 0xA000,
        /// <summary>
        /// WinVersion >= 0x0601
        /// </summary>
        Aia_End = 0xAFFF,
        #endregion
    }
}
WinEvent.cs
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using pinvoke;
 
namespace WindowsEvents
{
    class WinEvent : IDisposable
    {
        public delegate void EventData (
            int pid,
            int tid,
            uint dwEvent,
            IntPtr hWnd,
            int idObject,
            int idChild,
            uint dwEventThread,
            uint dwmsEventTime
            );
 
        public event EventData EventReceived;
 
        [MarshalAs( UnmanagedType.FunctionPtr )]
        User32.WINEVENTPROC winEventProc;
        IntPtr              hWinEvent;
        int                 pid;
        int                 tid;
        EventType           minEventType;
        EventType           maxEventType;
 
        public WinEvent ( )
            : this( 0, 0, EventType.Min, EventType.Max ) { }
 
        public WinEvent ( EventType min, EventType max )
            : this( 0, 0, min, max ) { }
 
        public WinEvent ( int pid, EventType min, EventType max )
            : this( pid, 0, min, max ) { }
 
        public WinEvent ( int pid, int tid, EventType min, EventType max )
        {
            ProcessId = pid;
            ThreadId = tid;
            MaxEventType = max;
            MinEventType = min;
 
            winEventProc = EventProc;
        }
 
        public int ProcessId
        {
            get { return pid; }
            set
            {
                if ( hWinEvent != IntPtr.Zero )
                    throw new InvalidOperationException(
                        "Can't change PID: Event started!"
                        );
                if ( value < 0 )
                    throw new ArgumentException(
                        "Can't change PID: value can't be less than zero!"
                        );
 
                pid = value;
            }
        }
 
        public int ThreadId
        {
            get { return tid; }
            set
            {
                if ( hWinEvent != IntPtr.Zero )
                    throw new InvalidOperationException(
                        "Can't change TID: Event started!"
                        );
                if ( value < 0 )
                    throw new ArgumentException(
                        "Can't change TID: value can't be less than zero!"
                        );
 
                tid = value;
            }
        }
 
        public EventType MinEventType
        {
            get { return minEventType; }
            set
            {
                if ( hWinEvent != IntPtr.Zero )
                    throw new InvalidOperationException(
                        "Can't change min event type: Event started!"
                        );
                if ( value > maxEventType )
                    throw new ArgumentException(
                        "Can't change min event type: value can't be more than 'max event type' value!"
                        );
 
                minEventType = value;
            }
        }
 
        public EventType MaxEventType
        {
            get { return minEventType; }
            set
            {
                if ( hWinEvent != IntPtr.Zero )
                    throw new InvalidOperationException(
                        "Can't change max event type: Event started!"
                        );
                if ( value < minEventType )
                    throw new ArgumentException(
                        "Can't change max event type: value can't be less than 'min event type' value!"
                        );
 
                maxEventType = value;
            }
        }
 
        public bool IsRunning
        {
            get
            {
                return hWinEvent != IntPtr.Zero;
            }
        }
 
        public void Run ( )
        {
            Run( minEventType, maxEventType );
        }
 
        public void Run ( EventType min, EventType max )
        {
            if ( winEventProc == null )
                throw new ObjectDisposedException( "WinEvent" );
            if ( hWinEvent != IntPtr.Zero )
                throw new InvalidOperationException(
                    "Can't start event hook: hook already run!"
                    );
 
            MaxEventType = max;
            MinEventType = min;
 
            hWinEvent = User32.SetWinEventHook(
                            (uint)min, (uint)max, IntPtr.Zero,
                            winEventProc, pid, tid,
                            User32.WINEVENT_OUTOFCONTEXT
                            );
 
            if ( hWinEvent == IntPtr.Zero )
                throw new Win32Exception( Marshal.GetLastWin32Error() );
        }
 
        public void Stop ( )
        {
            if ( winEventProc == null )
                throw new ObjectDisposedException( "WinEvent" );
            if ( hWinEvent == IntPtr.Zero )
                throw new InvalidOperationException(
                    "Can't stop event hook: hook not running!"
                    );
 
            if ( !User32.UnhookWinEvent( hWinEvent ) )
                throw new Win32Exception( Marshal.GetLastWin32Error() );
 
            hWinEvent = IntPtr.Zero;
        }
 
        public void Dispose ( )
        {
            if ( winEventProc != null )
            {
                if ( IsRunning )
                    Stop();
                winEventProc = null;
            }
        }
 
        void EventProc (
            IntPtr hWinEventHook,
            uint dwEvent,
            IntPtr hWnd,
            int idObject,
            int idChild,
            uint dwEventThread,
            uint dwmsEventTime
            )
        {
            OnEventReceived(
                dwEvent, hWnd, idObject, idChild,
                dwEventThread, dwmsEventTime
                );
        }
 
        void OnEventReceived (
            uint dwEvent,
            IntPtr hWnd,
            int idObject,
            int idChild,
            uint dwEventThread,
            uint dwmsEventTime
            )
        {
            Debug.WriteLine( dwEvent, "EventID" );
            if ( EventReceived != null )
                EventReceived(
                    pid, tid,
                    dwEvent, hWnd, idObject, idChild,
                    dwEventThread, dwmsEventTime
                    );
        }
    }
}

Использование:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using WindowsEvents;
// ...
 
        WinEvent[] winEvents;
 
        public Form1 ( )
        {
            InitializeComponent();
 
            this.FormClosed += ( s, e ) => {
                winEvents[0].Dispose();
                winEvents[1].Dispose();
            };
 
            winEvents = new WinEvent[] {
                // PIDs can be taken from Process.Id property
                new WinEvent( 6128, EventType.System_Sound, EventType.System_End ),
                new WinEvent( 5512, EventType.System_Sound, EventType.System_End )
            };
 
            winEvents[0].EventReceived += winEvent_EventReceived;
            winEvents[1].EventReceived += winEvent_EventReceived;
            winEvents[0].Run();
            winEvents[1].Run();
        }
 
        void winEvent_EventReceived ( int pid, int tid, uint dwEvent, IntPtr hWnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime )
        {
            Debug.WriteLine( pid + " | " + tid );
        }
  • Если pid и tid >= 0, т.е. оба установлены, тогда будет поставлен хук на определенный поток определенного процесса;
  • Если pid > 0, а tid == 0, тогда хук устанавливается на все потоки определенного процесса;
  • Если pid и tid == 0, тогда устанавливается глобальный хук.
3
 Аватар для desys
-7 / 12 / 1
Регистрация: 01.09.2012
Сообщений: 60
15.09.2012, 22:06  [ТС]
SSTREGG, Благодарю за все, но не могли бы просветить как мне это связать с процессом "notepad", pid и tid к сожалению не за шарил еще...

________________________________________ ________________________________________ ______
Буду молить Бога поделиться с вами исходниками...
0
Почетный модератор
Эксперт .NET
 Аватар для NickoTin
8729 / 3681 / 404
Регистрация: 14.06.2010
Сообщений: 4,513
Записей в блоге: 9
15.09.2012, 22:34
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Diagnostics;
using System.Windows.Forms;
using WindowsEvents;
 
namespace WindowsFormsApplication10
{
    public partial class Form1 : Form
    {
        WinEvent notepadEvent;
 
        public Form1 ( )
        {
            InitializeComponent();
            notepadEvent = new WinEvent(
                // All System events
                EventType.Min, EventType.System_End
                );
            notepadEvent.EventReceived += notepadEvent_EventReceived;
        }
 
        void notepadEvent_EventReceived ( int pid, int tid, uint dwEvent, IntPtr hWnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime )
        {
            Debug.WriteLine(
                string.Format(
                    "~ Event #{2} ~\r\nPID: {0} TID: {1}\r\nHWND: {3}\r\n\tidObject: {4}, idChild: {5}\r\nEvent TID: {6}\r\nEvent time: {7}\r\n",
                    pid, tid, dwEvent, hWnd, idObject,
                    idChild, dwEventThread, dwmsEventTime
                    )
                );
        }
 
        private void button1_Click ( object sender, EventArgs e )
        {
            // Run event hook
            if ( notepadEvent.IsRunning )
            {
                MessageBox.Show( "Hook alredy running!" );
                return;
            }
 
            var procs = Process.GetProcessesByName( "notepad" );
 
            if ( procs.Length == 0 )
            {
                MessageBox.Show( "There are no processes with name 'notepad'!" );
                return;
            }
 
            notepadEvent.ProcessId = procs[0].Id;
            notepadEvent.Run();
        }
 
        private void button2_Click ( object sender, EventArgs e )
        {
            // Stop event hook
            if ( !notepadEvent.IsRunning )
            {
                MessageBox.Show( "Hook not running yet!" );
                return;
            }
 
            notepadEvent.Stop();
        }
    }
}
2
 Аватар для desys
-7 / 12 / 1
Регистрация: 01.09.2012
Сообщений: 60
16.09.2012, 20:39  [ТС]
SSTREGG, Еще раз спасибо , но тема все же для того что бы разобраться с моим кодом...
Ваш код все же не стал разшаривать...

Вот кому если надо, то я это в класс засунул + логирование...
process_win.cs
Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
 
 
class process_win
{
 
    log process_log = new log();
 
    bool installed;
    IntPtr hWinEventhook;
 
    [DllImport("user32.dll")]
    private static extern int SetForegroundWindow(IntPtr hWnd);
    private const int SW_SHOWNORMAL = 1;
    private const int SW_SHOWMAXIMIZED = 3;
    private const int SW_RESTORE = 9;
 
    [DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
 
 
    public process_win()
    {}
 
    public string NameProc = "";
 
    public void process_win_string(string msg, string param)
    {
        NameProc = param;
        var processes = Process.GetProcessesByName(msg);
 
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = msg;
        proc.EnableRaisingEvents = true;
//        proc.SynchronizingObject = this;
 
        proc.Exited += new EventHandler(closeHandlerProcess);
 
        Wait(msg);
 
        if (processes.Any())
        {
            var handle = processes.First().MainWindowHandle;
            ShowWindow(handle, SW_RESTORE);
            SetForegroundWindow(handle);
            process_log.write("Разворачиваю " + param);
        }
 
        else
        {
            proc.Start();
            process_log.write("Запускаю "+param);
 
        }
 
 
        if (installed && pinvoke.User32.UnhookWinEvent(hWinEventhook))
            installed = false;
        else if (!installed)
        {
            var procs = Process.GetProcessesByName(msg);
 
            if (procs.Length > 0)
                hWinEventhook = pinvoke.User32.SetWinEventHook(pinvoke.User32.EVENT_SYSTEM_MINIMIZESTART, pinvoke.User32.EVENT_SYSTEM_MINIMIZEEND, IntPtr.Zero, WinEventProc, procs[0].Id, 0, pinvoke.User32.WINEVENT_OUTOFCONTEXT);
 
            if (hWinEventhook != IntPtr.Zero)
                installed = true;
            else { }//MessageBox.Show("Can't install winevent hook, err " +Marshal.GetLastWin32Error());
        }
 
 
    }
 
    void WinEventProc(IntPtr hWinEventHook, uint dwEvent, IntPtr hWnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        Debug.WriteLine(string.Format("Event: {0}\r\n\tHWND: 0x{1:X8}\r\n\tidObject: {2}\r\n\tidChild: {3}\r\n\tdwEventThread: 0x{4:X8}\r\n\tTime: {5}\r\n", dwEvent, hWnd, idObject, idChild, dwEventThread, dwmsEventTime));
 
        switch (dwEvent)
        {
            case pinvoke.User32.EVENT_SYSTEM_MINIMIZEEND:
                process_log.write("Разворачиваю " + NameProc);
                break;
            case pinvoke.User32.EVENT_SYSTEM_MINIMIZESTART:
                process_log.write("Сворачиваю " + NameProc);
                break;
        }
    }
 
    private static void Wait(string msg)
    {
        Process myProcess = Process.GetProcessesByName(msg).FirstOrDefault();
        if (myProcess != null)
        {
            myProcess.EnableRaisingEvents = true;
            myProcess.Exited += (sender, e) =>
            {
 
            };
        }
    }
 
    private void closeHandlerProcess(object sender, EventArgs e)
    {
        process_log.write("Закрываю " + NameProc);
    }
 
}

log.cs
Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
 
 
 
class log
   {
      //конструктор
      public log ()
      {
      }
      public void write (string msg)
      {
         DateTime currtime = DateTime.Now;
        string logtxt = String.Format("{0:MM.yy}", currtime);
         using (System.IO.StreamWriter file = new System.IO.StreamWriter(@logtxt+"_LOG1.log", true))
 
        
         {
            string tmptxt = String.Format("{0:dd/MM/yy - HH:mm:ss} {1}", currtime, msg);
            file.WriteLine(tmptxt);
            file.Close();
         }
      }
   }
C#
1
 
Form
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
 
 
        process_win win_process = new process_win();
 
 
        private void btnParagraph_Click(object sender, EventArgs e)
        {
             win_process.process_win_string("SIPClient.exe", "Телефон");
       }





Код не стабилен, так что тема активна, кто доделает тому +1000
1
 Аватар для desys
-7 / 12 / 1
Регистрация: 01.09.2012
Сообщений: 60
26.09.2012, 16:02  [ТС]
никому не интересно...
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
26.09.2012, 16:02
Помогаю со студенческими работами здесь

Не получается проанализировать код и исправить ошибки
&lt;html&gt; &lt;head&gt; &lt;title&gt; var1 &lt;/title&gt; &lt;/head&gt; &lt;body bgcolor = white&gt; &lt;div id = rt style = &quot;background: black; width:...

Ссылки на объекты. исправить ошибки (код готов)
Задание было такое: создать приложение для работы с пользовательским строковым классом. Грубо говоря, создать мини-текстовый редактор :D ...

Записать элементы в стек - исправить ошибки в код
Год не работал на C#. Привык к гибким php и js. И вот начал писать маленькую программу - сразу появилась куча непонятных ошибок. Мозг уже...

Найти ошибки в определении функции поиска (исправить код)
#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; struct Cours { string surname; string coursname; ...

Проанализировать представленный код, исправить логические и синтаксические ошибки
Определить, какая задача стоит перед программистом. programm 2C; Var a:array of integer; i,k, n:integer; Begin read(n); For...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
Оттенки серого
Argus19 18.03.2026
Оттенки серого Нашёл в интернете 3 прекрасных модуля: Модуль класса открытия диалога открытия/ сохранения файла на Win32 API; Модуль класса быстрого перекодирования цветного изображения в оттенки. . .
SDL3 для Desktop (MinGW): Рисуем цветные прямоугольники с помощью рисовальщика SDL3 на Си и C++
8Observer8 17.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-rectangles-sdl3-c. zip finish-rectangles-sdl3-cpp. zip
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая ссылка» (hard link),. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru