source: branches/eraser6/Util/KernelAPI.cs @ 612

Revision 612, 31.7 KB checked in by lowjoel, 6 years ago (diff)

Allow Eraser to run as a command line application (create our own console window). Define three actions: addtask, help and querymethods. Currently, help text and parameter parsing is implemented.

  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 * Copyright 2008 The Eraser Project
4 * Original Author: Joel Low <lowjoel@users.sourceforge.net>
5 * Modified By: Garrett Trant <gtrant@users.sourceforge.net>
6 *
7 * This file is part of Eraser.
8 *
9 * Eraser is free software: you can redistribute it and/or modify it under the
10 * terms of the GNU General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option) any later
12 * version.
13 *
14 * Eraser is distributed in the hope that it will be useful, but WITHOUT ANY
15 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 *
18 * A copy of the GNU General Public License can be found at
19 * <http://www.gnu.org/licenses/>.
20 */
21
22using System;
23using System.Collections.Generic;
24using System.Text;
25using System.Reflection;
26using System.Runtime.InteropServices;
27using Microsoft.Win32.SafeHandles;
28
29namespace Eraser.Util
30{
31    public static class KernelAPI
32    {
33        /// <summary>
34        /// Closes an open object handle.
35        /// </summary>
36        /// <param name="hObject">A valid handle to an open object.</param>
37        /// <returns>If the function succeeds, the return value is true. To get
38        /// extended error information, call Marshal.GetLastWin32Error().
39        ///
40        /// If the application is running under a debugger, the function will throw
41        /// an exception if it receives either a handle value that is not valid
42        /// or a pseudo-handle value. This can happen if you close a handle twice,
43        /// or if you call CloseHandle on a handle returned by the FindFirstFile
44        /// function.</returns>
45        [DllImport("Kernel32.dll", SetLastError = true)]
46        [return: MarshalAs(UnmanagedType.Bool)]
47        public static extern bool CloseHandle(IntPtr hObject);
48
49        /// <summary>
50        /// Retrieves a pseudo handle for the current process.
51        /// </summary>
52        /// <returns>A pseudo handle to the current process.</returns>
53        /// <remarks>A pseudo handle is a special constant, currently (HANDLE)-1,
54        /// that is interpreted as the current process handle. For compatibility
55        /// with future operating systems, it is best to call GetCurrentProcess
56        /// instead of hard-coding this constant value. The calling process can
57        /// use a pseudo handle to specify its own process whenever a process
58        /// handle is required. Pseudo handles are not inherited by child processes.
59        ///
60        /// This handle has the maximum possible access to the process object.
61        /// For systems that support security descriptors, this is the maximum
62        /// access allowed by the security descriptor for the calling process.
63        /// For systems that do not support security descriptors, this is
64        /// PROCESS_ALL_ACCESS. For more information, see Process Security and
65        /// Access Rights.
66        ///
67        /// A process can create a "real" handle to itself that is valid in the
68        /// context of other processes, or that can be inherited by other processes,
69        /// by specifying the pseudo handle as the source handle in a call to the
70        /// DuplicateHandle function. A process can also use the OpenProcess
71        /// function to open a real handle to itself.
72        ///
73        /// The pseudo handle need not be closed when it is no longer needed.
74        /// Calling the CloseHandle function with a pseudo handle has no effect.
75        /// If the pseudo handle is duplicated by DuplicateHandle, the duplicate
76        /// handle must be closed.</remarks>
77        [DllImport("Kernel32.dll", SetLastError = true)]
78        public static extern IntPtr GetCurrentProcess();
79
80        /// <summary>
81        /// Retrieves the process identifier of the calling process.
82        /// </summary>
83        /// <returns>The return value is the process identifier of the calling
84        /// process.</returns>
85        [DllImport("Kernel32.dll")]
86        public static extern uint GetCurrentProcessId();
87
88        /// <summary>
89        /// Retrieves a pseudo handle for the calling thread.
90        /// </summary>
91        /// <returns>The return value is a pseudo handle for the current thread.</returns>
92        [DllImport("Kernel32.dll", SetLastError = true)]
93        public static extern IntPtr GetCurrentThread();
94
95        /// <summary>
96        /// Retrieves the thread identifier of the calling thread.
97        /// </summary>
98        /// <returns>The return value is the thread identifier of the calling
99        /// thread.</returns>
100        [DllImport("Kernel32.dll")]
101        public static extern uint GetCurrentThreadId();
102
103        /// <summary>
104        /// Retrieves a handle to the heap of the calling process. This handle
105        /// can then be used in subsequent calls to the heap functions.
106        /// </summary>
107        /// <returns>If the function succeeds, the return value is a handle to
108        /// the calling process's heap.
109        ///
110        /// If the function fails, the return value is NULL. To get extended error
111        /// information, call Marshal.GetLastWin32Error.</returns>
112        [DllImport("Kernel32.dll", SetLastError = true)]
113        public static extern IntPtr GetProcessHeap();
114
115        /// <summary>
116        /// Retrieves timing information for the specified process.
117        /// </summary>
118        /// <param name="hThread">A handle to the process whose timing information
119        /// is sought. This handle must have the PROCESS_QUERY_INFORMATION access
120        /// right. For more information, see Thread Security and Access Rights.</param>
121        /// <param name="lpCreationTime">A reference to a long that receives the
122        /// creation time of the thread.</param>
123        /// <param name="lpExitTime">A reference to a long that receives the exit time
124        /// of the thread. If the thread has not exited, the value of field is
125        /// undefined.</param>
126        /// <param name="lpKernelTime">A reference to a long that receives the
127        /// amount of time that the thread has executed in kernel mode.</param>
128        /// <param name="lpUserTime">A reference to a long that receives the amount
129        /// of time that the thread has executed in user mode.</param>
130        /// <returns>If the function succeeds, the return value is nonzero.
131        ///
132        /// If the function fails, the return value is zero. To get extended error
133        /// information, call Marshal.GetLastWin32Error.</returns>
134        [DllImport("Kernel32.dll", SetLastError = true)]
135        [return: MarshalAs(UnmanagedType.Bool)]
136        public static extern bool GetProcessTimes(IntPtr hThread, out long lpCreationTime,
137           out long lpExitTime, out long lpKernelTime, out long lpUserTime);
138
139        /// <summary>
140        /// Retrieves the contents of the STARTUPINFO structure that was specified
141        /// when the calling process was created.
142        /// </summary>
143        /// <param name="lpStartupInfo">A pointer to a STARTUPINFO structure that
144        /// receives the startup information.</param>
145        [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
146        public static extern void GetStartupInfo(out STARTUPINFO lpStartupInfo);
147
148        /// <summary>
149        /// Retrieves information about the current system.
150        /// </summary>
151        /// <param name="lpSystemInfo">A pointer to a SYSTEM_INFO structure that
152        /// receives the information.</param>
153        [DllImport("Kernel32.dll")]
154        public static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
155
156        /// <summary>
157        /// Retrieves timing information for the specified thread.
158        /// </summary>
159        /// <param name="hThread">A handle to the thread whose timing information
160        /// is sought. This handle must have the THREAD_QUERY_INFORMATION access
161        /// right. For more information, see Thread Security and Access Rights.</param>
162        /// <param name="lpCreationTime">A reference to a long that receives the
163        /// creation time of the thread.</param>
164        /// <param name="lpExitTime">A reference to a long that receives the exit time
165        /// of the thread. If the thread has not exited, the value of field is
166        /// undefined.</param>
167        /// <param name="lpKernelTime">A reference to a long that receives the
168        /// amount of time that the thread has executed in kernel mode.</param>
169        /// <param name="lpUserTime">A reference to a long that receives the amount
170        /// of time that the thread has executed in user mode.</param>
171        /// <returns>If the function succeeds, the return value is nonzero.
172        ///
173        /// If the function fails, the return value is zero. To get extended error
174        /// information, call Marshal.GetLastWin32Error.</returns>
175        [DllImport("Kernel32.dll", SetLastError = true)]
176        [return: MarshalAs(UnmanagedType.Bool)]
177        public static extern bool GetThreadTimes(IntPtr hThread, out long lpCreationTime,
178           out long lpExitTime, out long lpKernelTime, out long lpUserTime);
179
180        /// <summary>
181        /// Retrieves the number of milliseconds that have elapsed since the system
182        /// was started, up to 49.7 days.
183        /// </summary>
184        /// <returns>The return value is the number of milliseconds that have elapsed
185        /// since the system was started.</returns>
186        /// <remarks>The resolution is limited to the resolution of the system timer.
187        /// This value is also affected by adjustments made by the GetSystemTimeAdjustment
188        /// function.
189        ///
190        /// The elapsed time is stored as a DWORD value. Therefore, the time will
191        /// wrap around to zero if the system is run continuously for 49.7 days.
192        /// To avoid this problem, use GetTickCount64. Otherwise, check for an
193        /// overflow condition when comparing times.
194        ///
195        /// If you need a higher resolution timer, use a multimedia timer or a
196        /// high-resolution timer.
197        ///
198        /// To obtain the time elapsed since the computer was started, retrieve
199        /// the System Up Time counter in the performance data in the registry key
200        /// HKEY_PERFORMANCE_DATA. The value returned is an 8-byte value. For more
201        /// information, see Performance Counters.</remarks>
202        [DllImport("Kernel32.dll")]
203        public static extern uint GetTickCount();
204
205        /// <summary>
206        /// Retrieves information about the system's current usage of both physical
207        /// and virtual memory.
208        /// </summary>
209        /// <param name="lpBuffer">A pointer to a MEMORYSTATUSEX structure that
210        /// receives information about current memory availability.</param>
211        /// <returns>If the function succeeds, the return value is nonzero.
212        /// If the function fails, the return value is zero. To get extended
213        /// error information, call Marshal.GetLastWin32Error.</returns>
214        [DllImport("Kernel32.dll", SetLastError = true)]
215        [return: MarshalAs(UnmanagedType.Bool)]
216        public static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
217
218        /// <summary>
219        /// The QueryPerformanceCounter function retrieves the current value of
220        /// the high-resolution performance counter.
221        /// </summary>
222        /// <param name="lpPerformanceCount">[out] Pointer to a variable that receives
223        /// the current performance-counter value, in counts.</param>
224        /// <returns>If the function succeeds, the return value is nonzero.
225        ///
226        /// If the function fails, the return value is zero. To get extended error
227        /// information, call Marshal.GetLastWin32Error. </returns>
228        [DllImport("Kernel32.dll", SetLastError = true)]
229        [return: MarshalAs(UnmanagedType.Bool)]
230        public static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
231
232        /// <summary>
233        /// Contains information about the current state of both physical and
234        /// virtual memory, including extended memory. The GlobalMemoryStatusEx
235        /// function stores information in this structure.
236        /// </summary>
237        [StructLayout(LayoutKind.Sequential)]
238        public struct MEMORYSTATUSEX
239        {
240            /// <summary>
241            /// The size of the structure, in bytes. You must set this member
242            /// before calling GlobalMemoryStatusEx.
243            /// </summary>
244            public uint dwLength;
245
246            /// <summary>
247            /// A number between 0 and 100 that specifies the approximate percentage
248            /// of physical memory that is in use (0 indicates no memory use and
249            /// 100 indicates full memory use).
250            /// </summary>
251            public uint dwMemoryLoad;
252
253            /// <summary>
254            /// The amount of actual physical memory, in bytes.
255            /// </summary>
256            public ulong ullTotalPhys;
257
258            /// <summary>
259            /// The amount of physical memory currently available, in bytes. This
260            /// is the amount of physical memory that can be immediately reused
261            /// without having to write its contents to disk first. It is the sum
262            /// of the size of the standby, free, and zero lists.
263            /// </summary>
264            public ulong ullAvailPhys;
265
266            /// <summary>
267            /// The current committed memory limit for the system or the current
268            /// process, whichever is smaller, in bytes. To get the system-wide
269            /// committed memory limit, call GetPerformanceInfo.
270            /// </summary>
271            public ulong ullTotalPageFile;
272
273            /// <summary>
274            /// The maximum amount of memory the current process can commit, in
275            /// bytes. This value is equal to or smaller than the system-wide
276            /// available commit value. To calculate the system-wide available
277            /// commit value, call GetPerformanceInfo and subtract the value of
278            /// CommitTotal from the value of CommitLimit.
279            /// </summary>
280            public ulong ullAvailPageFile;
281
282            /// <summary>
283            /// The size of the user-mode portion of the virtual address space of
284            /// the calling process, in bytes. This value depends on the type of
285            /// process, the type of processor, and the configuration of the
286            /// operating system. For example, this value is approximately 2 GB
287            /// for most 32-bit processes on an x86 processor and approximately
288            /// 3 GB for 32-bit processes that are large address aware running on
289            /// a system with 4-gigabyte tuning enabled.
290            /// </summary>
291            public ulong ullTotalVirtual;
292
293            /// <summary>
294            /// The amount of unreserved and uncommitted memory currently in the
295            /// user-mode portion of the virtual address space of the calling
296            /// process, in bytes.
297            /// </summary>
298            public ulong ullAvailVirtual;
299
300            /// <summary>
301            /// Reserved. This value is always 0.
302            /// </summary>
303            private ulong ullAvailExtendedVirtual;
304        }
305
306        /// <summary>
307        /// Contains information about the current computer system. This includes
308        /// the architecture and type of the processor, the number of processors
309        /// in the system, the page size, and other such information.
310        /// </summary>
311        [StructLayout(LayoutKind.Sequential)]
312        public struct SYSTEM_INFO
313        {
314            /// <summary>
315            /// Represents a list of processor architectures.
316            /// </summary>
317            public enum ProcessorArchitecture : ushort
318            {
319                /// <summary>
320                /// x64 (AMD or Intel).
321                /// </summary>
322                PROCESSOR_ARCHITECTURE_AMD64 = 9,
323
324                /// <summary>
325                /// Intel Itanium Processor Family (IPF).
326                /// </summary>
327                PROCESSOR_ARCHITECTURE_IA64 = 6,
328
329                /// <summary>
330                /// x86.
331                /// </summary>
332                PROCESSOR_ARCHITECTURE_INTEL = 0,
333
334                /// <summary>
335                /// Unknown architecture.
336                /// </summary>
337                PROCESSOR_ARCHITECTURE_UNKNOWN = 0xffff
338            }
339
340            /// <summary>
341            /// The processor architecture of the installed operating system.
342            /// This member can be one of the ProcessorArchitecture values.
343            /// </summary>
344            public ProcessorArchitecture processorArchitecture;
345
346            /// <summary>
347            /// This member is reserved for future use.
348            /// </summary>
349            private const ushort reserved = 0;
350
351            /// <summary>
352            /// The page size and the granularity of page protection and commitment.
353            /// This is the page size used by the VirtualAlloc function.
354            /// </summary>
355            public uint pageSize;
356
357            /// <summary>
358            /// A pointer to the lowest memory address accessible to applications
359            /// and dynamic-link libraries (DLLs).
360            /// </summary>
361            public IntPtr minimumApplicationAddress;
362
363            /// <summary>
364            /// A pointer to the highest memory address accessible to applications
365            /// and DLLs.
366            /// </summary>
367            public IntPtr maximumApplicationAddress;
368
369            /// <summary>
370            /// A mask representing the set of processors configured into the system.
371            /// Bit 0 is processor 0; bit 31 is processor 31.
372            /// </summary>
373            public IntPtr activeProcessorMask;
374
375            /// <summary>
376            /// The number of processors in the system.
377            /// </summary>
378            public uint numberOfProcessors;
379
380            /// <summary>
381            /// An obsolete member that is retained for compatibility. Use the
382            /// wProcessorArchitecture, wProcessorLevel, and wProcessorRevision
383            /// members to determine the type of processor.
384            /// Name                        Value
385            /// PROCESSOR_INTEL_386         386
386            /// PROCESSOR_INTEL_486         486
387            /// PROCESSOR_INTEL_PENTIUM     586
388            /// PROCESSOR_INTEL_IA64        2200
389            /// PROCESSOR_AMD_X8664         8664
390            /// </summary>
391            public uint processorType;
392
393            /// <summary>
394            /// The granularity for the starting address at which virtual memory
395            /// can be allocated. For more information, see VirtualAlloc.
396            /// </summary>
397            public uint allocationGranularity;
398
399            /// <summary>
400            /// The architecture-dependent processor level. It should be used only
401            /// for display purposes. To determine the feature set of a processor,
402            /// use the IsProcessorFeaturePresent function.
403            ///
404            /// If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_INTEL, wProcessorLevel
405            /// is defined by the CPU vendor.
406            /// If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_IA64, wProcessorLevel
407            /// is set to 1.
408            /// </summary>
409            public ushort processorLevel;
410
411            /// <summary>
412            /// The architecture-dependent processor revision. The following table
413            /// shows how the revision value is assembled for each type of
414            /// processor architecture.
415            ///
416            /// Processor                   Value
417            /// Intel Pentium, Cyrix        The high byte is the model and the
418            /// or NextGen 586              low byte is the stepping. For example,
419            ///                             if the value is xxyy, the model number
420            ///                             and stepping can be displayed as follows:
421            ///                             Model xx, Stepping yy
422            /// Intel 80386 or 80486        A value of the form xxyz.
423            ///                             If xx is equal to 0xFF, y - 0xA is the model
424            ///                             number, and z is the stepping identifier.
425            ///
426            ///                             If xx is not equal to 0xFF, xx + 'A'
427            ///                             is the stepping letter and yz is the minor stepping.
428            /// </summary>
429            public ushort processorRevision;
430        }
431
432        /// <summary>
433        /// Specifies the window station, desktop, standard handles, and appearance
434        /// of the main window for a process at creation time.
435        /// </summary>
436        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
437        public struct STARTUPINFO
438        {
439            /// <summary>
440            /// The size of the structure, in bytes.
441            /// </summary>
442            private uint cb;
443
444            /// <summary>
445            /// Reserved; must be NULL.
446            /// </summary>
447            private readonly IntPtr lpReserved;
448
449            /// <summary>
450            /// The name of the desktop, or the name of both the desktop and window
451            /// station for this process. A backslash in the string indicates that
452            /// the string includes both the desktop and window station names.
453            /// For more information, see Thread Connection to a Desktop.
454            /// </summary>
455            public string lpDesktop;
456
457            /// <summary>
458            /// For console processes, this is the title displayed in the title
459            /// bar if a new console window is created. If NULL, the name of the
460            /// executable file is used as the window title instead. This parameter
461            /// must be NULL for GUI or console processes that do not create a
462            /// new console window.
463            /// </summary>
464            public string lpTitle;
465
466            /// <summary>
467            /// If dwFlags specifies STARTF_USEPOSITION, this member is the x
468            /// offset of the upper left corner of a window if a new window is
469            /// created, in pixels. Otherwise, this member is ignored.
470            ///
471            /// The offset is from the upper left corner of the screen. For GUI
472            /// processes, the specified position is used the first time the
473            /// new process calls CreateWindow to create an overlapped window
474            /// if the x parameter of CreateWindow is CW_USEDEFAULT.
475            /// </summary>
476            public int dwX;
477
478            /// <summary>
479            /// If dwFlags specifies STARTF_USEPOSITION, this member is the y
480            /// offset of the upper left corner of a window if a new window is
481            /// created, in pixels. Otherwise, this member is ignored.
482            ///
483            /// The offset is from the upper left corner of the screen. For GUI
484            /// processes, the specified position is used the first time the new
485            /// process calls CreateWindow to create an overlapped window if the
486            /// y parameter of CreateWindow is CW_USEDEFAULT.
487            /// </summary>
488            public int dwY;
489
490            /// <summary>
491            /// If dwFlags specifies STARTF_USESIZE, this member is the width of
492            /// the window if a new window is created, in pixels. Otherwise,
493            /// this member is ignored.
494            ///
495            /// For GUI processes, this is used only the first time the new process
496            /// calls CreateWindow to create an overlapped window if the nWidth
497            /// parameter of CreateWindow is CW_USEDEFAULT.
498            /// </summary>
499            public int dwXSize;
500
501            /// <summary>
502            /// If dwFlags specifies STARTF_USESIZE, this member is the height of
503            /// the window if a new window is created, in pixels. Otherwise, this
504            /// member is ignored.
505            ///
506            /// For GUI processes, this is used only the first time the new process
507            /// calls CreateWindow to create an overlapped window if the nHeight
508            /// parameter of CreateWindow is CW_USEDEFAULT.
509            /// </summary>
510            public int dwYSize;
511
512            /// <summary>
513            /// If dwFlags specifies STARTF_USECOUNTCHARS, if a new console window
514            /// is created in a console process, this member specifies the screen
515            /// buffer width, in character columns. Otherwise, this member is ignored.
516            /// </summary>
517            public int dwXCountChars;
518
519            /// <summary>
520            /// If dwFlags specifies STARTF_USECOUNTCHARS, if a new console window
521            /// is created in a console process, this member specifies the screen
522            /// buffer height, in character rows. Otherwise, this member is ignored.
523            /// </summary>
524            public int dwYCountChars;
525
526            /// <summary>
527            /// If dwFlags specifies STARTF_USEFILLATTRIBUTE, this member is the
528            /// initial text and background colors if a new console window is
529            /// created in a console application. Otherwise, this member is ignored.
530            ///
531            /// This value can be any combination of the following values:
532            /// FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY,
533            /// BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY.
534            ///
535            /// For example, the following combination of values produces red text
536            /// on a white background:
537            ///     FOREGROUND_RED| BACKGROUND_RED| BACKGROUND_GREEN| BACKGROUND_BLUE
538            /// </summary>
539            public int dwFillAttribute;
540
541            /// <summary>
542            /// A bit field that determines whether certain STARTUPINFO members
543            /// are used when the process creates a window.
544            /// </summary>
545            public int dwFlags;
546
547            /// <summary>
548            /// If dwFlags specifies STARTF_USESHOWWINDOW, this member can be any
549            /// of the SW_ constants defined in Winuser.h. Otherwise, this member is ignored.
550            ///
551            /// For GUI processes, wShowWindow specifies the default value the
552            /// first time ShowWindow is called. The nCmdShow parameter of ShowWindow
553            /// is ignored. In subsequent calls to ShowWindow, the wShowWindow member
554            /// is used if the nCmdShow parameter of ShowWindow is set to SW_SHOWDEFAULT.
555            /// </summary>
556            public short wShowWindow;
557
558            /// <summary>
559            /// Reserved for use by the C Run-time; must be zero.
560            /// </summary>
561            private const short cbReserved2 = 0;
562
563            /// <summary>
564            /// Reserved for use by the C Run-time; must be NULL.
565            /// </summary>
566            private readonly IntPtr lpReserved2;
567
568            /// <summary>
569            /// If dwFlags specifies STARTF_USESTDHANDLES, this member is the
570            /// standard input handle for the process. Otherwise, this member is
571            /// ignored and the default for standard input is the keyboard buffer.
572            /// </summary>
573            public IntPtr hStdInput;
574
575            /// <summary>
576            /// If dwFlags specifies STARTF_USESTDHANDLES, this member is the
577            /// standard output handle for the process. Otherwise, this member is
578            /// ignored and the default for standard output is the console window's
579            /// buffer.
580            /// </summary>
581            public IntPtr hStdOutput;
582
583            /// <summary>
584            /// If dwFlags specifies STARTF_USESTDHANDLES, this member is the
585            /// standard error handle for the process. Otherwise, this member is
586            /// ignored and the default for standard error is the console window's
587            /// buffer.
588            /// </summary>
589            public IntPtr hStdError;
590        }
591
592        /// <summary>
593        /// Enables an application to inform the system that it is in use, thereby
594        /// preventing the system from entering sleep or turning off the display
595        /// while the application is running.
596        /// </summary>
597        /// <param name="esFlags">The thread's execution requirements. This parameter
598        /// can be one or more of the EXECUTION_STATE values.</param>
599        /// <returns>If the function succeeds, the return value is the previous
600        /// thread execution state.
601        ///
602        /// If the function fails, the return value is NULL.</returns>
603        /// <remarks>The system automatically detects activities such as local keyboard
604        /// or mouse input, server activity, and changing window focus. Activities
605        /// that are not automatically detected include disk or CPU activity and
606        /// video display.
607        ///
608        /// Calling SetThreadExecutionState without ES_CONTINUOUS simply resets
609        /// the idle timer; to keep the display or system in the working state,
610        /// the thread must call SetThreadExecutionState periodically.
611        ///
612        /// To run properly on a power-managed computer, applications such as fax
613        /// servers, answering machines, backup agents, and network management
614        /// applications must use both ES_SYSTEM_REQUIRED and ES_CONTINUOUS when
615        /// they process events. Multimedia applications, such as video players
616        /// and presentation applications, must use ES_DISPLAY_REQUIRED when they
617        /// display video for long periods of time without user input. Applications
618        /// such as word processors, spreadsheets, browsers, and games do not need
619        /// to call SetThreadExecutionState.
620        ///
621        /// The ES_AWAYMODE_REQUIRED value should be used only when absolutely
622        /// necessary by media applications that require the system to perform
623        /// background tasks such as recording television content or streaming media
624        /// to other devices while the system appears to be sleeping. Applications
625        /// that do not require critical background processing or that run on
626        /// portable computers should not enable away mode because it prevents
627        /// the system from conserving power by entering true sleep.
628        ///
629        /// To enable away mode, an application uses both ES_AWAYMODE_REQUIRED and
630        /// ES_CONTINUOUS; to disable away mode, an application calls
631        /// SetThreadExecutionState with ES_CONTINUOUS and clears
632        /// ES_AWAYMODE_REQUIRED. When away mode is enabled, any operation that
633        /// would put the computer to sleep puts it in away mode instead. The computer
634        /// appears to be sleeping while the system continues to perform tasks that
635        /// do not require user input. Away mode does not affect the sleep idle
636        /// timer; to prevent the system from entering sleep when the timer expires,
637        /// an application must also set the ES_SYSTEM_REQUIRED value.
638        ///
639        /// The SetThreadExecutionState function cannot be used to prevent the user
640        /// from putting the computer to sleep. Applications should respect that
641        /// the user expects a certain behavior when they close the lid on their
642        /// laptop or press the power button.
643        ///
644        /// This function does not stop the screen saver from executing.
645        /// </remarks>
646        [DllImport("Kernel32.dll")]
647        public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
648
649        /// <summary>
650        /// Execution state values to be used in conjuction with SetThreadExecutionState
651        /// </summary>
652        public enum EXECUTION_STATE : uint
653        {
654            /// <summary>
655            /// Enables away mode. This value must be specified with ES_CONTINUOUS.
656            ///
657            /// Away mode should be used only by media-recording and media-distribution
658            /// applications that must perform critical background processing on
659            /// desktop computers while the computer appears to be sleeping.
660            /// See remarks.
661            ///
662            /// Windows Server 2003 and Windows XP/2000: ES_AWAYMODE_REQUIRED is
663            /// not supported.
664            /// </summary>
665            ES_AWAYMODE_REQUIRED = 0x00000040,
666   
667            /// <summary>
668            /// Informs the system that the state being set should remain in effect
669            /// until the next call that uses ES_CONTINUOUS and one of the other
670            /// state flags is cleared.
671            /// </summary>
672            ES_CONTINUOUS = 0x80000000,
673
674            /// <summary>
675            /// Forces the display to be on by resetting the display idle timer.
676            /// </summary>
677            ES_DISPLAY_REQUIRED = 0x00000002,
678
679            /// <summary>
680            /// Forces the system to be in the working state by resetting the system
681            /// idle timer.
682            /// </summary>
683            ES_SYSTEM_REQUIRED = 0x00000001,
684   
685            /// <summary>
686            /// This value is not supported. If ES_USER_PRESENT is combined with
687            /// other esFlags values, the call will fail and none of the specified
688            /// states will be set.
689            ///
690            /// Windows Server 2003 and Windows XP/2000: Informs the system that a
691            /// user is present and resets the display and system idle timers.
692            /// ES_USER_PRESENT must be called with ES_CONTINUOUS.
693            /// </summary>
694            ES_USER_PRESENT = 0x00000004
695        }
696
697        /// <summary>
698        /// Allocates a new console for the calling process.
699        /// </summary>
700        /// <returns>If the function succeeds, the return value is nonzero.
701        ///
702        /// If the function fails, the return value is zero. To get extended error
703        /// information, call Marshal.GetLastWin32Error.</returns>
704        /// <remarks>A process can be associated with only one console, so the AllocConsole
705        /// function fails if the calling process already has a console. A process can
706        /// use the FreeConsole function to detach itself from its current console, then
707        /// it can call AllocConsole to create a new console or AttachConsole to attach
708        /// to another console.
709        ///
710        /// If the calling process creates a child process, the child inherits the
711        /// new console.
712        ///
713        /// AllocConsole initializes standard input, standard output, and standard error
714        /// handles for the new console. The standard input handle is a handle to the
715        /// console's input buffer, and the standard output and standard error handles
716        /// are handles to the console's screen buffer. To retrieve these handles, use
717        /// the GetStdHandle function.
718        ///
719        /// This function is primarily used by graphical user interface (GUI) application
720        /// to create a console window. GUI applications are initialized without a
721        /// console. Console applications are initialized with a console, unless they
722        /// are created as detached processes (by calling the CreateProcess function
723        /// with the DETACHED_PROCESS flag).</remarks>
724        [DllImport("Kernel32.dll", SetLastError = true)]
725        public static extern bool AllocConsole();
726
727        /// <summary>
728        /// Detaches the calling process from its console.
729        /// </summary>
730        /// <returns>If the function succeeds, the return value is nonzero.
731        ///
732        /// If the function fails, the return value is zero. To get extended error
733        /// information, call Marshal.GetLastWin32Error.</returns>
734        /// <remarks>A process can be attached to at most one console. If the calling
735        /// process is not already attached to a console, the error code returned is
736        /// ERROR_INVALID_PARAMETER (87).
737        ///
738        /// A process can use the FreeConsole function to detach itself from its
739        /// console. If other processes share the console, the console is not destroyed,
740        /// but the process that called FreeConsole cannot refer to it. A console is
741        /// closed when the last process attached to it terminates or calls FreeConsole.
742        /// After a process calls FreeConsole, it can call the AllocConsole function to
743        /// create a new console or AttachConsole to attach to another console.</remarks>
744        [DllImport("Kernel32.dll", SetLastError = true)]
745        public static extern bool FreeConsole();
746    }
747}
Note: See TracBrowser for help on using the repository browser.