diff --git a/1.x/trunk/ProcessHacker.Common/BaseConverter.cs b/1.x/trunk/ProcessHacker.Common/BaseConverter.cs
index 9d5dd91a9..6f3708cba 100644
--- a/1.x/trunk/ProcessHacker.Common/BaseConverter.cs
+++ b/1.x/trunk/ProcessHacker.Common/BaseConverter.cs
@@ -30,7 +30,7 @@ namespace ProcessHacker.Common
///
public static class BaseConverter
{
- private static readonly int[] _reverseChars = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ private static int[] _reverseChars = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 52,
53, 54, 55, 56, 57, 58, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -74,7 +74,7 @@ public static decimal ToNumber(string number, int b)
if (b > 70)
return 0;
- if (string.IsNullOrEmpty(number))
+ if (number == "")
return 0;
bool negative = number[0] == '-';
@@ -95,8 +95,8 @@ public static decimal ToNumber(string number, int b)
if (negative)
return -result;
-
- return result;
+ else
+ return result;
}
///
@@ -118,11 +118,11 @@ public static decimal ToNumberParse(string number)
///
public static decimal ToNumberParse(string number, bool allowNonStandardExts)
{
- if (string.IsNullOrEmpty(number))
+ if (number == "")
return 0;
bool negative = number[0] == '-';
- decimal result;
+ decimal result = 0;
if (negative)
number = number.Substring(1);
@@ -169,8 +169,8 @@ public static decimal ToNumberParse(string number, bool allowNonStandardExts)
if (negative)
return -result;
-
- return result;
+ else
+ return result;
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/ByteStreamReader.cs b/1.x/trunk/ProcessHacker.Common/ByteStreamReader.cs
index d838b59ae..37026970a 100644
--- a/1.x/trunk/ProcessHacker.Common/ByteStreamReader.cs
+++ b/1.x/trunk/ProcessHacker.Common/ByteStreamReader.cs
@@ -21,13 +21,15 @@
*/
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Text;
namespace ProcessHacker.Common
{
public sealed class ByteStreamReader : Stream
{
- private readonly byte[] _data;
+ private byte[] _data;
private long _position;
public ByteStreamReader(byte[] data)
diff --git a/1.x/trunk/ProcessHacker.Common/DeltaManager.cs b/1.x/trunk/ProcessHacker.Common/DeltaManager.cs
index 0545e781b..c5d38f54a 100644
--- a/1.x/trunk/ProcessHacker.Common/DeltaManager.cs
+++ b/1.x/trunk/ProcessHacker.Common/DeltaManager.cs
@@ -20,6 +20,8 @@
* along with Process Hacker. If not, see .
*/
+using System.Collections.Generic;
+
namespace ProcessHacker.Common
{
///
@@ -36,10 +38,10 @@ public interface ISubtractor
public static class Subtractor
{
- private static readonly Int64Subtractor _int64Subtractor = new Int64Subtractor();
- private static readonly Int32Subtractor _int32Subtractor = new Int32Subtractor();
- private static readonly DoubleSubtractor _doubleSubtractor = new DoubleSubtractor();
- private static readonly FloatSubtractor _floatSubtractor = new FloatSubtractor();
+ private static Int64Subtractor _int64Subtractor = new Int64Subtractor();
+ private static Int32Subtractor _int32Subtractor = new Int32Subtractor();
+ private static DoubleSubtractor _doubleSubtractor = new DoubleSubtractor();
+ private static FloatSubtractor _floatSubtractor = new FloatSubtractor();
public static Int64Subtractor Int64Subtractor
{
@@ -115,7 +117,7 @@ public interface IDeltaValue
public struct DeltaValue : IDeltaValue
{
- private readonly ISubtractor _subtractor;
+ private ISubtractor _subtractor;
private T _value;
private T _delta;
diff --git a/1.x/trunk/ProcessHacker.Common/EnumComparer.cs b/1.x/trunk/ProcessHacker.Common/EnumComparer.cs
index 54fd689c8..ed0aa58a5 100644
--- a/1.x/trunk/ProcessHacker.Common/EnumComparer.cs
+++ b/1.x/trunk/ProcessHacker.Common/EnumComparer.cs
@@ -6,6 +6,7 @@
using System;
using System.Collections.Generic;
+using System.Text;
using System.Reflection.Emit;
namespace ProcessHacker.Common
@@ -14,6 +15,7 @@ public sealed class EnumComparer : IEqualityComparer
where TEnum : struct, IComparable, IConvertible, IFormattable
{
public static readonly EnumComparer Instance;
+
private static readonly Func _equals;
private static readonly Func _getHashCode;
@@ -51,11 +53,12 @@ private static void AssertTypeIsEnum()
private static void AssertUnderlyingTypeIsSupported()
{
var underlyingType = Enum.GetUnderlyingType(typeof(TEnum));
- ICollection supportedTypes = new[]
- {
- typeof(byte), typeof(sbyte), typeof(short), typeof(ushort),
- typeof(int), typeof(uint), typeof(long), typeof(ulong)
- };
+ ICollection supportedTypes =
+ new[]
+ {
+ typeof (byte), typeof (sbyte), typeof (short), typeof (ushort),
+ typeof (int), typeof (uint), typeof (long), typeof (ulong)
+ };
if (supportedTypes.Contains(underlyingType))
return;
@@ -75,19 +78,18 @@ private static void AssertUnderlyingTypeIsSupported()
/// The generated method.
private static Func generateEquals()
{
- var method = new DynamicMethod(typeof(TEnum).Name + "_Equals", typeof(bool), new[]
- {
- typeof(TEnum), typeof(TEnum)
- }, typeof(TEnum), true);
-
+ var method = new DynamicMethod(typeof(TEnum).Name + "_Equals",
+ typeof(bool),
+ new[] { typeof(TEnum), typeof(TEnum) },
+ typeof(TEnum), true);
var generator = method.GetILGenerator();
// Writing body
generator.Emit(OpCodes.Ldarg_0); // load x to stack
generator.Emit(OpCodes.Ldarg_1); // load y to stack
generator.Emit(OpCodes.Ceq); // x == y
generator.Emit(OpCodes.Ret); // return result
-
- return (Func)method.CreateDelegate(typeof(Func));
+ return (Func)method.CreateDelegate
+ (typeof(Func));
}
///
@@ -102,11 +104,10 @@ private static Func generateEquals()
/// The generated method.
private static Func generateGetHashCode()
{
- var method = new DynamicMethod(typeof(TEnum).Name + "_GetHashCode", typeof(int), new[]
- {
- typeof(TEnum)
- }, typeof(TEnum), true);
-
+ var method = new DynamicMethod(typeof(TEnum).Name + "_GetHashCode",
+ typeof(int),
+ new[] { typeof(TEnum) },
+ typeof(TEnum), true);
var generator = method.GetILGenerator();
var underlyingType = Enum.GetUnderlyingType(typeof(TEnum));
var getHashCodeMethod = underlyingType.GetMethod("GetHashCode");
@@ -117,7 +118,6 @@ private static Func generateGetHashCode()
generator.Emit(OpCodes.Ldloca_S, castValue); // load *castValue to stack
generator.Emit(OpCodes.Call, getHashCodeMethod); // castValue.GetHashCode()
generator.Emit(OpCodes.Ret); // return result
-
return (Func)method.CreateDelegate(typeof(Func));
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/FreeList.cs b/1.x/trunk/ProcessHacker.Common/FreeList.cs
index 47d79f470..a1b38c686 100644
--- a/1.x/trunk/ProcessHacker.Common/FreeList.cs
+++ b/1.x/trunk/ProcessHacker.Common/FreeList.cs
@@ -20,6 +20,7 @@
* along with Process Hacker. If not, see .
*/
+using System;
using System.Threading;
namespace ProcessHacker.Common
@@ -27,10 +28,11 @@ namespace ProcessHacker.Common
///
/// Manages a list of free objects that can be re-used.
///
- public class FreeList where T : IResettable, new()
+ public class FreeList
+ where T : IResettable, new()
{
- private readonly T[] _list;
- private int _freeIndex;
+ private T[] _list;
+ private int _freeIndex = 0;
public FreeList(int maximumCount)
{
diff --git a/1.x/trunk/ProcessHacker.Common/IResettable.cs b/1.x/trunk/ProcessHacker.Common/IResettable.cs
index 85ceb09ef..2fa07049c 100644
--- a/1.x/trunk/ProcessHacker.Common/IResettable.cs
+++ b/1.x/trunk/ProcessHacker.Common/IResettable.cs
@@ -1,4 +1,8 @@
-namespace ProcessHacker.Common
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ProcessHacker.Common
{
public interface IResettable
{
diff --git a/1.x/trunk/ProcessHacker.Common/IdGenerator.cs b/1.x/trunk/ProcessHacker.Common/IdGenerator.cs
index bb3284725..cae77136d 100644
--- a/1.x/trunk/ProcessHacker.Common/IdGenerator.cs
+++ b/1.x/trunk/ProcessHacker.Common/IdGenerator.cs
@@ -30,9 +30,9 @@ namespace ProcessHacker.Common
///
public class IdGenerator
{
- private readonly int _step = 1;
- private bool _sort;
- private readonly List _ids = new List();
+ private int _step = 1;
+ private bool _sort = false;
+ private List _ids = new List();
private int _id;
///
@@ -88,9 +88,11 @@ public int Pop()
return id;
}
-
- id = this._id;
- this._id += this._step;
+ else
+ {
+ id = _id;
+ _id += _step;
+ }
}
return id;
diff --git a/1.x/trunk/ProcessHacker.Common/LibC.cs b/1.x/trunk/ProcessHacker.Common/LibC.cs
index 5240ecc17..f75ce1675 100644
--- a/1.x/trunk/ProcessHacker.Common/LibC.cs
+++ b/1.x/trunk/ProcessHacker.Common/LibC.cs
@@ -1,4 +1,8 @@
-namespace ProcessHacker.Common
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ProcessHacker.Common
{
public static class LibC
{
diff --git a/1.x/trunk/ProcessHacker.Common/LinkedList.cs b/1.x/trunk/ProcessHacker.Common/LinkedList.cs
index 340de4508..cb7f667f9 100644
--- a/1.x/trunk/ProcessHacker.Common/LinkedList.cs
+++ b/1.x/trunk/ProcessHacker.Common/LinkedList.cs
@@ -1,4 +1,6 @@
-namespace ProcessHacker.Common
+using System;
+
+namespace ProcessHacker.Common
{
public class LinkedListEntry
{
diff --git a/1.x/trunk/ProcessHacker.Common/Logging.cs b/1.x/trunk/ProcessHacker.Common/Logging.cs
index 9778d8998..e2c973f84 100644
--- a/1.x/trunk/ProcessHacker.Common/Logging.cs
+++ b/1.x/trunk/ProcessHacker.Common/Logging.cs
@@ -22,6 +22,7 @@
using System;
using System.Diagnostics;
+using System.Runtime.InteropServices;
namespace ProcessHacker.Common
{
@@ -29,7 +30,7 @@ namespace ProcessHacker.Common
public static class Logging
{
- public enum Importance
+ public enum Importance : int
{
Information = 0,
Warning,
@@ -39,18 +40,26 @@ public enum Importance
public static event LoggingDelegate Logged;
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ private static extern void OutputDebugString(string OutputString);
+
+ private static object _logLock = new object();
+
[Conditional("DEBUG")]
public static void Log(Importance importance, string message)
{
- string debugMessage =
- DateTime.Now.ToString("hh:mm:ss:fff:") +
- " ProcessHacker (T" + System.Threading.Thread.CurrentThread.ManagedThreadId +
- "): (" + importance.ToString() + ") " + message + "\r\n\r\n" + Environment.StackTrace;
+ lock (_logLock)
+ {
+ string debugMessage =
+ DateTime.Now.ToString("hh:mm:ss:fff:") +
+ " ProcessHacker (T" + System.Threading.Thread.CurrentThread.ManagedThreadId +
+ "): (" + importance.ToString() + ") " + message + "\r\n\r\n" + Environment.StackTrace;
- Debugger.Log(0, "DEBUG", debugMessage);
+ OutputDebugString(debugMessage);
- if (Logged != null)
- Logged(debugMessage);
+ if (Logged != null)
+ Logged(debugMessage);
+ }
}
[Conditional("DEBUG")]
@@ -59,7 +68,7 @@ public static void Log(Exception ex)
string message = ex.Message;
if (ex.InnerException != null)
- message += "\r\nInner exception:\r\n" + ex.InnerException;
+ message += "\r\nInner exception:\r\n" + ex.InnerException.ToString();
if (ex.StackTrace != null)
message += "\r\n" + ex.StackTrace;
diff --git a/1.x/trunk/ProcessHacker.Common/Messaging/Message.cs b/1.x/trunk/ProcessHacker.Common/Messaging/Message.cs
index 8e77a91af..99616e719 100644
--- a/1.x/trunk/ProcessHacker.Common/Messaging/Message.cs
+++ b/1.x/trunk/ProcessHacker.Common/Messaging/Message.cs
@@ -1,15 +1,23 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Common.Messaging
{
public class Message
{
- public object Tag { get; set; }
+ private object _tag;
+
+ public object Tag
+ {
+ get { return _tag; }
+ set { _tag = value; }
+ }
}
public class ActionMessage : Message
{
- private readonly Action _action;
+ private Action _action;
public ActionMessage(Action action)
{
diff --git a/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueue.cs b/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueue.cs
index 86f82763d..9ef8adb34 100644
--- a/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueue.cs
+++ b/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueue.cs
@@ -1,17 +1,18 @@
using System;
using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Common.Messaging
{
public class MessageQueue
{
- private readonly Queue _queue = new Queue();
- private readonly List _listeners = new List();
+ private Queue _queue = new Queue();
+ private List _listeners = new List();
public MessageQueue()
{
// Action message listener.
- this.AddListener(new MessageQueueListener(action => action.Action()));
+ this.AddListener(new MessageQueueListener((action) => action.Action()));
}
public void AddListener(MessageQueueListener listener)
diff --git a/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueueListener.cs b/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueueListener.cs
index 0b22b8733..b63b72ee0 100644
--- a/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueueListener.cs
+++ b/1.x/trunk/ProcessHacker.Common/Messaging/MessageQueueListener.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Common.Messaging
{
@@ -6,8 +8,8 @@ namespace ProcessHacker.Common.Messaging
public class MessageQueueListener
{
- private readonly MessageReceivedDelegate _callback;
- private readonly Type _type;
+ private MessageReceivedDelegate _callback;
+ private Type _type;
public MessageQueueListener(MessageReceivedDelegate callback, Type type)
{
@@ -26,12 +28,13 @@ public Type Type
}
}
- public class MessageQueueListener : MessageQueueListener where T : Message
+ public class MessageQueueListener : MessageQueueListener
+ where T : Message
{
public delegate void MessageReceivedDelegate(T message);
public MessageQueueListener(MessageReceivedDelegate callback)
- : base(message => callback((T)message), typeof(T))
+ : base((message) => callback((T)message), typeof(T))
{ }
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/Objects/BaseObject.cs b/1.x/trunk/ProcessHacker.Common/Objects/BaseObject.cs
index 6244dc021..2da6d5e3f 100644
--- a/1.x/trunk/ProcessHacker.Common/Objects/BaseObject.cs
+++ b/1.x/trunk/ProcessHacker.Common/Objects/BaseObject.cs
@@ -21,7 +21,7 @@
*/
/* If enabled, the object system will keep statistics. */
-//#define ENABLE_STATISTICS
+#define ENABLE_STATISTICS
/* If enabled, the finalizers on objects can be enabled and disabled.
* If disabled, the finalizers on objects can only be disabled.
@@ -61,23 +61,23 @@ namespace ProcessHacker.Common.Objects
/// the object will be freed.
///
///
- public abstract class BaseObject : IRefCounted
+ public abstract class BaseObject : IDisposable, IRefCounted
{
- private const long ObjectOwned = 0x1;
- private const long ObjectOwnedByGc = 0x2;
- private const long ObjectDisposed = 0x4;
- private const long ObjectRefCountShift = 3;
- private const long ObjectRefCountMask = 0x1fffffff;
- private const long ObjectRefCountIncrement = 0x8;
-
- private static long _createdCount;
- private static long _freedCount;
- private static long _disposedCount;
- private static long _finalizedCount;
- private static long _referencedCount;
- private static long _dereferencedCount;
-
-#if DEBUG_ENABLE_LIVE_LIST
+ private const int ObjectOwned = 0x1;
+ private const int ObjectOwnedByGc = 0x2;
+ private const int ObjectDisposed = 0x4;
+ private const int ObjectRefCountShift = 3;
+ private const int ObjectRefCountMask = 0x1fffffff;
+ private const int ObjectRefCountIncrement = 0x8;
+
+ private static int _createdCount = 0;
+ private static int _freedCount = 0;
+ private static int _disposedCount = 0;
+ private static int _finalizedCount = 0;
+ private static int _referencedCount = 0;
+ private static int _dereferencedCount = 0;
+
+#if DEBUG && DEBUG_ENABLE_LIVE_LIST
private static System.Collections.Generic.List> _liveList =
new System.Collections.Generic.List>();
#endif
@@ -85,29 +85,29 @@ public abstract class BaseObject : IRefCounted
///
/// Gets the number of disposable, owned objects that have been created.
///
- public static long CreatedCount { get { return _createdCount; } }
+ public static int CreatedCount { get { return _createdCount; } }
///
/// Gets the number of disposable objects that have been freed.
///
- public static long FreedCount { get { return _freedCount; } }
+ public static int FreedCount { get { return _freedCount; } }
///
/// Gets the number of disposable objects that have been Disposed with managed = true.
///
- public static long DisposedCount { get { return _disposedCount; } }
+ public static int DisposedCount { get { return _disposedCount; } }
///
/// Gets the number of disposable objects that have been Disposed with managed = false.
///
- public static long FinalizedCount { get { return _finalizedCount; } }
+ public static int FinalizedCount { get { return _finalizedCount; } }
///
/// Gets the number of times disposable objects have been referenced.
///
- public static long ReferencedCount { get { return _referencedCount; } }
+ public static int ReferencedCount { get { return _referencedCount; } }
///
/// Gets the number of times disposable objects have been dereferenced.
///
- public static long DereferencedCount { get { return _dereferencedCount; } }
+ public static int DereferencedCount { get { return _dereferencedCount; } }
-#if DEBUG_ENABLE_LIVE_LIST
+#if DEBUG && DEBUG_ENABLE_LIVE_LIST
public static void CleanLiveList()
{
var list = new System.Collections.Generic.List>();
@@ -122,17 +122,16 @@ public static void CleanLiveList()
}
#endif
- public static T SwapRef(ref T reference, T newObj) where T : class, IRefCounted
+ public static T SwapRef(ref T reference, T newObj)
+ where T : class, IRefCounted
{
T oldObj;
// Swap the reference.
- oldObj = Interlocked.Exchange(ref reference, newObj);
-
+ oldObj = Interlocked.Exchange(ref reference, newObj);
// Reference the new object.
if (newObj != null)
newObj.Reference();
-
// Dereference the old object.
if (oldObj != null)
oldObj.Dereference();
@@ -140,27 +139,27 @@ public static T SwapRef(ref T reference, T newObj) where T : class, IRefCount
return oldObj;
}
-#if DEBUG_ENABLE_LIVE_LIST
+#if DEBUG
///
/// A stack trace collected when the object is created.
///
private string _creationStackTrace;
#endif
///
- /// An UInt32 containing various fields.
+ /// An Int32 containing various fields.
///
- private long _value;
+ private int _value;
#if EXTENDED_FINALIZER
///
/// Whether the finalizer will run.
///
- private uint _finalizerRegistered = 1;
+ private int _finalizerRegistered = 1;
#endif
///
/// Initializes a disposable object.
///
- protected BaseObject()
+ public BaseObject()
: this(true)
{ }
@@ -168,7 +167,7 @@ protected BaseObject()
/// Initializes a disposable object.
///
/// Whether the resource is owned.
- protected BaseObject(bool owned)
+ public BaseObject(bool owned)
{
_value = ObjectOwned + ObjectOwnedByGc + ObjectRefCountIncrement;
@@ -188,9 +187,11 @@ protected BaseObject(bool owned)
Interlocked.Increment(ref _createdCount);
#endif
-#if DEBUG_ENABLE_LIVE_LIST
+#if DEBUG
_creationStackTrace = Environment.StackTrace;
+#if DEBUG_ENABLE_LIVE_LIST
_liveList.Add(new WeakReference(this));
+#endif
#endif
}
@@ -223,8 +224,8 @@ public void Dispose()
///
/// Whether to dispose managed resources.
public void Dispose(bool managed)
- {
- long value = 0;
+ {
+ int value;
if ((_value & ObjectOwned) == 0)
return;
@@ -315,9 +316,9 @@ public bool OwnedByGc
/// This information is for debugging purposes ONLY. DO NOT
/// base memory management logic upon this value.
///
- public long ReferenceCount
+ public int ReferenceCount
{
- get { return (_value >> (int)ObjectRefCountShift) & ObjectRefCountMask; }
+ get { return (_value >> ObjectRefCountShift) & ObjectRefCountMask; }
}
#if EXTENDED_FINALIZER
@@ -326,7 +327,7 @@ public long ReferenceCount
///
private void DisableFinalizer()
{
- long oldFinalizerRegistered;
+ int oldFinalizerRegistered;
oldFinalizerRegistered = Interlocked.CompareExchange(ref _finalizerRegistered, 0, 1);
@@ -342,7 +343,7 @@ private void DisableFinalizer()
///
protected void DisableOwnership(bool dispose)
{
- long value = 0;
+ int value;
if (dispose)
this.Dispose();
@@ -383,7 +384,7 @@ protected void DisableOwnership(bool dispose)
/// Dereference(false).
///
///
- public long Dereference()
+ public int Dereference()
{
return this.Dereference(true);
}
@@ -397,7 +398,7 @@ public long Dereference()
/// If you are calling this method from a finalizer, set
/// to false.
///
- public long Dereference(bool managed)
+ public int Dereference(bool managed)
{
return this.Dereference(1, managed);
}
@@ -407,7 +408,7 @@ public long Dereference(bool managed)
///
/// The number of times to dereference the object.
/// The new reference count.
- public long Dereference(long count)
+ public int Dereference(int count)
{
return this.Dereference(count, true);
}
@@ -418,10 +419,10 @@ public long Dereference(long count)
/// The number of times to dereference the object.
/// Whether to dispose managed resources.
/// The new reference count.
- public long Dereference(long count, bool managed)
+ public int Dereference(int count, bool managed)
{
- long value = 0;
- long newRefCount = 0;
+ int value;
+ int newRefCount;
// Initial parameter validation.
if (count == 0)
@@ -439,7 +440,7 @@ public long Dereference(long count, bool managed)
// Decrease the reference count.
value = Interlocked.Add(ref _value, -ObjectRefCountIncrement * count);
- newRefCount = (value >> (int)ObjectRefCountShift) & ObjectRefCountMask;
+ newRefCount = (value >> ObjectRefCountShift) & ObjectRefCountMask;
// Should not ever happen.
if (newRefCount < 0)
@@ -485,7 +486,7 @@ public void DereferenceDelayed()
///
private void EnableFinalizer()
{
- long oldFinalizerRegistered;
+ int oldFinalizerRegistered;
oldFinalizerRegistered = Interlocked.CompareExchange(ref _finalizerRegistered, 1, 0);
@@ -506,7 +507,7 @@ private void EnableFinalizer()
/// object) to match each call to Reference. Do not call Dispose.
///
///
- public long Reference()
+ public int Reference()
{
return this.Reference(1);
}
@@ -516,9 +517,9 @@ public long Reference()
///
/// The number of times to reference the object.
/// The new reference count.
- public long Reference(long count)
+ public int Reference(int count)
{
- long value;
+ int value;
// Don't do anything if the object isn't owned.
if ((_value & ObjectOwned) == 0)
@@ -535,7 +536,7 @@ public long Reference(long count)
value = Interlocked.Add(ref _value, ObjectRefCountIncrement * count);
- return (value >> (int)ObjectRefCountShift) & ObjectRefCountMask;
+ return (value >> ObjectRefCountShift) & ObjectRefCountMask;
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/Objects/DelayedReleasePool.cs b/1.x/trunk/ProcessHacker.Common/Objects/DelayedReleasePool.cs
index a6c57893f..b240d38c9 100644
--- a/1.x/trunk/ProcessHacker.Common/Objects/DelayedReleasePool.cs
+++ b/1.x/trunk/ProcessHacker.Common/Objects/DelayedReleasePool.cs
@@ -56,8 +56,8 @@ private enum DelayedReleaseFlags
///
private struct DelayedReleaseObject
{
- private readonly DelayedReleaseFlags _flags;
- private readonly BaseObject _object;
+ private DelayedReleaseFlags _flags;
+ private BaseObject _object;
public DelayedReleaseObject(DelayedReleaseFlags flags, BaseObject obj)
{
@@ -86,7 +86,14 @@ public BaseObject Object
///
public static DelayedReleasePool CurrentPool
{
- get { return _currentPool ?? (_currentPool = new DelayedReleasePool()); }
+ get
+ {
+ if (_currentPool == null)
+ _currentPool = new DelayedReleasePool();
+
+ return _currentPool;
+ }
+ private set { _currentPool = value; }
}
///
@@ -97,7 +104,10 @@ private static Stack PoolStack
get
{
// No locking needed because the stack is thread-local.
- return _poolStack ?? (_poolStack = new Stack());
+ if (_poolStack == null)
+ _poolStack = new Stack();
+
+ return _poolStack;
}
}
@@ -107,9 +117,6 @@ private static Stack PoolStack
/// The current delayed release pool.
private static void PopPool(DelayedReleasePool pool)
{
- if (pool == null)
- throw new ArgumentNullException("pool");
-
if (_currentPool != pool)
throw new OutOfOrderException(
"Attempted to pop a pool when it wasn't on top of the stack. " +
@@ -129,8 +136,8 @@ private static void PushPool(DelayedReleasePool pool)
_currentPool = pool;
}
- private readonly int _creatorThreadId;
- private readonly List _objects = new List();
+ private int _creatorThreadId;
+ private List _objects = new List();
///
/// Creates a delayed release pool and sets it as the currently active pool.
@@ -188,12 +195,11 @@ public void Drain()
/// Whether to release managed resources.
public void Drain(bool managed)
{
- foreach (DelayedReleaseObject obj in _objects)
+ foreach (var obj in _objects)
{
- if (obj.Flags.HasFlag(DelayedReleaseFlags.Dispose))
+ if ((obj.Flags & DelayedReleaseFlags.Dispose) == DelayedReleaseFlags.Dispose)
obj.Object.Dispose();
-
- if (obj.Flags.HasFlag(DelayedReleaseFlags.Dereference))
+ if ((obj.Flags & DelayedReleaseFlags.Dereference) == DelayedReleaseFlags.Dereference)
obj.Object.Dereference(managed);
}
diff --git a/1.x/trunk/ProcessHacker.Common/Objects/HandleTable.cs b/1.x/trunk/ProcessHacker.Common/Objects/HandleTable.cs
index f35264d16..938c7902d 100644
--- a/1.x/trunk/ProcessHacker.Common/Objects/HandleTable.cs
+++ b/1.x/trunk/ProcessHacker.Common/Objects/HandleTable.cs
@@ -27,8 +27,20 @@ namespace ProcessHacker.Common.Objects
{
public class HandleTableEntry
{
- public int Handle { get; internal set; }
- public IRefCounted Object { get; internal set; }
+ private int _handle;
+ private IRefCounted _object;
+
+ public int Handle
+ {
+ get { return _handle; }
+ internal set { _handle = value; }
+ }
+
+ public IRefCounted Object
+ {
+ get { return _object; }
+ internal set { _object = value; }
+ }
}
///
@@ -52,9 +64,9 @@ public class HandleTable : BaseObject
/// Return true to stop enumerating; otherwise return false.
public delegate bool EnumerateHandleTableDelegate(int handle, TEntry entry);
- private readonly IdGenerator _handleGenerator = new IdGenerator(4, 4);
- private readonly FastResourceLock _lock = new FastResourceLock();
- private readonly Dictionary _handles = new Dictionary();
+ private IdGenerator _handleGenerator = new IdGenerator(4, 4);
+ private FastResourceLock _lock = new FastResourceLock();
+ private Dictionary _handles = new Dictionary();
protected override void DisposeObject(bool disposing)
{
@@ -306,7 +318,8 @@ public T ReferenceByHandle(int handle)
/// An object. This object has been referenced and must be
/// dereferenced once it is no longer needed.
///
- public T ReferenceByHandle(int handle, out TEntry entry) where T : class, IRefCounted
+ public T ReferenceByHandle(int handle, out TEntry entry)
+ where T : class, IRefCounted
{
IRefCounted obj = this.ReferenceByHandle(handle, out entry);
@@ -318,10 +331,12 @@ public T ReferenceByHandle(int handle, out TEntry entry) where T : class, IRe
{
return (T)obj;
}
-
- // Wrong type. Dereference and return.
- obj.Dereference();
- return null;
+ else
+ {
+ // Wrong type. Dereference and return.
+ obj.Dereference();
+ return null;
+ }
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/Objects/IRefCounted.cs b/1.x/trunk/ProcessHacker.Common/Objects/IRefCounted.cs
index e7f10cf67..cbb37b004 100644
--- a/1.x/trunk/ProcessHacker.Common/Objects/IRefCounted.cs
+++ b/1.x/trunk/ProcessHacker.Common/Objects/IRefCounted.cs
@@ -8,21 +8,21 @@ public interface IRefCounted : IDisposable
/// Decrements the reference count of the object.
///
/// The new reference count.
- long Dereference();
+ int Dereference();
///
/// Decrements the reference count of the object.
///
/// Whether to dispose managed resources.
/// The new reference count.
- long Dereference(bool managed);
+ int Dereference(bool managed);
///
/// Decreases the reference count of the object.
///
/// The number of times to dereference the object.
/// The new reference count.
- long Dereference(long count);
+ int Dereference(int count);
///
/// Decreases the reference count of the object.
@@ -30,7 +30,7 @@ public interface IRefCounted : IDisposable
/// The number of times to dereference the object.
/// Whether to dispose managed resources.
/// The new reference count.
- long Dereference(long count, bool managed);
+ int Dereference(int count, bool managed);
///
/// Ensures that the reference counting system has exclusive control
@@ -43,13 +43,13 @@ public interface IRefCounted : IDisposable
/// Increments the reference count of the object.
///
/// The new reference count.
- long Reference();
+ int Reference();
///
/// Increases the reference count of the object.
///
/// The number of times to reference the object.
/// The new reference count.
- long Reference(long count);
+ int Reference(int count);
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/Objects/SecuredHandleTable.cs b/1.x/trunk/ProcessHacker.Common/Objects/SecuredHandleTable.cs
index 9bce52099..77dd24b2c 100644
--- a/1.x/trunk/ProcessHacker.Common/Objects/SecuredHandleTable.cs
+++ b/1.x/trunk/ProcessHacker.Common/Objects/SecuredHandleTable.cs
@@ -27,30 +27,33 @@ namespace ProcessHacker.Common.Objects
public class SecuredHandleTableEntry : HandleTableEntry
{
private long _grantedAccess;
+
public long GrantedAccess
{
get { return _grantedAccess; }
set { _grantedAccess = value; }
}
- public bool AreAllAccessesGranted(TAccess access) where TAccess : struct
+ public bool AreAllAccessesGranted(TAccess access)
+ where TAccess : struct
{
long accessLong = Convert.ToInt64(access);
if ((_grantedAccess & accessLong) == accessLong)
return true;
-
- return false;
+ else
+ return false;
}
- public bool AreAnyAccessesGranted(TAccess access) where TAccess : struct
+ public bool AreAnyAccessesGranted(TAccess access)
+ where TAccess : struct
{
long accessLong = Convert.ToInt64(access);
if ((_grantedAccess & accessLong) != 0)
return true;
-
- return false;
+ else
+ return false;
}
}
@@ -74,12 +77,12 @@ public class SecuredHandleTable : HandleTable
/// The object to reference.
/// The granted access to the object.
/// The new handle.
- public int Allocate(IRefCounted obj, TAccess grantedAccess) where TAccess : struct
+ public int Allocate(IRefCounted obj, TAccess grantedAccess)
+ where TAccess : struct
{
- TEntry entry = new TEntry
- {
- GrantedAccess = Convert.ToInt64(grantedAccess)
- };
+ TEntry entry = new TEntry();
+
+ entry.GrantedAccess = Convert.ToInt64(grantedAccess);
return base.Allocate(obj, entry);
}
@@ -94,9 +97,10 @@ public int Allocate(IRefCounted obj, TAccess grantedAccess) where TAcce
/// An object. This object has been referenced and must be
/// dereferenced once it is no longer needed.
///
- public IRefCounted ReferenceByHandle(int handle, TAccess access) where TAccess : struct
+ public IRefCounted ReferenceByHandle(int handle, TAccess access)
+ where TAccess : struct
{
- return this.ReferenceByHandle(handle, access, false);
+ return this.ReferenceByHandle(handle, access, false);
}
///
@@ -112,30 +116,34 @@ public IRefCounted ReferenceByHandle(int handle, TAccess access) where
/// An object. This object has been referenced and must be
/// dereferenced once it is no longer needed.
///
- public IRefCounted ReferenceByHandle(int handle, TAccess access, bool throwOnAccessDenied) where TAccess : struct
+ public IRefCounted ReferenceByHandle(int handle, TAccess access, bool throwOnAccessDenied)
+ where TAccess : struct
{
TEntry entry;
+ IRefCounted obj;
// Reference the object.
- IRefCounted obj = this.ReferenceByHandle(handle, out entry);
+ obj = this.ReferenceByHandle(handle, out entry);
if (obj == null)
return null;
// Check the access.
- if (entry.AreAllAccessesGranted(access))
+ if (entry.AreAllAccessesGranted(access))
{
// OK, return the object.
return obj;
}
-
- // Access denied. Dereference the object and return.
- obj.Dereference();
-
- if (throwOnAccessDenied)
- throw new UnauthorizedAccessException("Access denied.");
-
- return null;
+ else
+ {
+ // Access denied. Dereference the object and return.
+ obj.Dereference();
+
+ if (throwOnAccessDenied)
+ throw new UnauthorizedAccessException("Access denied.");
+ else
+ return null;
+ }
}
///
@@ -149,7 +157,9 @@ public IRefCounted ReferenceByHandle(int handle, TAccess access, bool t
/// An object. This object has been referenced and must be
/// dereferenced once it is no longer needed.
///
- public T ReferenceByHandle(int handle, TAccess access) where T : class, IRefCounted where TAccess : struct
+ public T ReferenceByHandle(int handle, TAccess access)
+ where T : class, IRefCounted
+ where TAccess : struct
{
return this.ReferenceByHandle(handle, access, false);
}
@@ -168,9 +178,11 @@ public T ReferenceByHandle(int handle, TAccess access) where T : cla
/// An object. This object has been referenced and must be
/// dereferenced once it is no longer needed.
///
- public T ReferenceByHandle(int handle, TAccess access, bool throwOnAccessDenied) where T : class, IRefCounted where TAccess : struct
+ public T ReferenceByHandle(int handle, TAccess access, bool throwOnAccessDenied)
+ where T : class, IRefCounted
+ where TAccess : struct
{
- IRefCounted obj = this.ReferenceByHandle(handle, access, throwOnAccessDenied);
+ IRefCounted obj = this.ReferenceByHandle(handle, access, throwOnAccessDenied);
if (obj == null)
return null;
@@ -178,12 +190,13 @@ public T ReferenceByHandle(int handle, TAccess access, bool throwOnA
// Check the type.
if (obj is T)
{
- return obj as T;
+ return (T)obj;
+ }
+ else
+ {
+ obj.Dereference();
+ return null;
}
-
- obj.Dereference();
-
- return null;
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/ProcessHacker.Common.csproj b/1.x/trunk/ProcessHacker.Common/ProcessHacker.Common.csproj
index d3c136c66..704e9fd35 100644
--- a/1.x/trunk/ProcessHacker.Common/ProcessHacker.Common.csproj
+++ b/1.x/trunk/ProcessHacker.Common/ProcessHacker.Common.csproj
@@ -10,7 +10,7 @@
Properties
ProcessHacker.Common
ProcessHacker.Common
- v4.5
+ v4.0
512
@@ -48,7 +48,6 @@
true
AnyCPU
AllRules.ruleset
- false
pdbonly
@@ -62,7 +61,6 @@
true
AnyCPU
AllRules.ruleset
- false
@@ -117,6 +115,7 @@
+
diff --git a/1.x/trunk/ProcessHacker.Common/Properties/AssemblyInfo.cs b/1.x/trunk/ProcessHacker.Common/Properties/AssemblyInfo.cs
index 44018ff4a..f99cfef91 100644
--- a/1.x/trunk/ProcessHacker.Common/Properties/AssemblyInfo.cs
+++ b/1.x/trunk/ProcessHacker.Common/Properties/AssemblyInfo.cs
@@ -1,4 +1,5 @@
using System.Reflection;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
diff --git a/1.x/trunk/ProcessHacker.Common/Settings/SettingDefaultAttribute.cs b/1.x/trunk/ProcessHacker.Common/Settings/SettingDefaultAttribute.cs
index b840335dc..567b0a46a 100644
--- a/1.x/trunk/ProcessHacker.Common/Settings/SettingDefaultAttribute.cs
+++ b/1.x/trunk/ProcessHacker.Common/Settings/SettingDefaultAttribute.cs
@@ -30,7 +30,7 @@ namespace ProcessHacker.Common.Settings
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class SettingDefaultAttribute : Attribute
{
- private readonly string _value;
+ private string _value;
///
/// Initializes a new instance of the SettingDefaultAttribute class.
diff --git a/1.x/trunk/ProcessHacker.Common/Settings/SettingsBase.cs b/1.x/trunk/ProcessHacker.Common/Settings/SettingsBase.cs
index 2c2c75cbf..a4e926b5f 100644
--- a/1.x/trunk/ProcessHacker.Common/Settings/SettingsBase.cs
+++ b/1.x/trunk/ProcessHacker.Common/Settings/SettingsBase.cs
@@ -32,17 +32,17 @@ namespace ProcessHacker.Common.Settings
///
public abstract class SettingsBase
{
- private readonly ISettingsStore _store;
- private readonly Dictionary _settings = new Dictionary();
- private readonly Dictionary _modifiedSettings = new Dictionary();
- private readonly Dictionary _defaultsCache = new Dictionary();
- private readonly Dictionary _typeCache = new Dictionary();
+ private ISettingsStore _store;
+ private Dictionary _settings = new Dictionary();
+ private Dictionary _modifiedSettings = new Dictionary();
+ private Dictionary _defaultsCache = new Dictionary();
+ private Dictionary _typeCache = new Dictionary();
///
/// Creates a settings class with the specified storage provider.
///
/// The storage provider.
- protected SettingsBase(ISettingsStore store)
+ public SettingsBase(ISettingsStore store)
{
_store = store;
}
@@ -76,15 +76,14 @@ protected virtual object ConvertFromString(string value, Type valueType)
{
if (valueType.IsPrimitive)
return Convert.ChangeType(value, valueType);
-
- if (valueType == typeof(string))
+ else if (valueType == typeof(string))
return value;
- TypeConverter converter = TypeDescriptor.GetConverter(valueType);
+ var converter = TypeDescriptor.GetConverter(valueType);
// Since all types can convert to System.String, we also need to make sure they can
// convert from System.String.
- if (converter != null && (converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(typeof(string))))
+ if (converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(typeof(string)))
return converter.ConvertFromInvariantString(value);
throw new InvalidOperationException("The setting '" + value + "' has an unsupported type.");
@@ -100,15 +99,14 @@ protected virtual string ConvertToString(object value, Type valueType)
{
if (valueType.IsPrimitive)
return (string)Convert.ChangeType(value, typeof(string));
-
- if (valueType == typeof(string))
+ else if (valueType == typeof(string))
return (string)value;
- TypeConverter converter = TypeDescriptor.GetConverter(valueType);
+ var converter = TypeDescriptor.GetConverter(valueType);
// Since all types can convert to System.String, we also need to make sure they can
// convert from System.String.
- if (converter != null && (converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(typeof(string))))
+ if (converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(typeof(string)))
return converter.ConvertToInvariantString(value);
throw new InvalidOperationException("The setting '" + value + "' has an unsupported type.");
@@ -125,15 +123,12 @@ private string GetSettingDefault(string name)
{
if (!_defaultsCache.ContainsKey(name))
{
- PropertyInfo property = this.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
- object[] attributes = property.GetCustomAttributes(typeof(SettingDefaultAttribute), true);
+ var property = this.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
+ var attributes = property.GetCustomAttributes(typeof(SettingDefaultAttribute), true);
if (attributes.Length == 1)
{
- SettingDefaultAttribute settingDefaultAttribute = attributes[0] as SettingDefaultAttribute;
-
- if (settingDefaultAttribute != null)
- this._defaultsCache.Add(name, settingDefaultAttribute.Value);
+ _defaultsCache.Add(name, (attributes[0] as SettingDefaultAttribute).Value);
}
else
{
@@ -173,6 +168,8 @@ private Type GetSettingType(string name)
private object GetValue(string name)
{
object value;
+ string settingValue;
+ Type settingType;
lock (_modifiedSettings)
{
@@ -186,14 +183,14 @@ private object GetValue(string name)
return _settings[name];
}
- string settingValue = this._store.GetValue(name);
+ settingValue = _store.GetValue(name);
- if (string.IsNullOrEmpty(settingValue))
+ if (settingValue == null)
settingValue = this.GetSettingDefault(name);
- if (string.IsNullOrEmpty(settingValue))
- settingValue = string.Empty;
+ if (settingValue == null)
+ settingValue = "";
- Type settingType = this.GetSettingType(name);
+ settingType = this.GetSettingType(name);
try
{
@@ -253,7 +250,7 @@ public void Save()
{
lock (_modifiedSettings)
{
- foreach (KeyValuePair pair in _modifiedSettings)
+ foreach (var pair in _modifiedSettings)
{
_store.SetValue(pair.Key, this.ConvertToString(pair.Value, this.GetSettingType(pair.Key)));
}
diff --git a/1.x/trunk/ProcessHacker.Common/Settings/VolatileSettingsStore.cs b/1.x/trunk/ProcessHacker.Common/Settings/VolatileSettingsStore.cs
index 0dda0ce3b..5ffb44f5e 100644
--- a/1.x/trunk/ProcessHacker.Common/Settings/VolatileSettingsStore.cs
+++ b/1.x/trunk/ProcessHacker.Common/Settings/VolatileSettingsStore.cs
@@ -1,4 +1,8 @@
-namespace ProcessHacker.Common.Settings
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ProcessHacker.Common.Settings
{
public sealed class VolatileSettingsStore : ISettingsStore
{
diff --git a/1.x/trunk/ProcessHacker.Common/Settings/XmlFileSettingsStore.cs b/1.x/trunk/ProcessHacker.Common/Settings/XmlFileSettingsStore.cs
index 54a98c8db..23795c3a6 100644
--- a/1.x/trunk/ProcessHacker.Common/Settings/XmlFileSettingsStore.cs
+++ b/1.x/trunk/ProcessHacker.Common/Settings/XmlFileSettingsStore.cs
@@ -20,7 +20,10 @@
* along with Process Hacker. If not, see .
*/
+using System;
+using System.Collections.Generic;
using System.IO;
+using System.Text;
using System.Xml;
namespace ProcessHacker.Common.Settings
@@ -34,8 +37,8 @@ public sealed class XmlFileSettingsStore : ISettingsStore
private const string _settingElementName = "setting";
private const string _nameAttributeName = "name";
- private readonly string _fileName;
- private readonly object _docLock = new object();
+ private string _fileName;
+ private object _docLock = new object();
private XmlDocument _doc;
private XmlNode _rootNode;
@@ -80,10 +83,7 @@ public string GetValue(string name)
{
lock (_docLock)
{
- XmlNodeList nodes = _rootNode.SelectNodes(_settingElementName + "[@" + _nameAttributeName + "='" + name + "']");
-
- if (nodes == null)
- return null;
+ var nodes = _rootNode.SelectNodes(_settingElementName + "[@" + _nameAttributeName + "='" + name + "']");
if (nodes.Count == 0)
return null;
@@ -146,16 +146,16 @@ public void SetValue(string name, string value)
{
lock (_docLock)
{
- XmlNodeList nodes = _rootNode.SelectNodes(_settingElementName + "[@" + _nameAttributeName + "='" + name + "']");
+ var nodes = _rootNode.SelectNodes(_settingElementName + "[@" + _nameAttributeName + "='" + name + "']");
- if (nodes != null && nodes.Count != 0)
+ if (nodes.Count != 0)
{
nodes[0].InnerText = value;
}
else
{
- XmlElement settingElement = _doc.CreateElement(_settingElementName);
- XmlAttribute nameAttribute = _doc.CreateAttribute(_nameAttributeName);
+ var settingElement = _doc.CreateElement(_settingElementName);
+ var nameAttribute = _doc.CreateAttribute(_nameAttributeName);
nameAttribute.Value = name;
settingElement.Attributes.Append(nameAttribute);
diff --git a/1.x/trunk/ProcessHacker.Common/String255.cs b/1.x/trunk/ProcessHacker.Common/String255.cs
index b84fb6223..a62f20fb6 100644
--- a/1.x/trunk/ProcessHacker.Common/String255.cs
+++ b/1.x/trunk/ProcessHacker.Common/String255.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Common
{
@@ -108,8 +110,8 @@ public void Append(string str)
fixed (char* buffer = this.Buffer)
{
- foreach (char t in str)
- buffer[this.Length++] = t;
+ for (int i = 0; i < str.Length; i++)
+ buffer[this.Length++] = str[i];
buffer[this.Length] = '\0';
}
@@ -119,11 +121,14 @@ public int CompareTo(String255 str)
{
fixed (char* buffer = this.Buffer)
{
- int result = LibC.WMemCmp(buffer, str.Buffer, this.Length < str.Length ? this.Length : str.Length);
+ int result;
+
+ result = LibC.WMemCmp(buffer, str.Buffer, this.Length < str.Length ? this.Length : str.Length);
if (result == 0)
return this.Length - str.Length;
- return result;
+ else
+ return result;
}
}
@@ -140,9 +145,10 @@ public override bool Equals(object other)
{
if (other is String255)
return this.Equals((String255)other);
- if (other is string)
+ else if (other is string)
return this.Equals((string)other);
- return false;
+ else
+ return false;
}
public bool Equals(String255 other)
@@ -189,8 +195,8 @@ public int IndexOf(char c)
if (ptr != null)
return (int)(ptr - buffer);
-
- return -1;
+ else
+ return -1;
}
}
@@ -198,9 +204,12 @@ public override int GetHashCode()
{
int hashCode = 0x15051505;
- for (int i = 0; i < this.Length; i += 4)
+ fixed (char* buffer = this.Buffer)
{
- hashCode += hashCode ^ (hashCode << ((i % 4) * 8));
+ for (int i = 0; i < this.Length; i += 4)
+ {
+ hashCode += hashCode ^ (hashCode << ((i % 4) * 8));
+ }
}
return hashCode;
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/ActionSync.cs b/1.x/trunk/ProcessHacker.Common/Threading/ActionSync.cs
index d0d7c018c..8c59a7599 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/ActionSync.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/ActionSync.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using System.Threading;
namespace ProcessHacker.Common.Threading
@@ -32,8 +34,8 @@ namespace ProcessHacker.Common.Threading
public struct ActionSync
{
private int _value;
- private readonly int _target;
- private readonly Action _action;
+ private int _target;
+ private Action _action;
///
/// Initializes an action-sync structure.
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/FairResourceLock.cs b/1.x/trunk/ProcessHacker.Common/Threading/FairResourceLock.cs
index 7588a423d..75fb1ff37 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/FairResourceLock.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/FairResourceLock.cs
@@ -21,11 +21,8 @@
*/
#define DEFER_EVENT_CREATION
-
-#if DEBUG
-#define ENABLE_STATISTICS
-#define RIGOROUS_CHECKS
-#endif
+//#define ENABLE_STATISTICS
+//#define RIGOROUS_CHECKS
using System;
using System.Runtime.InteropServices;
@@ -124,18 +121,13 @@ public struct Statistics
public int PeakShrdWtrsCount;
}
- private struct WaitBlock
+ private unsafe struct WaitBlock
{
- public static readonly int SizeOf;
+ public static readonly int Size = Marshal.SizeOf(typeof(WaitBlock));
public WaitBlock* Flink;
public WaitBlock* Blink;
public int Flags;
-
- static WaitBlock()
- {
- SizeOf = Marshal.SizeOf(typeof(WaitBlock));
- }
}
private enum ListPosition
@@ -214,20 +206,20 @@ private static bool RemoveEntryList(WaitBlock* entry)
private WaitBlock* _firstSharedWaiter;
#if ENABLE_STATISTICS
- private int _exclusiveWaitersCount;
- private int _sharedWaitersCount;
-
- private int _acqExclCount;
- private int _acqShrdCount;
- private int _acqExclContCount;
- private int _acqShrdContCount;
- private int _acqExclBlkCount;
- private int _acqShrdBlkCount;
- private int _acqExclSlpCount;
- private int _acqShrdSlpCount;
- private int _insWaitBlkRetryCount;
- private int _peakExclWtrsCount;
- private int _peakShrdWtrsCount;
+ private int _exclusiveWaitersCount = 0;
+ private int _sharedWaitersCount = 0;
+
+ private int _acqExclCount = 0;
+ private int _acqShrdCount = 0;
+ private int _acqExclContCount = 0;
+ private int _acqShrdContCount = 0;
+ private int _acqExclBlkCount = 0;
+ private int _acqShrdBlkCount = 0;
+ private int _acqExclSlpCount = 0;
+ private int _acqShrdSlpCount = 0;
+ private int _insWaitBlkRetryCount = 0;
+ private int _peakExclWtrsCount = 0;
+ private int _peakShrdWtrsCount = 0;
#endif
///
@@ -249,7 +241,7 @@ public FairResourceLock(int spinCount)
_lock = new SpinLock();
_spinCount = Environment.ProcessorCount != 1 ? spinCount : 0;
- _waitersListHead = (WaitBlock*)Marshal.AllocHGlobal(WaitBlock.SizeOf);
+ _waitersListHead = (WaitBlock*)Marshal.AllocHGlobal(WaitBlock.Size);
_waitersListHead->Flink = _waitersListHead;
_waitersListHead->Blink = _waitersListHead;
_waitersListHead->Flags = 0;
@@ -726,7 +718,7 @@ private IntPtr CreateWakeEvent()
public Statistics GetStatistics()
{
#if ENABLE_STATISTICS
- return new Statistics
+ return new Statistics()
{
AcqExcl = _acqExclCount,
AcqShrd = _acqShrdCount,
@@ -1134,7 +1126,7 @@ private void WakeExclusive()
private void WakeShared()
{
WaitBlock wakeList = new WaitBlock();
- WaitBlock* wb;
+ WaitBlock* wb = null;
wakeList.Flink = &wakeList;
wakeList.Blink = &wakeList;
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/FastLock.cs b/1.x/trunk/ProcessHacker.Common/Threading/FastLock.cs
index efc735b7f..4c51e3369 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/FastLock.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/FastLock.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
using System.Threading;
namespace ProcessHacker.Common.Threading
@@ -41,10 +43,13 @@ public void Acquire()
}
// Slow path 2 - wait on the event.
+
+ IntPtr newEvent;
+
// Note: see FastEvent.cs for a more detailed explanation of this
// technique.
- IntPtr newEvent = Interlocked.CompareExchange(ref this._event, IntPtr.Zero, IntPtr.Zero);
+ newEvent = Interlocked.CompareExchange(ref _event, IntPtr.Zero, IntPtr.Zero);
if (newEvent == IntPtr.Zero)
{
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/FastMutex.cs b/1.x/trunk/ProcessHacker.Common/Threading/FastMutex.cs
index 008cc5c5a..5a83cc3c3 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/FastMutex.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/FastMutex.cs
@@ -16,7 +16,7 @@ public sealed class FastMutex
public struct FastMutexContext : IDisposable
{
private bool _disposed;
- private readonly FastMutex _fastMutex;
+ private FastMutex _fastMutex;
internal FastMutexContext(FastMutex fastMutex)
{
@@ -37,7 +37,7 @@ public void Dispose()
}
}
- private readonly object _lock = new object();
+ private object _lock = new object();
///
/// Acquires the mutex and prevents others from acquiring it.
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/FastResourceLock.cs b/1.x/trunk/ProcessHacker.Common/Threading/FastResourceLock.cs
index 3f78ebb86..cdac07d57 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/FastResourceLock.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/FastResourceLock.cs
@@ -21,11 +21,8 @@
*/
#define DEFER_EVENT_CREATION
-
-#if DEBUG
-#define ENABLE_STATISTICS
-#define RIGOROUS_CHECKS
-#endif
+//#define ENABLE_STATISTICS
+//#define RIGOROUS_CHECKS
using System;
using System.Threading;
@@ -201,24 +198,21 @@ public struct Statistics
private IntPtr _exclusiveWakeEvent;
#if ENABLE_STATISTICS
- private int _acqExclCount;
- private int _acqShrdCount;
- private int _acqExclContCount;
- private int _acqShrdContCount;
- private int _acqExclSlpCount;
- private int _acqShrdSlpCount;
- private int _peakExclWtrsCount;
- private int _peakShrdWtrsCount;
+ private int _acqExclCount = 0;
+ private int _acqShrdCount = 0;
+ private int _acqExclContCount = 0;
+ private int _acqShrdContCount = 0;
+ private int _acqExclSlpCount = 0;
+ private int _acqShrdSlpCount = 0;
+ private int _peakExclWtrsCount = 0;
+ private int _peakShrdWtrsCount = 0;
#endif
///
/// Creates a FastResourceLock.
///
public FastResourceLock()
- {
-#if ENABLE_STATISTICS
- this._acqExclContCount = 0;
-#endif
+ {
_value = 0;
#if !DEFER_EVENT_CREATION
@@ -353,8 +347,8 @@ public void AcquireExclusive()
Interlocked2.Set(
ref _peakExclWtrsCount,
- p => p < exclWtrsCount,
- p => exclWtrsCount
+ (p) => p < exclWtrsCount,
+ (p) => exclWtrsCount
);
#endif
@@ -463,8 +457,8 @@ public void AcquireShared()
Interlocked2.Set(
ref _peakShrdWtrsCount,
- p => p < shrdWtrsCount,
- p => shrdWtrsCount
+ (p) => p < shrdWtrsCount,
+ (p) => shrdWtrsCount
);
#endif
@@ -534,10 +528,12 @@ public void ConvertExclusiveToShared()
/// A reference to the event handle.
private void EnsureEventCreated(ref IntPtr handle)
{
+ IntPtr eventHandle;
+
if (Thread.VolatileRead(ref handle) != IntPtr.Zero)
return;
- IntPtr eventHandle = NativeMethods.CreateSemaphore(IntPtr.Zero, 0, int.MaxValue, null);
+ eventHandle = NativeMethods.CreateSemaphore(IntPtr.Zero, 0, int.MaxValue, null);
if (Interlocked.CompareExchange(ref handle, eventHandle, IntPtr.Zero) != IntPtr.Zero)
NativeMethods.CloseHandle(eventHandle);
@@ -551,7 +547,7 @@ private void EnsureEventCreated(ref IntPtr handle)
public Statistics GetStatistics()
{
#if ENABLE_STATISTICS
- return new Statistics
+ return new Statistics()
{
AcqExcl = _acqExclCount,
AcqShrd = _acqShrdCount,
@@ -601,7 +597,9 @@ public void ReleaseExclusive()
// Case 2: if we have shared waiters, release all of them.
else
{
- int sharedWaiters = (value >> LockSharedWaitersShift) & LockSharedWaitersMask;
+ int sharedWaiters;
+
+ sharedWaiters = (value >> LockSharedWaitersShift) & LockSharedWaitersMask;
if (Interlocked.CompareExchange(
ref _value,
@@ -824,17 +822,18 @@ public bool TryAcquireShared()
value
) == value;
}
-
- if (((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 0)
+ else if (((value >> LockSharedOwnersShift) & LockSharedOwnersMask) != 0)
{
return Interlocked.CompareExchange(
- ref this._value,
+ ref _value,
value + LockSharedOwnersIncrement,
value
) == value;
}
-
- return false;
+ else
+ {
+ return false;
+ }
}
///
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/FastStack.cs b/1.x/trunk/ProcessHacker.Common/Threading/FastStack.cs
index 111ab2593..42fd55a71 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/FastStack.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/FastStack.cs
@@ -13,13 +13,8 @@ private class FastStackNode
public FastStackNode Next;
}
- private readonly int _count;
- private FastStackNode _bottom;
-
- public FastStack(int count)
- {
- _count = count;
- }
+ private int _count = 0;
+ private FastStackNode _bottom = null;
public int Count
{
@@ -53,7 +48,7 @@ public T Pop()
throw new InvalidOperationException("The stack is empty.");
// Try to replace the pointer.
- if (Interlocked.CompareExchange(
+ if (Interlocked.CompareExchange>(
ref _bottom,
bottom.Next,
bottom
@@ -68,11 +63,10 @@ public T Pop()
public void Push(T value)
{
FastStackNode bottom;
+ FastStackNode entry;
- FastStackNode entry = new FastStackNode
- {
- Value = value
- };
+ entry = new FastStackNode();
+ entry.Value = value;
// Atomically replace the bottom of the stack.
while (true)
@@ -81,7 +75,7 @@ public void Push(T value)
entry.Next = bottom;
// Try to replace the pointer.
- if (Interlocked.CompareExchange(
+ if (Interlocked.CompareExchange>(
ref _bottom,
entry,
bottom
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/IResourceLock.cs b/1.x/trunk/ProcessHacker.Common/Threading/IResourceLock.cs
index 58bcbdbb1..4d1baaf93 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/IResourceLock.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/IResourceLock.cs
@@ -1,4 +1,8 @@
-namespace ProcessHacker.Common.Threading
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ProcessHacker.Common.Threading
{
public interface IResourceLock
{
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/Interlocked2.cs b/1.x/trunk/ProcessHacker.Common/Threading/Interlocked2.cs
index e46da6230..351838a42 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/Interlocked2.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/Interlocked2.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
using System.Threading;
namespace ProcessHacker.Common.Threading
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/NativeMethods.cs b/1.x/trunk/ProcessHacker.Common/Threading/NativeMethods.cs
index 589f412f5..4697175da 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/NativeMethods.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/NativeMethods.cs
@@ -1,6 +1,8 @@
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
+using System.Text;
namespace ProcessHacker.Common.Threading
{
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/RundownProtection.cs b/1.x/trunk/ProcessHacker.Common/Threading/RundownProtection.cs
index c5c1367d2..7752ee58f 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/RundownProtection.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/RundownProtection.cs
@@ -20,6 +20,7 @@
* along with Process Hacker. If not, see .
*/
+using System;
using System.Threading;
namespace ProcessHacker.Common.Threading
@@ -129,7 +130,9 @@ public void Release()
// Has the rundown already started?
if ((value & RundownActive) != 0)
{
- int newValue = Interlocked.Add(ref this._value, -RundownCountIncrement);
+ int newValue;
+
+ newValue = Interlocked.Add(ref _value, -RundownCountIncrement);
// Are we the last out? Set the event if that's the case.
if (newValue == RundownActive)
@@ -139,13 +142,15 @@ public void Release()
return;
}
-
- if (Interlocked.CompareExchange(
- ref this._value,
- value - RundownCountIncrement,
- value
- ) == value)
- return;
+ else
+ {
+ if (Interlocked.CompareExchange(
+ ref _value,
+ value - RundownCountIncrement,
+ value
+ ) == value)
+ return;
+ }
}
}
@@ -164,7 +169,9 @@ public void Release(int count)
// Has the rundown already started?
if ((value & RundownActive) != 0)
{
- int newValue = Interlocked.Add(ref this._value, -RundownCountIncrement * count);
+ int newValue;
+
+ newValue = Interlocked.Add(ref _value, -RundownCountIncrement * count);
// Are we the last out? Set the event if that's the case.
if (newValue == RundownActive)
@@ -174,13 +181,15 @@ public void Release(int count)
return;
}
-
- if (Interlocked.CompareExchange(
- ref this._value,
- value - RundownCountIncrement * count,
- value
- ) == value)
- return;
+ else
+ {
+ if (Interlocked.CompareExchange(
+ ref _value,
+ value - RundownCountIncrement * count,
+ value
+ ) == value)
+ return;
+ }
}
}
@@ -201,10 +210,12 @@ public void Wait()
/// Whether all references were released.
public bool Wait(int millisecondsTimeout)
{
+ int value;
+
// Fast path. Just in case there are no users, we can go ahead
// and set the active flag and exit. Or if someone has already
// initiated the rundown, exit as well.
- int value = Interlocked.CompareExchange(ref this._value, RundownActive, 0);
+ value = Interlocked.CompareExchange(ref _value, RundownActive, 0);
if (value == 0 || value == RundownActive)
return true;
@@ -222,8 +233,8 @@ public bool Wait(int millisecondsTimeout)
// Wait for the event, but only if we had users.
if ((value & ~RundownActive) != 0)
return _wakeEvent.Wait(millisecondsTimeout);
-
- return true;
+ else
+ return true;
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/SemaphorePair.cs b/1.x/trunk/ProcessHacker.Common/Threading/SemaphorePair.cs
index dd180d8ae..25013a681 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/SemaphorePair.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/SemaphorePair.cs
@@ -5,9 +5,9 @@ namespace ProcessHacker.Common.Threading
{
public class SemaphorePair : IDisposable
{
- private readonly int _count;
- private readonly Semaphore _readSemaphore;
- private readonly Semaphore _writeSemaphore;
+ private int _count;
+ private Semaphore _readSemaphore;
+ private Semaphore _writeSemaphore;
public SemaphorePair(int count)
{
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/ThreadTask.cs b/1.x/trunk/ProcessHacker.Common/Threading/ThreadTask.cs
index 2a15c7011..26ce7310f 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/ThreadTask.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/ThreadTask.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
using System.Threading;
namespace ProcessHacker.Common.Threading
@@ -11,11 +13,11 @@ public sealed class ThreadTask
public event ThreadTaskCompletedDelegate Completed;
public event ThreadTaskRunTaskDelegate RunTask;
- private Thread _thread;
+ private Thread _thread = null;
private object _result;
private Exception _exception;
- private bool _cancelled;
- private bool _running;
+ private bool _cancelled = false;
+ private bool _running = false;
public bool Cancelled
{
@@ -55,10 +57,8 @@ public void Start(object param)
_cancelled = false;
_running = true;
- _thread = new Thread(this.ThreadStart)
- {
- IsBackground = true
- };
+ _thread = new Thread(this.ThreadStart);
+ _thread.IsBackground = true;
_thread.Start(param);
}
diff --git a/1.x/trunk/ProcessHacker.Common/Threading/WaitableQueue.cs b/1.x/trunk/ProcessHacker.Common/Threading/WaitableQueue.cs
index 4d6f2db27..fef78eb7e 100644
--- a/1.x/trunk/ProcessHacker.Common/Threading/WaitableQueue.cs
+++ b/1.x/trunk/ProcessHacker.Common/Threading/WaitableQueue.cs
@@ -1,12 +1,15 @@
-using System.Collections;
+using System;
+using System.Collections;
using System.Collections.Generic;
+using System.Text;
+using System.Threading;
namespace ProcessHacker.Common.Threading
{
- public class WaitableQueue : IEnumerable
+ public class WaitableQueue : IEnumerable, IEnumerable
{
- private readonly Queue _queue = new Queue();
- private readonly SemaphorePair _pair;
+ private Queue _queue = new Queue();
+ private SemaphorePair _pair;
public WaitableQueue()
: this(int.MaxValue)
@@ -47,8 +50,10 @@ public T Dequeue()
public bool Dequeue(int timeout, out T item)
{
+ bool waitResult = true;
+
// Wait for an item to dequeue.
- bool waitResult = _pair.WaitRead(timeout);
+ waitResult = _pair.WaitRead(timeout);
// Dequeue an item if we waited successfully,
// otherwise pass the default value back.
diff --git a/1.x/trunk/ProcessHacker.Common/Tokenizer.cs b/1.x/trunk/ProcessHacker.Common/Tokenizer.cs
index 425ab979b..c21ef4a28 100644
--- a/1.x/trunk/ProcessHacker.Common/Tokenizer.cs
+++ b/1.x/trunk/ProcessHacker.Common/Tokenizer.cs
@@ -5,8 +5,8 @@ namespace ProcessHacker.Common
{
public class Tokenizer
{
- private readonly string _text;
- private int _i;
+ private string _text;
+ private int _i = 0;
public Tokenizer(string text)
{
@@ -90,7 +90,7 @@ public string EatQuotedString()
_i++;
}
else
- return string.Empty;
+ return "";
while (_i < _text.Length)
{
@@ -102,29 +102,20 @@ public string EatQuotedString()
}
else if (inEscape)
{
- switch (this._text[this._i])
- {
- case '\\':
- sb.Append('\\');
- break;
- case '"':
- sb.Append('"');
- break;
- case '\'':
- sb.Append('\'');
- break;
- case 'r':
- sb.Append('\r');
- break;
- case 'n':
- sb.Append('\n');
- break;
- case 't':
- sb.Append('\t');
- break;
- default:
- throw new Exception("Unrecognized escape sequence '\\" + this._text[this._i] + "'");
- }
+ if (_text[_i] == '\\')
+ sb.Append('\\');
+ else if (_text[_i] == '"')
+ sb.Append('"');
+ else if (_text[_i] == '\'')
+ sb.Append('\'');
+ else if (_text[_i] == 'r')
+ sb.Append('\r');
+ else if (_text[_i] == 'n')
+ sb.Append('\n');
+ else if (_text[_i] == 't')
+ sb.Append('\t');
+ else
+ throw new Exception("Unrecognized escape sequence '\\" + _text[_i] + "'");
_i++;
inEscape = false;
diff --git a/1.x/trunk/ProcessHacker.Common/Ui/ColumnHeaderExtensions.cs b/1.x/trunk/ProcessHacker.Common/Ui/ColumnHeaderExtensions.cs
index c7e812784..cef6c409d 100644
--- a/1.x/trunk/ProcessHacker.Common/Ui/ColumnHeaderExtensions.cs
+++ b/1.x/trunk/ProcessHacker.Common/Ui/ColumnHeaderExtensions.cs
@@ -10,7 +10,7 @@ namespace ProcessHacker.Common.Ui
public static class ColumnHeaderExtensions
{
[StructLayout(LayoutKind.Sequential)]
- public struct LVCOLUMN
+ private struct LVCOLUMN
{
public Int32 mask;
public Int32 cx;
@@ -45,13 +45,11 @@ public static void SetSortIcon(this ColumnHeader column, SortOrder order)
for (int i = 0; i <= listView.Columns.Count - 1; i++)
{
IntPtr ColumnPtr = new IntPtr(i);
- LVCOLUMN lvColumn = new LVCOLUMN
- {
- mask = HDI_FORMAT
- };
+ LVCOLUMN lvColumn = new LVCOLUMN();
+ lvColumn.mask = HDI_FORMAT;
SendMessage(columnHeader, HDM_GETITEM, ColumnPtr, ref lvColumn);
- if (order != SortOrder.None && i == column.Index)
+ if (!(order == SortOrder.None) && i == column.Index)
{
switch (order)
{
diff --git a/1.x/trunk/ProcessHacker.Common/Ui/SortedListViewComparer.cs b/1.x/trunk/ProcessHacker.Common/Ui/SortedListViewComparer.cs
index 9aadbdff8..588d1298c 100644
--- a/1.x/trunk/ProcessHacker.Common/Ui/SortedListViewComparer.cs
+++ b/1.x/trunk/ProcessHacker.Common/Ui/SortedListViewComparer.cs
@@ -43,19 +43,26 @@ public class SortedListViewComparer : IComparer
{
private class DefaultComparer : ISortedListViewComparer
{
+ private SortedListViewComparer _sortedListComparer;
+
+ public DefaultComparer(SortedListViewComparer sortedListComparer)
+ {
+ _sortedListComparer = sortedListComparer;
+ }
+
public int Compare(ListViewItem x, ListViewItem y, int column)
{
string sx, sy;
long ix, iy;
IComparable cx, cy;
- sx = x.SubItems[column].Text.Replace(",", string.Empty);
- sy = y.SubItems[column].Text.Replace(",", string.Empty);
+ sx = x.SubItems[column].Text.Replace(",", "");
+ sy = y.SubItems[column].Text.Replace(",", "");
- if (!long.TryParse(sx.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? sx.Substring(2) : sx,
+ if (!long.TryParse(sx.StartsWith("0x") ? sx.Substring(2) : sx,
sx.StartsWith("0x") ? NumberStyles.AllowHexSpecifier : 0,
null, out ix) ||
- !long.TryParse(sy.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? sy.Substring(2) : sy,
+ !long.TryParse(sy.StartsWith("0x") ? sy.Substring(2) : sy,
sy.StartsWith("0x") ? NumberStyles.AllowHexSpecifier : 0,
null, out iy))
{
@@ -72,17 +79,17 @@ public int Compare(ListViewItem x, ListViewItem y, int column)
}
}
- private readonly ListView _list;
- private bool _virtualMode;
+ private ListView _list;
+ private bool _virtualMode = false;
private RetrieveVirtualItemEventHandler _retrieveVirtualItem;
- private bool _triState;
+ private bool _triState = false;
private ISortedListViewComparer _comparer;
private ISortedListViewComparer _triStateComparer;
private int _sortColumn;
private SortOrder _sortOrder;
- private readonly Dictionary> _customSorters =
+ private Dictionary> _customSorters =
new Dictionary>();
- private readonly List _columnSortOrder = new List();
+ private List _columnSortOrder = new List();
///
/// Creates a new sorted list manager.
@@ -91,10 +98,10 @@ public int Compare(ListViewItem x, ListViewItem y, int column)
public SortedListViewComparer(ListView list)
{
_list = list;
- _list.ColumnClick += this.list_ColumnClick;
+ _list.ColumnClick += new ColumnClickEventHandler(list_ColumnClick);
_sortColumn = 0;
_sortOrder = SortOrder.Ascending;
- _comparer = new DefaultComparer();
+ _comparer = new DefaultComparer(this);
this.SetSortIcon();
}
@@ -135,7 +142,7 @@ public ISortedListViewComparer Comparer
set
{
if (value == null)
- _comparer = new DefaultComparer();
+ _comparer = new DefaultComparer(this);
else
_comparer = value;
}
@@ -229,20 +236,31 @@ private void SetSortIcon()
// Avoid forcing handle creation before all other initialization
// has finished. This is done by handling the Layout event and
// performing the icon setting there.
- _list.DoDelayed(control => _list.Columns[_sortColumn].SetSortIcon(_sortOrder));
+ _list.DoDelayed((control) => _list.Columns[_sortColumn].SetSortIcon(_sortOrder));
}
- private int ModifySort(int result, SortOrder order)
+ private ListViewItem GetItem(int index)
{
- switch (order)
+ if (_virtualMode)
{
- case SortOrder.Ascending:
- return result;
- case SortOrder.Descending:
- return -result;
- default:
- return result;
+ var args = new RetrieveVirtualItemEventArgs(index);
+ _retrieveVirtualItem(this, args);
+ return args.Item;
}
+ else
+ {
+ return _list.Items[index];
+ }
+ }
+
+ private int ModifySort(int result, SortOrder order)
+ {
+ if (order == SortOrder.Ascending)
+ return result;
+ else if (order == SortOrder.Descending)
+ return -result;
+ else
+ return result;
}
private int Compare(ListViewItem x, ListViewItem y, int column)
diff --git a/1.x/trunk/ProcessHacker.Common/Utils.cs b/1.x/trunk/ProcessHacker.Common/Utils.cs
index 718ebe4e7..b1f296a63 100644
--- a/1.x/trunk/ProcessHacker.Common/Utils.cs
+++ b/1.x/trunk/ProcessHacker.Common/Utils.cs
@@ -25,6 +25,7 @@
using System.Drawing;
using System.IO;
using System.Reflection;
+using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
@@ -70,6 +71,8 @@ public enum Endianness
///
public static int UnitSpecifier = 4;
+ private static PropertyInfo _doubleBufferedProperty;
+
///
/// Aligns a number to the specified power-of-two alignment value.
///
@@ -130,7 +133,7 @@ public static T[] Concat(params T[][] ap)
/// True if the array contains the value, otherwise false.
public static bool Contains(this T[] array, T value)
{
- return Array.IndexOf(array, value) != -1;
+ return Array.IndexOf(array, value) != -1;
}
///
@@ -195,8 +198,8 @@ public static string CreateEllipsis(string s, int len)
{
if (s.Length <= len)
return s;
-
- return s.Substring(0, len - 4) + " ...";
+ else
+ return s.Substring(0, len - 4) + " ...";
}
///
@@ -215,11 +218,24 @@ public static string CreateRandomString(int length)
return sb.ToString();
}
+ ///
+ /// Clears and cleans up resources held by the menu items.
+ ///
+ public static void DisposeAndClear(this Menu.MenuItemCollection items)
+ {
+ //foreach (MenuItem item in items)
+ //{
+ // item.Dispose();
+ //}
+
+ items.Clear();
+ }
+
///
/// Disables the menu items contained in the specified menu.
///
/// The menu.
- public static void DisableAllMenuItems(MenuItem menu)
+ public static void DisableAllMenuItems(Menu menu)
{
foreach (MenuItem item in menu.MenuItems)
item.Enabled = false;
@@ -228,7 +244,7 @@ public static void DisableAllMenuItems(MenuItem menu)
///
/// Disables all menu items.
///
- public static void DisableAll(this MenuItem menu)
+ public static void DisableAll(this Menu menu)
{
DisableAllMenuItems(menu);
}
@@ -521,7 +537,7 @@ public static string FormatRelativeDateTime(DateTime time)
double months = span.TotalDays * 12 / 365;
double years = months / 12;
double centuries = years / 100;
- string str;
+ string str = "";
// Start from the most general time unit and see if they can be used
// without any fractional component.
@@ -577,7 +593,7 @@ public static string FormatRelativeDateTime(DateTime time)
str = "a very short time";
// Turn 1 into "a", e.g. 1 minute -> a minute
- if (str.StartsWith("1 ", StringComparison.OrdinalIgnoreCase))
+ if (str.StartsWith("1 "))
{
// Special vowel case: a hour -> an hour
if (str[2] != 'h')
@@ -605,7 +621,7 @@ public static string FormatSize(int size)
public static string FormatSize(uint size)
{
int i = 0;
- double s = size;
+ double s = (double)size;
while (s > 1024 && i < SizeUnitNames.Length && i < UnitSpecifier)
{
@@ -644,7 +660,7 @@ public static string FormatSize(long size)
public static string FormatSize(ulong size)
{
int i = 0;
- double s = size;
+ double s = (double)size;
while (s > 1024 && i < SizeUnitNames.Length && i < UnitSpecifier)
{
@@ -708,7 +724,7 @@ public static DateTime GetAssemblyBuildDate(Assembly assembly, bool forceFileDat
// The last write time of the assembly, or DateTime.MaxValue if an exception occurred.
public static DateTime GetAssemblyLastWriteTime(Assembly assembly)
{
- if (string.IsNullOrEmpty(assembly.Location))
+ if (assembly.Location == null || assembly.Location == "")
return DateTime.MaxValue;
try
@@ -824,10 +840,10 @@ public static int GetPrime(int minimum)
if (minimum < 0)
throw new ArgumentOutOfRangeException("minimum");
- foreach (int t in Primes)
+ for (int i = 0; i < Primes.Length; i++)
{
- if (t >= minimum)
- return t;
+ if (Primes[i] >= minimum)
+ return Primes[i];
}
for (int i = minimum | 1; i < int.MaxValue; i += 2)
@@ -936,8 +952,8 @@ public static char MakePrintable(char c)
{
if (c >= ' ' && c <= '~')
return c;
-
- return '.';
+ else
+ return '.';
}
///
@@ -949,8 +965,8 @@ public static string MakePrintable(string s)
{
StringBuilder sb = new StringBuilder();
- foreach (char t in s)
- sb.Append(MakePrintable(t));
+ for (int i = 0; i < s.Length; i++)
+ sb.Append(MakePrintable(s[i]));
return sb.ToString();
}
@@ -1043,7 +1059,7 @@ public static Dictionary ParseCommandLine(string[] args)
foreach (string s in args)
{
- if (s.StartsWith("-", StringComparison.OrdinalIgnoreCase))
+ if (s.StartsWith("-"))
{
if (dict.ContainsKey(s))
throw new ArgumentException("Option already specified.");
@@ -1108,7 +1124,7 @@ public static string ReadString(Stream s, int length)
if (s.Read(buffer, 0, length) == 0)
throw new EndOfStreamException();
- return Encoding.ASCII.GetString(buffer);
+ return System.Text.Encoding.ASCII.GetString(buffer);
}
public static uint ReadUInt32(Stream s, Endianness type)
@@ -1145,7 +1161,7 @@ public static string ReadUnicodeString(Stream s)
if (b == 0 && b2 == 0)
break;
- str.Append(Encoding.Unicode.GetChars(new[] { (byte)b, (byte)b2 }));
+ str.Append(Encoding.Unicode.GetChars(new byte[] { (byte)b, (byte)b2 }));
}
return str.ToString();
@@ -1174,7 +1190,7 @@ public static string ReadUnicodeString(Stream s, int length)
if (b2 == -1)
break;
- str.Append(Encoding.Unicode.GetChars(new[] { (byte)b, (byte)b2 }));
+ str.Append(Encoding.Unicode.GetChars(new byte[] { (byte)b, (byte)b2 }));
i += 2;
}
@@ -1298,6 +1314,35 @@ public static void SelectAll(this ListView items)
}
}
+ ///
+ /// Enables or disables double buffering for a control.
+ ///
+ /// The control.
+ /// The type of the control.
+ /// The new setting.
+ public static void SetDoubleBuffered(this Control c, Type t, bool value)
+ {
+ PropertyInfo doubleBufferedProperty = _doubleBufferedProperty;
+
+ if (doubleBufferedProperty == null)
+ {
+ _doubleBufferedProperty = doubleBufferedProperty = t.GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance);
+ }
+
+ doubleBufferedProperty.SetValue(c, value, null);
+ }
+
+ ///
+ /// Enables or disables double buffering for a control.
+ ///
+ /// The control to set the property on.
+ /// The new value.
+ public static void SetDoubleBuffered(this Control c, bool value)
+ {
+ c.SetDoubleBuffered(c.GetType(), value);
+ }
+
///
/// Shows a file in Windows Explorer.
///
@@ -1310,13 +1355,23 @@ public static void ShowFileInExplorer(string fileName)
///
/// Calculates the size of a structure.
///
+ /// The structure type.
+ /// The size of the structure.
+ public static int SizeOf()
+ {
+ return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
+ }
+
+ ///
+ /// Calculates the size of a structure.
+ ///
+ /// The structure type.
/// A power-of-two whole-structure alignment to apply.
- ///
/// The size of the structure.
- public static int SizeOf(int alignment, int size)
+ public static int SizeOf(int alignment)
{
// HACK: This is wrong, but it works.
- return size + alignment;
+ return SizeOf() + alignment;
}
///
@@ -1381,14 +1436,17 @@ public static int ToInt32(this byte[] data)
public static int ToInt32(this byte[] data, Endianness type)
{
- switch (type)
+ if (type == Endianness.Little)
{
- case Endianness.Little:
- return (data[0]) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
- case Endianness.Big:
- return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3]);
- default:
- throw new ArgumentException();
+ return (data[0]) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
+ }
+ else if (type == Endianness.Big)
+ {
+ return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3]);
+ }
+ else
+ {
+ throw new ArgumentException();
}
}
@@ -1399,16 +1457,19 @@ public static long ToInt64(this byte[] data)
public static long ToInt64(this byte[] data, Endianness type)
{
- switch (type)
+ if (type == Endianness.Little)
+ {
+ return (data[0]) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24) |
+ (data[4] << 32) | (data[5] << 40) | (data[6] << 48) | (data[7] << 56);
+ }
+ else if (type == Endianness.Big)
{
- case Endianness.Little:
- return (data[0]) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24) |
- (data[4] << 32) | (data[5] << 40) | (data[6] << 48) | (data[7] << 56);
- case Endianness.Big:
- return (data[0] << 56) | (data[1] << 48) | (data[2] << 40) | (data[3] << 32) |
- (data[4] << 24) | (data[5] << 16) | (data[6] << 8) | (data[7]);
- default:
- throw new ArgumentException();
+ return (data[0] << 56) | (data[1] << 48) | (data[2] << 40) | (data[3] << 32) |
+ (data[4] << 24) | (data[5] << 16) | (data[6] << 8) | (data[7]);
+ }
+ else
+ {
+ throw new ArgumentException();
}
}
@@ -1417,15 +1478,12 @@ public static IntPtr ToIntPtr(this byte[] data)
if (IntPtr.Size != data.Length)
throw new ArgumentException("data");
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(data.ToInt32(Endianness.Little));
- case sizeof(long):
- return new IntPtr(data.ToInt64(Endianness.Little));
- default:
- throw new ArgumentException("data");
- }
+ if (IntPtr.Size == sizeof(int))
+ return new IntPtr(data.ToInt32(Endianness.Little));
+ else if (IntPtr.Size == sizeof(long))
+ return new IntPtr(data.ToInt64(Endianness.Little));
+ else
+ throw new ArgumentException("data");
}
public static ushort ToUInt16(this byte[] data, Endianness type)
@@ -1435,14 +1493,17 @@ public static ushort ToUInt16(this byte[] data, Endianness type)
public static ushort ToUInt16(this byte[] data, int offset, Endianness type)
{
- switch (type)
+ if (type == Endianness.Little)
+ {
+ return (ushort)(data[offset] | (data[offset + 1] << 8));
+ }
+ else if (type == Endianness.Big)
{
- case Endianness.Little:
- return (ushort)(data[offset] | (data[offset + 1] << 8));
- case Endianness.Big:
- return (ushort)((data[offset] << 8) | data[offset + 1]);
- default:
- throw new ArgumentException();
+ return (ushort)((data[offset] << 8) | data[offset + 1]);
+ }
+ else
+ {
+ throw new ArgumentException();
}
}
@@ -1453,16 +1514,19 @@ public static uint ToUInt32(this byte[] data, Endianness type)
public static uint ToUInt32(this byte[] data, int offset, Endianness type)
{
- switch (type)
+ if (type == Endianness.Little)
+ {
+ return (uint)(data[offset]) | (uint)(data[offset + 1] << 8) |
+ (uint)(data[offset + 2] << 16) | (uint)(data[offset + 3] << 24);
+ }
+ else if (type == Endianness.Big)
{
- case Endianness.Little:
- return (uint)(data[offset]) | (uint)(data[offset + 1] << 8) |
- (uint)(data[offset + 2] << 16) | (uint)(data[offset + 3] << 24);
- case Endianness.Big:
- return (uint)(data[offset] << 24) | (uint)(data[offset + 1] << 16) |
- (uint)(data[offset + 2] << 8) | (uint)(data[offset + 3]);
- default:
- throw new ArgumentException();
+ return (uint)(data[offset] << 24) | (uint)(data[offset + 1] << 16) |
+ (uint)(data[offset + 2] << 8) | (uint)(data[offset + 3]);
+ }
+ else
+ {
+ throw new ArgumentException();
}
}
@@ -1485,7 +1549,7 @@ public static void ValidateBuffer(byte[] buffer, int offset, int length, bool ca
if (buffer != null)
{
if (buffer.Length - offset < length)
- throw new ArgumentOutOfRangeException("buffer", "The buffer is too small for the specified offset and length.");
+ throw new ArgumentOutOfRangeException("The buffer is too small for the specified offset and length.");
}
else
{
@@ -1494,7 +1558,7 @@ public static void ValidateBuffer(byte[] buffer, int offset, int length, bool ca
// We don't have a buffer, so make sure the offset and length are zero.
if (offset != 0 || length != 0)
- throw new ArgumentOutOfRangeException("offset", "The offset and length must be zero for a null buffer.");
+ throw new ArgumentOutOfRangeException("The offset and length must be zero for a null buffer.");
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/WeakReference.cs b/1.x/trunk/ProcessHacker.Common/WeakReference.cs
new file mode 100644
index 000000000..a7d0bece0
--- /dev/null
+++ b/1.x/trunk/ProcessHacker.Common/WeakReference.cs
@@ -0,0 +1,39 @@
+using System;
+
+namespace ProcessHacker.Common
+{
+ public class WeakReference
+ where T : class
+ {
+ public static implicit operator T(WeakReference reference)
+ {
+ return reference.Target;
+ }
+
+ private WeakReference _weakReference;
+
+ public WeakReference(T obj)
+ : this(obj, false)
+ { }
+
+ public WeakReference(T obj, bool trackResurrection)
+ {
+ _weakReference = new WeakReference(obj, trackResurrection);
+ }
+
+ public bool Alive
+ {
+ get { return _weakReference.IsAlive; }
+ }
+
+ public bool TrackResurrection
+ {
+ get { return _weakReference.TrackResurrection; }
+ }
+
+ public T Target
+ {
+ get { return _weakReference.Target as T; }
+ }
+ }
+}
diff --git a/1.x/trunk/ProcessHacker.Common/WorkQueue.cs b/1.x/trunk/ProcessHacker.Common/WorkQueue.cs
index 4d2f93b76..b37f82208 100644
--- a/1.x/trunk/ProcessHacker.Common/WorkQueue.cs
+++ b/1.x/trunk/ProcessHacker.Common/WorkQueue.cs
@@ -37,10 +37,10 @@ public sealed class WorkQueue
///
public sealed class WorkItem
{
- private readonly WorkQueue _owner;
- private readonly string _tag;
- private readonly Delegate _work;
- private readonly object[] _args;
+ private WorkQueue _owner;
+ private string _tag;
+ private Delegate _work;
+ private object[] _args;
private bool _enabled = true;
private FastEvent _completedEvent = new FastEvent(false);
private object _result;
@@ -175,7 +175,7 @@ public bool WaitOne(int timeout)
}
}
- private static readonly WorkQueue _globalWorkQueue = new WorkQueue();
+ private static WorkQueue _globalWorkQueue = new WorkQueue();
///
/// Gets the global work queue instance.
@@ -228,7 +228,7 @@ public static WorkItem GlobalQueueWorkItemTag(Delegate work, string tag, params
///
/// The work queue. This object is used as a lock.
///
- private readonly Queue _workQueue = new Queue();
+ private Queue _workQueue = new Queue();
///
/// The maximum number of worker threads. If there are less worker threads
/// than this limit, they will be created as necessary. If there are more
@@ -241,15 +241,15 @@ public static WorkItem GlobalQueueWorkItemTag(Delegate work, string tag, params
/// as necessary and the number of worker threads will never drop below
/// this number.
///
- private int _minWorkerThreads;
+ private int _minWorkerThreads = 0;
///
/// The pool of worker threads. This object is used as a lock.
///
- private readonly Dictionary _workerThreads = new Dictionary();
+ private Dictionary _workerThreads = new Dictionary();
///
/// The number of worker threads which are currently running work.
///
- private int _busyCount;
+ private int _busyCount = 0;
///
/// A worker will block on the work-arrived event for this amount of time
/// before terminating.
@@ -258,7 +258,13 @@ public static WorkItem GlobalQueueWorkItemTag(Delegate work, string tag, params
///
/// If true, prevents new work items from being queued.
///
- private volatile bool _isJoining;
+ private volatile bool _isJoining = false;
+
+ ///
+ /// Creates a new work queue.
+ ///
+ public WorkQueue()
+ { }
///
/// Gets the number of worker threads that are currently busy.
@@ -336,11 +342,9 @@ public void CreateMinimumWorkerThreads()
///
private void CreateWorkerThread()
{
- Thread workThread = new Thread(this.WorkerThreadStart, Utils.SixteenthStackSize)
- {
- IsBackground = true,
- Priority = ThreadPriority.Lowest
- };
+ Thread workThread = new Thread(this.WorkerThreadStart, Utils.SixteenthStackSize);
+ workThread.IsBackground = true;
+ workThread.Priority = ThreadPriority.Lowest;
workThread.SetApartmentState(ApartmentState.STA);
_workerThreads.Add(workThread.ManagedThreadId, workThread);
workThread.Start();
@@ -374,7 +378,7 @@ public void JoinAll()
// Check for work items.
while (_workQueue.Count > 0)
{
- WorkItem workItem;
+ WorkItem workItem = null;
// Lock and re-check.
lock (_workQueue)
@@ -407,8 +411,11 @@ public bool RemoveQueuedWorkItem(WorkItem workItem)
workItem.Enabled = false;
return true;
}
- // The work item is no longer in the queue.
- return false;
+ else
+ {
+ // The work item is no longer in the queue.
+ return false;
+ }
}
}
@@ -528,7 +535,7 @@ private void WorkerThreadStart()
// Check for work.
if (_workQueue.Count > 0)
{
- WorkItem workItem;
+ WorkItem workItem = null;
// There is work, but we must lock and re-check.
lock (_workQueue)
@@ -546,7 +553,7 @@ private void WorkerThreadStart()
else
{
// No work available. Wait for work.
- bool workArrived;
+ bool workArrived = false;
lock (_workQueue)
workArrived = Monitor.Wait(_workQueue, _noWorkTimeout);
@@ -556,14 +563,17 @@ private void WorkerThreadStart()
// Work arrived. Go back so we can perform it.
continue;
}
- // No work arrived during the timeout period. Delete the thread.
- lock (this._workerThreads)
+ else
{
- // Check the minimum.
- if (this._workerThreads.Count > this._minWorkerThreads)
+ // No work arrived during the timeout period. Delete the thread.
+ lock (_workerThreads)
{
- this.DestroyWorkerThread();
- return;
+ // Check the minimum.
+ if (_workerThreads.Count > _minWorkerThreads)
+ {
+ this.DestroyWorkerThread();
+ return;
+ }
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Common/app.config b/1.x/trunk/ProcessHacker.Common/app.config
index b4ca687d2..89dc7d426 100644
--- a/1.x/trunk/ProcessHacker.Common/app.config
+++ b/1.x/trunk/ProcessHacker.Common/app.config
@@ -1,3 +1,3 @@
-
+
diff --git a/1.x/trunk/ProcessHacker.Native/Api/Enums.cs b/1.x/trunk/ProcessHacker.Native/Api/Enums.cs
index 2cdd47e6e..825d1dbc6 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/Enums.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/Enums.cs
@@ -179,7 +179,7 @@ public enum FileCreationDispositionWin32 : uint
TruncateExisting = 5
}
- public enum GdiBlendMode
+ public enum GdiBlendMode : int
{
Black = 1,
NotMergePen,
@@ -200,7 +200,7 @@ public enum GdiBlendMode
Last
}
- public enum GdiPenStyle
+ public enum GdiPenStyle : int
{
Solid = 0,
Dash,
@@ -213,7 +213,7 @@ public enum GdiPenStyle
Alternate
}
- public enum GdiStockObject
+ public enum GdiStockObject : int
{
WhiteBrush = 0,
LightGrayBrush,
@@ -236,7 +236,7 @@ public enum GdiStockObject
DcPen
}
- public enum GetWindowLongOffset
+ public enum GetWindowLongOffset : int
{
WndProc = -4,
HInstance = -6,
@@ -248,14 +248,14 @@ public enum GetWindowLongOffset
}
[Flags]
- public enum HeapEntry32Flags
+ public enum HeapEntry32Flags : int
{
Fixed = 0x00000001,
Free = 0x00000002,
Moveable = 0x00000004
}
- public enum LoadImageType
+ public enum LoadImageType : int
{
Bitmap = 0,
Icon = 1,
@@ -308,14 +308,14 @@ public enum MemoryState : uint
LargePages = 0x20000000
}
- public enum MemoryType
+ public enum MemoryType : int
{
Image = 0x1000000,
Mapped = 0x40000,
Private = 0x20000
}
- public enum MibTcpState
+ public enum MibTcpState : int
{
Closed = 1,
Listening = 2,
@@ -331,7 +331,6 @@ public enum MibTcpState
DeleteTcb = 12
}
- [Flags]
public enum MinidumpType : uint
{
Normal = 0x00000000,
@@ -457,41 +456,6 @@ public enum ProcessPriorityClassWin32 : int
AboveNormal = 0x8000
}
- [Flags]
- public enum PropSheetPageFlags
- {
- Default = 0x0,
- DlgIndirect = 0x1,
- UseHIcon = 0x2,
- UseIconID = 0x4,
- UseTitle = 0x8,
- RtlReading = 0x10,
-
- HasHelp = 0x20,
- UseRefParent = 0x40,
- UseCallback = 0x80,
- Premature = 0x400,
-
- HideHeader = 0x800,
- UseHeaderTitle = 0x1000,
- UseHeaderSubTitle = 0x2000,
- UseFusionContext = 0x4000
- }
-
- public enum PropSheetPageCallbackMessage
- {
- AddRef = 0,
- Release = 1,
- Create = 2
- }
-
- public enum PropSheetNotification : uint
- {
- First = ~200u + 1, // -200
- SetActive = First - 0,
- KillActive = First - 1
- }
-
[Flags]
public enum RedrawWindowFlags
{
diff --git a/1.x/trunk/ProcessHacker.Native/Api/Extensions.cs b/1.x/trunk/ProcessHacker.Native/Api/Extensions.cs
index cbbe8f5d9..b7a636607 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/Extensions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/Extensions.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -29,7 +30,7 @@ namespace ProcessHacker.Native
{
public static class NativeExtensions
{
- private static bool NphNotAvailable;
+ private static bool NphNotAvailable = false;
public static ObjectBasicInformation GetBasicInfo(this SystemHandleEntry thisHandle)
{
@@ -41,34 +42,39 @@ public static ObjectBasicInformation GetBasicInfo(this SystemHandleEntry thisHan
public static ObjectBasicInformation GetBasicInfo(this SystemHandleEntry thisHandle, ProcessHandle process)
{
+ NtStatus status = NtStatus.Success;
IntPtr handle = new IntPtr(thisHandle.Handle);
IntPtr objectHandleI;
GenericHandle objectHandle = null;
int retLength;
+ int baseAddress;
- Win32.NtDuplicateObject(
- process,
- handle,
- ProcessHandle.Current,
- out objectHandleI,
- 0,
- 0,
- 0
- ).ThrowIf();
-
- try
+ if (KProcessHacker.Instance == null)
{
+ if ((status = Win32.NtDuplicateObject(
+ process, handle, ProcessHandle.Current, out objectHandleI, 0, 0, 0)) >= NtStatus.Error)
+ Win32.Throw();
+
objectHandle = new GenericHandle(objectHandleI);
+ }
- using (MemoryAlloc data = new MemoryAlloc(ObjectBasicInformation.SizeOf))
+ try
+ {
+ using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(ObjectBasicInformation))))
{
- Win32.NtQueryObject(
- objectHandle,
- ObjectInformationClass.ObjectBasicInformation,
- data,
- data.Size,
- out retLength
- ).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectBasicInformation,
+ data, data.Size, out retLength, out baseAddress);
+ }
+ else
+ {
+ status = Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectBasicInformation,
+ data, data.Size, out retLength);
+ }
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return data.ReadStruct();
}
@@ -91,49 +97,62 @@ public static string GetName(this ClientId clientId, bool includeThread)
if (includeThread)
{
- if (!string.IsNullOrEmpty(processName))
- return processName + " (" + clientId.ProcessId.ToString() + "): " + clientId.ThreadId.ToString();
-
- return "Non-existent process (" + clientId.ProcessId.ToString() + "): " + clientId.ThreadId.ToString();
+ if (processName != null)
+ return processName + " (" + clientId.ProcessId.ToString() + "): " +
+ clientId.ThreadId.ToString();
+ else
+ return "Non-existent process (" + clientId.ProcessId.ToString() + "): " +
+ clientId.ThreadId.ToString();
+ }
+ else
+ {
+ if (processName != null)
+ return processName + " (" + clientId.ProcessId.ToString() + ")";
+ else
+ return "Non-existent process (" + clientId.ProcessId.ToString() + ")";
}
-
- if (!string.IsNullOrEmpty(processName))
- return processName + " (" + clientId.ProcessId.ToString() + ")";
-
- return "Non-existent process (" + clientId.ProcessId.ToString() + ")";
}
private static string GetObjectNameNt(ProcessHandle process, IntPtr handle, GenericHandle dupHandle)
{
int retLength;
+ int baseAddress = 0;
- Win32.NtQueryObject(
- dupHandle,
- ObjectInformationClass.ObjectNameInformation,
- IntPtr.Zero,
- 0,
- out retLength
- );
+ if (KProcessHacker.Instance != null)
+ {
+ KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectNameInformation,
+ IntPtr.Zero, 0, out retLength, out baseAddress);
+ }
+ else
+ {
+ Win32.NtQueryObject(dupHandle, ObjectInformationClass.ObjectNameInformation,
+ IntPtr.Zero, 0, out retLength);
+ }
if (retLength > 0)
{
using (MemoryAlloc oniMem = new MemoryAlloc(retLength))
{
- Win32.NtQueryObject(
- dupHandle,
- ObjectInformationClass.ObjectNameInformation,
- oniMem,
- oniMem.Size,
- out retLength
- ).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ if (KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectNameInformation,
+ oniMem, oniMem.Size, out retLength, out baseAddress) >= NtStatus.Error)
+ throw new Exception("ZwQueryObject failed.");
+ }
+ else
+ {
+ if (Win32.NtQueryObject(dupHandle, ObjectInformationClass.ObjectNameInformation,
+ oniMem, oniMem.Size, out retLength) >= NtStatus.Error)
+ throw new Exception("NtQueryObject failed.");
+ }
- ObjectNameInformation oni = oniMem.ReadStruct();
- UnicodeString str = oni.Name;
+ var oni = oniMem.ReadStruct();
+ var str = oni.Name;
- //if (KProcessHacker.Instance != null)
- //str.Buffer = str.Buffer.Increment(oniMem.Memory.Decrement(baseAddress));
+ if (KProcessHacker.Instance != null)
+ str.Buffer = str.Buffer.Increment(oniMem.Memory.Decrement(baseAddress));
- return str.Text;
+ return str.Read();
}
}
@@ -147,7 +166,8 @@ public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle)
public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle, bool getName)
{
- using (ProcessHandle process = new ProcessHandle(thisHandle.ProcessId, ProcessAccess.DupHandle))
+ using (ProcessHandle process = new ProcessHandle(thisHandle.ProcessId,
+ KProcessHacker.Instance != null ? OSVersion.MinProcessQueryInfoAccess : ProcessAccess.DupHandle))
{
return thisHandle.GetHandleInfo(process, getName);
}
@@ -162,24 +182,20 @@ public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle,
{
IntPtr handle = new IntPtr(thisHandle.Handle);
IntPtr objectHandleI;
- int retLength;
+ int retLength = 0;
GenericHandle objectHandle = null;
if (thisHandle.Handle == 0 || thisHandle.Handle == -1 || thisHandle.Handle == -2)
throw new WindowsException(NtStatus.InvalidHandle);
// Duplicate the handle if we're not using KPH
- //if (KProcessHacker.Instance == null)
+ if (KProcessHacker.Instance == null)
{
- Win32.NtDuplicateObject(
- process,
- handle,
- ProcessHandle.Current,
- out objectHandleI,
- 0,
- 0,
- 0
- ).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtDuplicateObject(
+ process, handle, ProcessHandle.Current, out objectHandleI, 0, 0, 0)) >= NtStatus.Error)
+ Win32.Throw(status);
objectHandle = new GenericHandle(objectHandleI);
}
@@ -202,35 +218,45 @@ public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle,
Windows.ObjectTypesLock.ReleaseShared();
}
- if (string.IsNullOrEmpty(info.TypeName))
+ if (info.TypeName == null)
{
- Win32.NtQueryObject(
- objectHandle,
- ObjectInformationClass.ObjectTypeInformation,
- IntPtr.Zero,
- 0,
- out retLength
- );
+ int baseAddress = 0;
+
+ if (KProcessHacker.Instance != null)
+ {
+ KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
+ IntPtr.Zero, 0, out retLength, out baseAddress);
+ }
+ else
+ {
+ Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
+ IntPtr.Zero, 0, out retLength);
+ }
if (retLength > 0)
{
using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
{
- Win32.NtQueryObject(
- objectHandle,
- ObjectInformationClass.ObjectTypeInformation,
- otiMem,
- otiMem.Size,
- out retLength
- ).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ if (KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
+ otiMem, otiMem.Size, out retLength, out baseAddress) >= NtStatus.Error)
+ throw new Exception("ZwQueryObject failed.");
+ }
+ else
+ {
+ if (Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
+ otiMem, otiMem.Size, out retLength) >= NtStatus.Error)
+ throw new Exception("NtQueryObject failed.");
+ }
- ObjectTypeInformation oti = otiMem.ReadStruct();
- UnicodeString str = oti.Name;
+ var oti = otiMem.ReadStruct();
+ var str = oti.Name;
- //if (KProcessHacker.Instance != null)
- //str.Buffer = str.Buffer.Increment(otiMem.Memory.Decrement(baseAddress));
+ if (KProcessHacker.Instance != null)
+ str.Buffer = str.Buffer.Increment(otiMem.Memory.Decrement(baseAddress));
- info.TypeName = str.Text;
+ info.TypeName = str.Read();
Windows.ObjectTypesLock.AcquireExclusive();
@@ -252,14 +278,14 @@ out retLength
// Get the object's name. If the object is a file we must take special
// precautions so that we don't hang.
- if (string.Equals(info.TypeName, "File", StringComparison.OrdinalIgnoreCase))
+ if (info.TypeName == "File")
{
- //if (KProcessHacker.Instance != null)
- //{
- // // Use KProcessHacker for files to avoid hangs.
- // info.OrigName = KProcessHacker.Instance.GetHandleObjectName(process, handle);
- //}
- //else
+ if (KProcessHacker.Instance != null)
+ {
+ // Use KProcessHacker for files to avoid hangs.
+ info.OrigName = KProcessHacker.Instance.GetHandleObjectName(process, handle);
+ }
+ else
{
// 0: No hack, query the thing normally.
// 1: No hack, use NProcessHacker.
@@ -289,16 +315,13 @@ out retLength
// Use NProcessHacker.
using (MemoryAlloc oniMem = new MemoryAlloc(0x4000))
{
- NProcessHacker.PhQueryNameFileObject(
- objectHandle,
- oniMem,
- oniMem.Size,
- out retLength
- ).ThrowIf();
+ if (NProcessHacker.PhQueryNameFileObject(
+ objectHandle, oniMem, oniMem.Size, out retLength) >= NtStatus.Error)
+ throw new Exception("PhQueryNameFileObject failed.");
var oni = oniMem.ReadStruct();
- info.OrigName = oni.Name.Text;
+ info.OrigName = oni.Name.Read();
}
}
catch (DllNotFoundException)
@@ -316,7 +339,7 @@ out retLength
{
// KProcessHacker and NProcessHacker not available. Fall back to using hack
// (i.e. not querying the name at all if the access is 0x0012019f).
- if (thisHandle.GrantedAccess != 0x0012019f)
+ if ((int)thisHandle.GrantedAccess != 0x0012019f)
info.OrigName = GetObjectNameNt(process, handle, objectHandle);
}
}
@@ -341,20 +364,33 @@ out retLength
case "Key":
info.BestName = NativeUtils.FormatNativeKeyName(info.OrigName);
+
break;
case "Process":
{
int processId;
- using (NativeHandle processHandle = new NativeHandle(process, handle, OSVersion.MinProcessQueryInfoAccess))
+ if (KProcessHacker.Instance != null)
{
- if ((processId = Win32.GetProcessId(processHandle)) == 0)
- Win32.Throw();
+ processId = KProcessHacker.Instance.KphGetProcessId(process, handle);
+
+ if (processId == 0)
+ throw new Exception("Invalid PID");
+ }
+ else
+ {
+ using (var processHandle =
+ new NativeHandle(process, handle, OSVersion.MinProcessQueryInfoAccess))
+ {
+ if ((processId = Win32.GetProcessId(processHandle)) == 0)
+ Win32.Throw();
+ }
}
info.BestName = (new ClientId(processId, 0)).GetName(false);
}
+
break;
case "Thread":
@@ -362,82 +398,106 @@ out retLength
int processId;
int threadId;
- using (var threadHandle = new NativeHandle(process, handle, OSVersion.MinThreadQueryInfoAccess))
+ if (KProcessHacker.Instance != null)
{
- var basicInfo = ThreadHandle.FromHandle(threadHandle).GetBasicInformation();
+ threadId = KProcessHacker.Instance.KphGetThreadId(process, handle, out processId);
- threadId = basicInfo.ClientId.ThreadId;
- processId = basicInfo.ClientId.ProcessId;
+ if (threadId == 0 || processId == 0)
+ throw new Exception("Invalid TID or PID");
+ }
+ else
+ {
+ using (var threadHandle =
+ new NativeHandle(process, handle, OSVersion.MinThreadQueryInfoAccess))
+ {
+ var basicInfo = ThreadHandle.FromHandle(threadHandle).GetBasicInformation();
+
+ threadId = basicInfo.ClientId.ThreadId;
+ processId = basicInfo.ClientId.ProcessId;
+ }
}
info.BestName = (new ClientId(processId, threadId)).GetName(true);
}
+
break;
case "TmEn":
{
- using (NativeHandle enHandleDup = new NativeHandle(process, handle, EnlistmentAccess.QueryInformation))
- using (EnlistmentHandle enHandle = EnlistmentHandle.FromHandle(enHandleDup))
+ using (var enHandleDup =
+ new NativeHandle(process, handle, EnlistmentAccess.QueryInformation))
{
- info.BestName = enHandle.BasicInformation.EnlistmentId.ToString("B");
+ var enHandle = EnlistmentHandle.FromHandle(enHandleDup);
+
+ info.BestName = enHandle.GetBasicInformation().EnlistmentId.ToString("B");
}
}
break;
case "TmRm":
{
- using (var rmHandleDup = new NativeHandle(process, handle, ResourceManagerAccess.QueryInformation))
+ using (var rmHandleDup =
+ new NativeHandle(process, handle, ResourceManagerAccess.QueryInformation))
{
var rmHandle = ResourceManagerHandle.FromHandle(rmHandleDup);
- info.BestName = rmHandle.Description;
+ info.BestName = rmHandle.GetDescription();
if (string.IsNullOrEmpty(info.BestName))
- info.BestName = rmHandle.Guid.ToString("B");
+ info.BestName = rmHandle.GetGuid().ToString("B");
}
}
break;
case "TmTm":
{
- using (NativeHandle tmHandleDup = new NativeHandle(process, handle, TmAccess.QueryInformation))
- using (TmHandle tmHandle = TmHandle.FromHandle(tmHandleDup))
+ using (var tmHandleDup =
+ new NativeHandle(process, handle, TmAccess.QueryInformation))
{
- info.BestName = FileUtils.GetFileName(FileUtils.GetFileName(tmHandle.LogFileName));
+ var tmHandle = TmHandle.FromHandle(tmHandleDup);
+
+ info.BestName = FileUtils.GetFileName(FileUtils.GetFileName(tmHandle.GetLogFileName()));
if (string.IsNullOrEmpty(info.BestName))
- info.BestName = tmHandle.BasicInformation.TmIdentity.ToString("B");
+ info.BestName = tmHandle.GetBasicInformation().TmIdentity.ToString("B");
}
}
break;
case "TmTx":
{
- using (var transactionHandleDup = new NativeHandle(process, handle, TransactionAccess.QueryInformation))
+ using (var transactionHandleDup =
+ new NativeHandle(process, handle, TransactionAccess.QueryInformation))
{
- TransactionHandle transactionHandle = TransactionHandle.FromHandle(transactionHandleDup);
+ var transactionHandle = TransactionHandle.FromHandle(transactionHandleDup);
- info.BestName = transactionHandle.Description;
+ info.BestName = transactionHandle.GetDescription();
if (string.IsNullOrEmpty(info.BestName))
- info.BestName = transactionHandle.BasicInformation.TransactionId.ToString("B");
+ info.BestName = transactionHandle.GetBasicInformation().TransactionId.ToString("B");
}
}
break;
case "Token":
{
- using (var tokenHandleDup = new NativeHandle(process, handle, TokenAccess.Query))
- using (TokenHandle tokenHandle = TokenHandle.FromHandle(tokenHandleDup))
- using (tokenHandle.User)
+ using (var tokenHandleDup =
+ new NativeHandle(process, handle, TokenAccess.Query))
{
- info.BestName = tokenHandle.User.GetFullName(true) + ": 0x" + tokenHandle.Statistics.AuthenticationId;
+ var tokenHandle = TokenHandle.FromHandle(tokenHandleDup);
+ var sid = tokenHandle.GetUser();
+
+ using (sid)
+ info.BestName = sid.GetFullName(true) + ": 0x" +
+ tokenHandle.GetStatistics().AuthenticationId.ToString();
}
}
+
break;
default:
- if (!string.IsNullOrEmpty(info.OrigName))
+ if (info.OrigName != null &&
+ info.OrigName != "")
{
info.BestName = info.OrigName;
}
@@ -451,7 +511,7 @@ out retLength
}
catch
{
- if (!string.IsNullOrEmpty(info.OrigName))
+ if (info.OrigName != null && info.OrigName != "")
{
info.BestName = info.OrigName;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Api/Functions.cs b/1.x/trunk/ProcessHacker.Native/Api/Functions.cs
index 5fc47f803..51647ecdb 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/Functions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/Functions.cs
@@ -35,6 +35,7 @@
using System.Text;
using System.Threading;
using System.Windows.Forms;
+using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
namespace ProcessHacker.Native.Api
@@ -441,7 +442,7 @@ public static extern IntPtr ImageNtHeader(
[In] IntPtr ImageBase
);
- [DllImport("imagehlp.dll", SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true, CharSet = CharSet.Ansi)]
+ [DllImport("imagehlp.dll", SetLastError = true, CharSet = CharSet.Ansi)]
public static extern bool MapAndLoad(
[In] string ImageName,
[In] [Optional] string DllPath,
@@ -2590,8 +2591,8 @@ [In] UipiFilterFlag flag
public static extern IntPtr SendMessage(
[In] IntPtr hWnd,
[In] WindowMessage msg,
- [In] IntPtr w,
- [In] IntPtr l
+ [In] int w,
+ [In] int l
);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
diff --git a/1.x/trunk/ProcessHacker.Native/Api/HResult.cs b/1.x/trunk/ProcessHacker.Native/Api/HResult.cs
index a15542d46..b91d0cb78 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/HResult.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/HResult.cs
@@ -21,6 +21,7 @@
* along with Process Hacker. If not, see .
*/
+using System;
using System.Runtime.InteropServices;
namespace ProcessHacker.Native.Api
diff --git a/1.x/trunk/ProcessHacker.Native/Api/ISecurityInformation.cs b/1.x/trunk/ProcessHacker.Native/Api/ISecurityInformation.cs
index 80186163b..4938bca58 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/ISecurityInformation.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/ISecurityInformation.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using System.Runtime.InteropServices;
namespace ProcessHacker.Native.Api
diff --git a/1.x/trunk/ProcessHacker.Native/Api/LsaFunctions.cs b/1.x/trunk/ProcessHacker.Native/Api/LsaFunctions.cs
index 0e57c8493..a6a69f412 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/LsaFunctions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/LsaFunctions.cs
@@ -21,7 +21,9 @@
*/
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Text;
using ProcessHacker.Native.Security;
namespace ProcessHacker.Native.Api
diff --git a/1.x/trunk/ProcessHacker.Native/Api/LsaStructs.cs b/1.x/trunk/ProcessHacker.Native/Api/LsaStructs.cs
index 2b082ff77..b5fe9b79d 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/LsaStructs.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/LsaStructs.cs
@@ -21,7 +21,9 @@
*/
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Text;
namespace ProcessHacker.Native.Api
{
@@ -60,13 +62,6 @@ public struct LsaTranslatedSid2
[StructLayout(LayoutKind.Sequential)]
public struct LsaTrustInformation
{
- public static readonly int SizeOf;
-
- static LsaTrustInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(LsaTrustInformation));
- }
-
public UnicodeString Name;
public IntPtr Sid; // Sid*
}
@@ -74,13 +69,6 @@ static LsaTrustInformation()
[StructLayout(LayoutKind.Sequential)]
public struct Msv1_0_InteractiveLogon
{
- public static readonly int SizeOf;
-
- static Msv1_0_InteractiveLogon()
- {
- SizeOf = Marshal.SizeOf(typeof(Msv1_0_InteractiveLogon));
- }
-
public Msv1_0_LogonSubmitType MessageType;
public UnicodeString LogonDomainName;
public UnicodeString UserName;
@@ -111,13 +99,6 @@ public struct Msv1_0_InteractiveProfile
[StructLayout(LayoutKind.Sequential)]
public struct PolicyPrivilegeDefinition
{
- public static readonly int SizeOf;
-
- static PolicyPrivilegeDefinition()
- {
- SizeOf = Marshal.SizeOf(typeof(PolicyPrivilegeDefinition));
- }
-
public UnicodeString Name;
public Luid LocalValue;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Api/NativeDefinitions.cs b/1.x/trunk/ProcessHacker.Native/Api/NativeDefinitions.cs
index fe065c3a1..f72d1a20b 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/NativeDefinitions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/NativeDefinitions.cs
@@ -84,9 +84,9 @@ public static partial class Win32
public const string TransactionManagerPath = @"\TransactionManager";
public static readonly IntPtr KnownAceSidStartOffset = Marshal.OffsetOf(typeof(KnownAceStruct), "SidStart");
- public static readonly int SecurityDescriptorMinLength = SecurityDescriptorStruct.SizeOf;
+ public static readonly int SecurityDescriptorMinLength = Marshal.SizeOf(typeof(SecurityDescriptorStruct));
public static readonly int SecurityMaxSidSize =
- SidStruct.SizeOf - sizeof(int) + (SidMaxSubAuthorities * sizeof(int));
+ Marshal.SizeOf(typeof(SidStruct)) - sizeof(int) + (SidMaxSubAuthorities * sizeof(int));
public static readonly IntPtr UserSharedData = new IntPtr(0x7ffe0000);
public static int CsrMakeApiNumber(int dllIndex, int apiIndex)
diff --git a/1.x/trunk/ProcessHacker.Native/Api/NativeEnums.cs b/1.x/trunk/ProcessHacker.Native/Api/NativeEnums.cs
index 18b08cf76..15d0f6e64 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/NativeEnums.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/NativeEnums.cs
@@ -210,7 +210,6 @@ public enum DebugObjectInformationClass : int
MaxDebugObjectInfoClass
}
- [Flags]
public enum DeviceControlAccess : int
{
Any = 0,
@@ -425,7 +424,7 @@ public enum FileCreationDisposition : int
OverwriteIf = 0x5
}
- public enum FileInformationClass
+ public enum FileInformationClass : int
{
FileDirectoryInformation = 1, // dir
FileFullDirectoryInformation, // dir
diff --git a/1.x/trunk/ProcessHacker.Native/Api/NativeFunctions.cs b/1.x/trunk/ProcessHacker.Native/Api/NativeFunctions.cs
index 02d8913f2..c571bcdf7 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/NativeFunctions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/NativeFunctions.cs
@@ -1507,15 +1507,6 @@ public static extern NtStatus NtQueryInformationToken(
[Out] [Optional] out int ReturnLength
);
- [DllImport("ntdll.dll")]
- public static unsafe extern NtStatus NtQueryInformationToken(
- [In] IntPtr TokenHandle,
- [In] TokenInformationClass TokenInformationClass,
- void* TokenInformation,
- [In] int TokenInformationLength,
- [Optional] void* ReturnLength
- );
-
[DllImport("ntdll.dll")]
public static extern NtStatus NtQueryInformationToken(
[In] IntPtr TokenHandle,
@@ -1676,14 +1667,6 @@ public static extern NtStatus NtQuerySymbolicLinkObject(
[Out] [Optional] out int ReturnLength
);
- [DllImport("ntdll.dll")]
- public static unsafe extern NtStatus NtQuerySystemInformation(
- [In] SystemInformationClass SystemInformationClass,
- void* SystemInformation,
- [In] int SystemInformationLength,
- int* ReturnLength
- );
-
[DllImport("ntdll.dll")]
public static extern NtStatus NtQuerySystemInformation(
[In] SystemInformationClass SystemInformationClass,
@@ -2520,7 +2503,7 @@ [In] [Optional] ref long Timeout
[DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
public static extern NtStatus LdrGetDllHandle(
[In] [Optional] string DllPath,
- [In] [Optional] int DllCharacteristics,
+ [In] [Optional] ref int DllCharacteristics,
[In] ref UnicodeString DllName,
[Out] out IntPtr DllHandle
);
@@ -2528,7 +2511,7 @@ [Out] out IntPtr DllHandle
[DllImport("ntdll.dll")]
public static extern NtStatus LdrGetProcedureAddress(
[In] IntPtr DllHandle,
- [In] [Optional] IntPtr ProcedureName,
+ [In] [Optional] ref AnsiString ProcedureName,
[In] [Optional] int ProcedureNumber,
[Out] out IntPtr ProcedureAddress
);
@@ -2536,7 +2519,7 @@ [Out] out IntPtr ProcedureAddress
[DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
public static extern NtStatus LdrLoadDll(
[In] [Optional] string DllPath,
- [In] [Optional] int DllCharacteristics,
+ [In] [Optional] ref int DllCharacteristics,
[In] ref UnicodeString DllName,
[Out] out IntPtr DllHandle
);
@@ -3311,14 +3294,6 @@ public static extern void RtlMoveMemory(
[In] IntPtr Length
);
-
- [DllImport("ntdll.dll")]
- public static extern unsafe void RtlMoveMemory(
- void* Destination,
- void* Source,
- [In] IntPtr Length
- );
-
[DllImport("ntdll.dll")]
public static extern void RtlZeroMemory(
[In] IntPtr Destination,
diff --git a/1.x/trunk/ProcessHacker.Native/Api/NativeStructs.cs b/1.x/trunk/ProcessHacker.Native/Api/NativeStructs.cs
index b8a053771..243f8848f 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/NativeStructs.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/NativeStructs.cs
@@ -99,13 +99,6 @@ public struct AclRevisionInformation
[StructLayout(LayoutKind.Sequential)]
public struct AclSizeInformation
{
- public static readonly int SizeOf;
-
- static AclSizeInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(AclSizeInformation));
- }
-
public int AceCount;
public int AclBytesInUse;
public int AclBytesFree;
@@ -126,10 +119,11 @@ public struct AnsiString : IDisposable
{
public AnsiString(string str)
{
- using (UnicodeString unicodeStr = new UnicodeString(str))
- {
- this = unicodeStr.ToAnsiString();
- }
+ UnicodeString unicodeStr;
+
+ unicodeStr = new UnicodeString(str);
+ this = unicodeStr.ToAnsiString();
+ unicodeStr.Dispose();
}
public ushort Length;
@@ -147,9 +141,11 @@ public void Dispose()
public UnicodeString ToUnicodeString()
{
+ NtStatus status;
UnicodeString unicodeStr = new UnicodeString();
- Win32.RtlAnsiStringToUnicodeString(ref unicodeStr, ref this, true).ThrowIf();
+ if ((status = Win32.RtlAnsiStringToUnicodeString(ref unicodeStr, ref this, true)) >= NtStatus.Error)
+ Win32.Throw(status);
return unicodeStr;
}
@@ -158,13 +154,6 @@ public UnicodeString ToUnicodeString()
[StructLayout(LayoutKind.Sequential)]
public struct BaseCreateProcessMsg
{
- public static readonly int SizeOf;
-
- static BaseCreateProcessMsg()
- {
- SizeOf = Marshal.SizeOf(typeof(BaseCreateProcessMsg));
- }
-
public IntPtr ProcessHandle;
public IntPtr ThreadHandle;
public ClientId ClientId;
@@ -184,8 +173,6 @@ public struct BaseCreateThreadMsg
[StructLayout(LayoutKind.Sequential)]
public struct ClientId
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(ClientId));
-
public ClientId(int processId, int threadId)
{
this.UniqueProcess = new IntPtr(processId);
@@ -195,15 +182,8 @@ public ClientId(int processId, int threadId)
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
- public int ProcessId
- {
- get { return this.UniqueProcess.ToInt32(); }
- }
-
- public int ThreadId
- {
- get { return this.UniqueThread.ToInt32(); }
- }
+ public int ProcessId { get { return this.UniqueProcess.ToInt32(); } }
+ public int ThreadId { get { return this.UniqueThread.ToInt32(); } }
}
[StructLayout(LayoutKind.Sequential)]
@@ -262,13 +242,6 @@ public struct Context
[StructLayout(LayoutKind.Sequential)]
public struct ContextAmd64
{
- public static readonly int SizeOf;
-
- static ContextAmd64()
- {
- SizeOf = Marshal.SizeOf(typeof(ContextAmd64));
- }
-
public long P1Home;
public long P2Home;
public long P3Home;
@@ -454,13 +427,6 @@ public struct DbgUiWaitStateChange
[StructLayout(LayoutKind.Sequential)]
public struct EnlistmentBasicInformation
{
- public static readonly int SizeOf;
-
- static EnlistmentBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(EnlistmentBasicInformation));
- }
-
public Guid EnlistmentId;
public Guid TransactionId;
public Guid ResourceManagerId;
@@ -469,13 +435,6 @@ static EnlistmentBasicInformation()
[StructLayout(LayoutKind.Sequential)]
public struct EventBasicInformation
{
- public static readonly int SizeOf;
-
- static EventBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(EventBasicInformation));
- }
-
public EventType EventType;
public int EventState;
}
@@ -521,13 +480,6 @@ public struct FileAllInformation
[StructLayout(LayoutKind.Sequential)]
public struct FileBasicInformation
{
- public static readonly int SizeOf;
-
- static FileBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileBasicInformation));
- }
-
public long CreationTime;
public long LastAccessTime;
public long LastWriteTime;
@@ -538,13 +490,6 @@ static FileBasicInformation()
[StructLayout(LayoutKind.Sequential)]
public struct FileCompletionInformation
{
- public static readonly int SizeOf;
-
- static FileCompletionInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileCompletionInformation));
- }
-
public IntPtr Port;
public IntPtr Key;
}
@@ -552,14 +497,8 @@ static FileCompletionInformation()
[StructLayout(LayoutKind.Sequential)]
public struct FileDirectoryInformation
{
- public static readonly int SizeOf;
- public static readonly int FileNameOffset;
-
- static FileDirectoryInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileDirectoryInformation));
- FileNameOffset = Marshal.OffsetOf(typeof(FileDirectoryInformation), "FileName").ToInt32();
- }
+ public static int FileNameOffset =
+ Marshal.OffsetOf(typeof(FileDirectoryInformation), "FileName").ToInt32();
public int NextEntryOffset;
public int FileIndex;
@@ -578,13 +517,6 @@ static FileDirectoryInformation()
[StructLayout(LayoutKind.Sequential)]
public struct FileDispositionInformation
{
- public static readonly int SizeOf;
-
- static FileDispositionInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileDispositionInformation));
- }
-
[MarshalAs(UnmanagedType.I1)]
public bool DeleteFile;
}
@@ -598,28 +530,12 @@ public struct FileEaInformation
[StructLayout(LayoutKind.Sequential)]
public struct FileEndOfFileInformation
{
- public static readonly int SizeOf;
-
- static FileEndOfFileInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileEndOfFileInformation));
- }
-
public long EndOfFile;
}
[StructLayout(LayoutKind.Sequential)]
public struct FileFsAttributeInformation
{
- public static readonly int SizeOf;
- public static readonly int FileSystemNameOffset;
-
- static FileFsAttributeInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileFsAttributeInformation));
- FileSystemNameOffset = Marshal.OffsetOf(typeof(FileFsAttributeInformation), "FileSystemName").ToInt32();
- }
-
public int FileSystemAttributes;
public int MaximumComponentNameLength;
public int FileSystemNameLength;
@@ -638,22 +554,11 @@ public struct FileFsLabelInformation
[StructLayout(LayoutKind.Sequential)]
public struct FileFsVolumeInformation
{
- public static readonly int SizeOf;
- public static readonly int VolumeLabelOffset;
-
- static FileFsVolumeInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileFsVolumeInformation));
- VolumeLabelOffset = Marshal.OffsetOf(typeof(FileFsVolumeInformation), "VolumeLabel").ToInt32();
- }
-
public long VolumeCreationTime;
public int VolumeSerialNumber;
public int VolumeLabelLength;
-
[MarshalAs(UnmanagedType.I1)]
public bool SupportsObjects;
-
public short VolumeLabel;
// Volume label string follows (WCHAR).
}
@@ -689,14 +594,8 @@ public struct FileModeInformation
[StructLayout(LayoutKind.Sequential)]
public struct FileNameInformation
{
- public static readonly int SizeOf;
- public static int FileNameOffset;
-
- static FileNameInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileNameInformation));
- FileNameOffset = Marshal.OffsetOf(typeof(FileNameInformation), "FileName").ToInt32();
- }
+ public static int FileNameOffset =
+ Marshal.OffsetOf(typeof(FileNameInformation), "FileName").ToInt32();
public int FileNameLength;
public short FileName;
@@ -729,13 +628,6 @@ public struct FileNotifyInformation
[StructLayout(LayoutKind.Sequential)]
public struct FilePipeInformation
{
- public static readonly int SizeOf;
-
- static FilePipeInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FilePipeInformation));
- }
-
public PipeType ReadMode;
public PipeCompletionMode CompletionMode;
}
@@ -743,13 +635,6 @@ static FilePipeInformation()
[StructLayout(LayoutKind.Sequential)]
public struct FilePipeLocalInformation
{
- public static readonly int SizeOf;
-
- static FilePipeLocalInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FilePipeLocalInformation));
- }
-
public PipeType NamedPipeType;
public PipeConfiguration NamedPipeConfiguration;
public int MaximumInstances;
@@ -791,33 +676,17 @@ public struct FilePipeWaitForBuffer
[StructLayout(LayoutKind.Sequential)]
public struct FilePositionInformation
{
- public static readonly int SizeOf;
-
- static FilePositionInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FilePositionInformation));
- }
-
public long CurrentByteOffset;
}
[StructLayout(LayoutKind.Sequential)]
public struct FileStandardInformation
{
- public static readonly int SizeOf;
-
- static FileStandardInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileStandardInformation));
- }
-
public long AllocationSize;
public long EndOfFile;
public int NumberOfLinks;
-
[MarshalAs(UnmanagedType.I1)]
public bool DeletePending;
-
[MarshalAs(UnmanagedType.I1)]
public bool Directory;
}
@@ -825,14 +694,8 @@ static FileStandardInformation()
[StructLayout(LayoutKind.Sequential)]
public struct FileStreamInformation
{
- public static readonly int SizeOf;
- public static int StreamNameOffset;
-
- static FileStreamInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(FileStreamInformation));
- StreamNameOffset = Marshal.OffsetOf(typeof(FileStreamInformation), "StreamName").ToInt32();
- }
+ public static int StreamNameOffset =
+ Marshal.OffsetOf(typeof(FileStreamInformation), "StreamName").ToInt32();
public int NextEntryOffset;
public int StreamNameLength;
@@ -1155,13 +1018,6 @@ public struct IoCompletionBasicInformation
[StructLayout(LayoutKind.Sequential)]
public struct IoCounters
{
- public static readonly int SizeOf;
-
- static IoCounters()
- {
- SizeOf = Marshal.SizeOf(typeof(IoCounters));
- }
-
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
@@ -1173,13 +1029,6 @@ static IoCounters()
[StructLayout(LayoutKind.Sequential)]
public struct IoStatusBlock
{
- public static readonly int SizeOf;
-
- static IoStatusBlock()
- {
- SizeOf = Marshal.SizeOf(typeof(IoStatusBlock));
- }
-
public IoStatusBlock(NtStatus status)
: this(status, IntPtr.Zero)
{ }
@@ -1222,8 +1071,6 @@ public unsafe NtStatus Status
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectBasicAccountingInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(JobObjectBasicAccountingInformation));
-
public long TotalUserTime;
public long TotalKernelTime;
public long ThisPeriodTotalUserTime;
@@ -1237,8 +1084,6 @@ public struct JobObjectBasicAccountingInformation
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectBasicAndIoAccountingInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(JobObjectBasicAndIoAccountingInformation));
-
public JobObjectBasicAccountingInformation BasicInfo;
public IoCounters IoInfo;
}
@@ -1246,8 +1091,6 @@ public struct JobObjectBasicAndIoAccountingInformation
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectBasicLimitInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(JobObjectBasicLimitInformation));
-
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public JobObjectLimitFlags LimitFlags;
@@ -1276,13 +1119,6 @@ public struct JobObjectEndOfJobTimeInformation
[StructLayout(LayoutKind.Sequential)]
public struct JobObjectExtendedLimitInformation
{
- public static readonly int SizeOf;
-
- static JobObjectExtendedLimitInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(JobObjectExtendedLimitInformation));
- }
-
public JobObjectBasicLimitInformation BasicLimitInformation;
public IoCounters IoInfo;
public int ProcessMemoryLimit;
@@ -1423,13 +1259,6 @@ public struct KeyWriteTimeInformation
[StructLayout(LayoutKind.Sequential)]
public struct KnownAceStruct
{
- public static readonly int SizeOf;
-
- static KnownAceStruct()
- {
- SizeOf = Marshal.SizeOf(typeof(KnownAceStruct));
- }
-
public AceHeader Header;
public int Mask;
public int SidStart;
@@ -1551,14 +1380,8 @@ public LargeInteger(long quadPart)
[StructLayout(LayoutKind.Sequential)]
public struct LdrDataTableEntry
{
- public static readonly int SizeOf;
- public static readonly int LoadCountOffset;
-
- static LdrDataTableEntry()
- {
- SizeOf = Marshal.SizeOf(typeof(LdrDataTableEntry));
- LoadCountOffset = Marshal.OffsetOf(typeof(LdrDataTableEntry), "LoadCount").ToInt32();
- }
+ public static readonly int LoadCountOffset =
+ Marshal.OffsetOf(typeof(LdrDataTableEntry), "LoadCount").ToInt32();
public ListEntry InLoadOrderLinks;
public ListEntry InMemoryOrderLinks;
@@ -1591,22 +1414,12 @@ public struct ListEntry
[StructLayout(LayoutKind.Explicit, Pack = 4)]
public struct Luid : IEquatable, IEquatable
{
- public static readonly int SizeOf;
- public static readonly Luid Empty;
+ public static readonly Luid Empty = new Luid();
public static readonly Luid System = new Luid(0x3e7, 0);
public static readonly Luid AnonymousLogon = new Luid(0x3e6, 0);
public static readonly Luid LocalService = new Luid(0x3e5, 0);
public static readonly Luid NetworkService = new Luid(0x3e4, 0);
- static Luid()
- {
- SizeOf = Marshal.SizeOf(typeof(Luid));
- System = new Luid(0x3e7, 0);
- AnonymousLogon = new Luid(0x3e6, 0);
- LocalService = new Luid(0x3e5, 0);
- NetworkService = new Luid(0x3e4, 0);
- }
-
///
/// Creates a LUID from a single 64-bit value.
///
@@ -1653,9 +1466,11 @@ public Luid(uint lowPart, int highPart)
/// A new LUID.
public static Luid Allocate()
{
+ NtStatus status;
Luid luid;
- Win32.NtAllocateLocallyUniqueId(out luid).ThrowIf();
+ if ((status = Win32.NtAllocateLocallyUniqueId(out luid)) >= NtStatus.Error)
+ Win32.Throw(status);
return luid;
}
@@ -1712,18 +1527,9 @@ public struct MessageResourceEntry
[StructLayout(LayoutKind.Sequential)]
public struct MutantBasicInformation
{
- public static readonly int SizeOf;
-
- static MutantBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(MutantBasicInformation));
- }
-
public int CurrentCount;
-
[MarshalAs(UnmanagedType.U1)]
public bool OwnedByCaller;
-
[MarshalAs(UnmanagedType.U1)]
public bool AbandonedState;
}
@@ -1731,13 +1537,6 @@ static MutantBasicInformation()
[StructLayout(LayoutKind.Sequential)]
public struct MutantOwnerInformation
{
- public static readonly int SizeOf;
-
- static MutantOwnerInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(MutantOwnerInformation));
- }
-
public ClientId ClientId;
}
@@ -1756,8 +1555,6 @@ public struct NtTib
[StructLayout(LayoutKind.Sequential)]
public struct ObjectAttributes : IDisposable
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(ObjectAttributes));
-
public ObjectAttributes(
string objectName,
ObjectFlags attributes,
@@ -1773,17 +1570,17 @@ public ObjectAttributes(
SecurityQualityOfService? securityQos
)
{
- this.Length = SizeOf;
+ this.Length = Marshal.SizeOf(typeof(ObjectAttributes));
this.RootDirectory = IntPtr.Zero;
this.ObjectName = IntPtr.Zero;
- this.PtrSecurityDescriptor = IntPtr.Zero;
- this.PtrSecurityQualityOfService = IntPtr.Zero;
+ this.SecurityDescriptor = IntPtr.Zero;
+ this.SecurityQualityOfService = IntPtr.Zero;
// Object name
- if (!string.IsNullOrEmpty(objectName))
+ if (objectName != null)
{
UnicodeString unicodeString = new UnicodeString(objectName);
- IntPtr unicodeStringMemory = MemoryAlloc.PrivateHeap.Allocate(UnicodeString.SizeOf);
+ IntPtr unicodeStringMemory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnicodeString)));
Marshal.StructureToPtr(unicodeString, unicodeStringMemory, false);
this.ObjectName = unicodeStringMemory;
@@ -1797,13 +1594,13 @@ public ObjectAttributes(
this.RootDirectory = rootDirectory;
// Security descriptor
- this.PtrSecurityDescriptor = securityDescriptor ?? IntPtr.Zero;
+ this.SecurityDescriptor = securityDescriptor ?? IntPtr.Zero;
// Security QOS
if (securityQos.HasValue)
{
- this.PtrSecurityQualityOfService = MemoryAlloc.PrivateHeap.Allocate(SecurityQualityOfService.SizeOf);
- Marshal.StructureToPtr(securityQos.Value, this.PtrSecurityQualityOfService, false);
+ this.SecurityQualityOfService = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityQualityOfService)));
+ Marshal.StructureToPtr(securityQos.Value, this.SecurityQualityOfService, false);
}
}
@@ -1811,23 +1608,28 @@ public ObjectAttributes(
public IntPtr RootDirectory;
public IntPtr ObjectName;
public ObjectFlags Attributes;
- public IntPtr PtrSecurityDescriptor;
- public IntPtr PtrSecurityQualityOfService;
+ public IntPtr SecurityDescriptor;
+ public IntPtr SecurityQualityOfService;
public void Dispose()
{
// Object name
if (this.ObjectName != IntPtr.Zero)
{
- MemoryAlloc.PrivateHeap.Free(this.ObjectName);
+ UnicodeString unicodeString =
+ (UnicodeString)Marshal.PtrToStructure(this.ObjectName, typeof(UnicodeString));
+
+ unicodeString.Dispose();
+ Marshal.FreeHGlobal(this.ObjectName);
+
this.ObjectName = IntPtr.Zero;
}
// Security QOS
- if (this.PtrSecurityQualityOfService != IntPtr.Zero)
+ if (this.SecurityQualityOfService != null)
{
- MemoryAlloc.PrivateHeap.Free(this.PtrSecurityQualityOfService);
- this.PtrSecurityQualityOfService = IntPtr.Zero;
+ Marshal.FreeHGlobal(this.SecurityQualityOfService);
+ this.SecurityQualityOfService = IntPtr.Zero;
}
}
}
@@ -1835,13 +1637,6 @@ public void Dispose()
[StructLayout(LayoutKind.Sequential)]
public struct ObjectBasicInformation
{
- public static readonly int SizeOf;
-
- static ObjectBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(ObjectBasicInformation));
- }
-
public uint Attributes;
public int GrantedAccess;
public uint HandleCount;
@@ -1856,30 +1651,15 @@ static ObjectBasicInformation()
public uint TypeInformationLength;
public uint SecurityDescriptorLength;
public ulong CreateTime;
-
}
[StructLayout(LayoutKind.Sequential)]
public struct ObjectDirectoryInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(ObjectDirectoryInformation));
-
public UnicodeString Name;
public UnicodeString TypeName;
}
- [StructLayout(LayoutKind.Sequential)]
- public struct ObjectHandleFlagInformation
- {
- public static readonly int SizeOf = Marshal.SizeOf(typeof(ObjectHandleFlagInformation));
-
- [MarshalAs(UnmanagedType.Bool)]
- public bool Inherit;
-
- [MarshalAs(UnmanagedType.Bool)]
- public bool ProtectFromClose;
- }
-
[StructLayout(LayoutKind.Sequential)]
public struct ObjectNameInformation
{
@@ -2017,13 +1797,6 @@ public struct Peb
[StructLayout(LayoutKind.Sequential)]
public struct PebLdrData
{
- public static readonly int SizeOf;
-
- static PebLdrData()
- {
- SizeOf = Marshal.SizeOf(typeof(PebLdrData));
- }
-
public int Length;
[MarshalAs(UnmanagedType.I1)]
public bool Initialized;
@@ -2050,13 +1823,6 @@ public struct PooledUsageAndLimits
[StructLayout(LayoutKind.Sequential)]
public struct PortMessageStruct
{
- public static readonly int SizeOf;
-
- static PortMessageStruct()
- {
- SizeOf = Marshal.SizeOf(typeof(PortMessageStruct));
- }
-
public short DataLength;
public short TotalLength;
public PortMessageType Type;
@@ -2080,7 +1846,7 @@ public struct PortView
[StructLayout(LayoutKind.Sequential)]
public struct PrivilegeSetStruct
{
- public static readonly int PrivilegesOffset =
+ public static int PrivilegesOffset =
Marshal.OffsetOf(typeof(PrivilegeSetStruct), "Privileges").ToInt32();
public int Count;
@@ -2091,8 +1857,6 @@ public struct PrivilegeSetStruct
[StructLayout(LayoutKind.Sequential)]
public struct ProcessBasicInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(ProcessBasicInformation));
-
public NtStatus ExitStatus;
public IntPtr PebBaseAddress;
public IntPtr AffinityMask;
@@ -2111,8 +1875,6 @@ public struct ProcessForegroundBackground
[StructLayout(LayoutKind.Sequential)]
public struct ProcessHandleTracingEnable
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(ProcessHandleTracingEnable));
-
public int Flags; // No flags. Set to 0.
}
@@ -2126,13 +1888,6 @@ public struct ProcessHandleTracingEnableEx
[StructLayout(LayoutKind.Sequential)]
public struct ProcessHandleTracingEntry
{
- public static readonly int SizeOf;
-
- static ProcessHandleTracingEntry()
- {
- SizeOf = Marshal.SizeOf(typeof(ProcessHandleTracingEntry));
- }
-
public IntPtr Handle;
public ClientId ClientId;
public HandleTraceType Type;
@@ -2156,16 +1911,9 @@ public struct ProcessHandleTracingQuery
[StructLayout(LayoutKind.Sequential)]
public struct ProcessPriorityClassStruct
{
- public static readonly int SizeOf;
-
//the type char is set by the CLR runtime to marshal as Ansi (single byte) for some insane reason...
public char Foreground;
public char PriorityClass;
-
- static ProcessPriorityClassStruct()
- {
- SizeOf = Marshal.SizeOf(typeof(ProcessPriorityClassStruct));
- }
}
[StructLayout(LayoutKind.Sequential)]
@@ -2267,13 +2015,6 @@ public struct RtlHandleTable
[StructLayout(LayoutKind.Sequential)]
public struct RtlHeapInformation
{
- public static readonly int SizeOf;
-
- static RtlHeapInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(RtlHeapInformation));
- }
-
public IntPtr BaseAddress;
public int Flags;
public ushort EntryOverhead;
@@ -2327,13 +2068,6 @@ public struct RtlProcessHeaps
[StructLayout(LayoutKind.Sequential)]
public struct RtlProcessLockInformation
{
- public static readonly int SizeOf;
-
- static RtlProcessLockInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(RtlProcessLockInformation));
- }
-
public IntPtr Address;
public RtlLockType Type;
public ushort CreatorBackTraceInformation;
@@ -2362,13 +2096,6 @@ public struct RtlProcessLocks
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct RtlProcessModuleInformation
{
- public static readonly int SizeOf;
-
- static RtlProcessModuleInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(RtlProcessModuleInformation));
- }
-
public IntPtr Section; // empty
public IntPtr MappedBase;
public IntPtr ImageBase;
@@ -2406,32 +2133,26 @@ public struct RtlUserProcessInformation
[StructLayout(LayoutKind.Sequential)]
public struct RtlUserProcessParameters
{
- public static readonly int SizeOf;
- public static readonly int CurrentDirectoryOffset;
- public static readonly int DllPathOffset;
- public static readonly int ImagePathNameOffset;
- public static readonly int CommandLineOffset;
- public static readonly int EnvironmentOffset;
- public static readonly int WindowTitleOffset;
- public static readonly int DesktopInfoOffset;
- public static readonly int ShellInfoOffset;
- public static readonly int RuntimeDataOffset;
- public static readonly int CurrentDirectoriesOffset;
-
- static RtlUserProcessParameters()
- {
- SizeOf = Marshal.SizeOf(typeof(RtlUserProcessParameters));
- CurrentDirectoryOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CurrentDirectory").ToInt32();
- DllPathOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "DllPath").ToInt32();
- ImagePathNameOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "ImagePathName").ToInt32();
- CommandLineOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CommandLine").ToInt32();
- EnvironmentOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "Environment").ToInt32();
- WindowTitleOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "WindowTitle").ToInt32();
- DesktopInfoOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "DesktopInfo").ToInt32();
- ShellInfoOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "ShellInfo").ToInt32();
- RuntimeDataOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "RuntimeData").ToInt32();
- CurrentDirectoriesOffset = Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CurrentDirectories").ToInt32();
- }
+ public static readonly int CurrentDirectoryOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CurrentDirectory").ToInt32();
+ public static readonly int DllPathOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "DllPath").ToInt32();
+ public static readonly int ImagePathNameOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "ImagePathName").ToInt32();
+ public static readonly int CommandLineOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CommandLine").ToInt32();
+ public static readonly int EnvironmentOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "Environment").ToInt32();
+ public static readonly int WindowTitleOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "WindowTitle").ToInt32();
+ public static readonly int DesktopInfoOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "DesktopInfo").ToInt32();
+ public static readonly int ShellInfoOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "ShellInfo").ToInt32();
+ public static readonly int RuntimeDataOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "RuntimeData").ToInt32();
+ public static readonly int CurrentDirectoriesOffset =
+ Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CurrentDirectories").ToInt32();
public struct CurDir
{
@@ -2488,23 +2209,14 @@ public struct RtlDriveLetterCurDir
[StructLayout(LayoutKind.Sequential)]
public struct SectionBasicInformation
{
- public static readonly int SizeOf;
-
public int Unknown;
public SectionAttributes SectionAttributes;
public long SectionSize;
-
- static SectionBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SectionBasicInformation));
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct SectionImageInformation
{
- public static readonly int SizeOf;
-
public IntPtr TransferAddress;
public int StackZeroBits;
public IntPtr StackReserved;
@@ -2523,18 +2235,11 @@ public struct SectionImageInformation
public int LoaderFlags;
public int ImageFileSize;
public int Reserved;
-
- static SectionImageInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SectionImageInformation));
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct SecurityDescriptorStruct
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(SecurityDescriptorStruct));
-
public byte Revision;
public byte Sbz1;
public SecurityDescriptorControlFlags Control;
@@ -2559,15 +2264,13 @@ public struct SecurityDescriptorRelativeStruct
[StructLayout(LayoutKind.Sequential)]
public struct SecurityQualityOfService
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(SecurityQualityOfService));
-
public SecurityQualityOfService(
SecurityImpersonationLevel impersonationLevel,
bool dynamicTracking,
bool effectiveOnly
)
{
- this.Length = SizeOf;
+ this.Length = Marshal.SizeOf(typeof(SecurityQualityOfService));
this.ImpersonationLevel = impersonationLevel;
this.ContextTrackingMode = dynamicTracking;
this.EffectiveOnly = effectiveOnly;
@@ -2584,27 +2287,13 @@ bool effectiveOnly
[StructLayout(LayoutKind.Sequential)]
public struct SemaphoreBasicInformation
{
- public static readonly int SizeOf;
-
public int CurrentCount;
public int MaximumCount;
-
- static SemaphoreBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SemaphoreBasicInformation));
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct SidStruct
{
- public static readonly int SizeOf;
-
- static SidStruct()
- {
- SizeOf = Marshal.SizeOf(typeof(SidStruct));
- }
-
public byte Revision;
public byte SubAuthorityCount;
public SidIdentifierAuthority IdentifierAuthority;
@@ -2615,13 +2304,6 @@ static SidStruct()
[StructLayout(LayoutKind.Sequential)]
public struct SidAndAttributes
{
- public static readonly int SizeOf;
-
- static SidAndAttributes()
- {
- SizeOf = Marshal.SizeOf(typeof(SidAndAttributes));
- }
-
public IntPtr Sid; // ptr to a SID object
public SidAttributes Attributes;
@@ -2656,8 +2338,6 @@ public struct SystemAuditAceStruct
[StructLayout(LayoutKind.Sequential)]
public struct SystemBasicInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(SystemBasicInformation));
-
public int Reserved;
public int TimerResolution;
public int PageSize;
@@ -2674,8 +2354,6 @@ public struct SystemBasicInformation
[StructLayout(LayoutKind.Sequential)]
public struct SystemCacheInformation
{
- public static readonly int SizeOf;
-
///
/// The size of the system working set, in bytes.
///
@@ -2696,11 +2374,6 @@ public struct SystemCacheInformation
public IntPtr TransitionSharedPagesPeak;
public int TransitionRePurposeCount;
public int Flags;
-
- static SystemCacheInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SystemCacheInformation));
- }
}
[StructLayout(LayoutKind.Sequential)]
@@ -2730,21 +2403,13 @@ public struct SystemHandleEntry
[StructLayout(LayoutKind.Sequential)]
public struct SystemHandleInformation
{
- public static readonly int HandlesOffset = Marshal.OffsetOf(typeof(SystemHandleInformation), "Handles").ToInt32();
+ public static readonly int HandlesOffset =
+ Marshal.OffsetOf(typeof(SystemHandleInformation), "Handles").ToInt32();
public int NumberOfHandles;
public SystemHandleEntry Handles;
}
- [StructLayout(LayoutKind.Sequential)]
- public struct SystemProcessImageNameInformation
- {
- public static readonly int SizeOf = Marshal.SizeOf(typeof(SystemProcessImageNameInformation));
-
- public int ProcessId;
- public UnicodeString ImageName;
- }
-
[StructLayout(LayoutKind.Sequential)]
public struct SystemLoadAndCallImage
{
@@ -2785,13 +2450,6 @@ public struct SystemObjectTypeInformation
[StructLayout(LayoutKind.Sequential)]
public struct SystemPagefileInformation
{
- public static readonly int SizeOf;
-
- static SystemPagefileInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SystemPagefileInformation));
- }
-
public int NextEntryOffset;
public int TotalSize;
public int TotalInUse;
@@ -2802,12 +2460,7 @@ static SystemPagefileInformation()
[StructLayout(LayoutKind.Sequential)]
public struct SystemPerformanceInformation
{
- public static readonly int SizeOf;
-
- static SystemPerformanceInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SystemPerformanceInformation));
- }
+ public static readonly int Size = Marshal.SizeOf(typeof(SystemPerformanceInformation));
///
/// The total idle time of all processors in units of 100-nanoseconds.
@@ -2828,196 +2481,194 @@ static SystemPerformanceInformation()
///
/// Number of calls to NtReadFile.
///
- public uint IoReadOperationCount;
+ public int IoReadOperationCount;
///
/// Number of calls to NtWriteFile.
///
- public uint IoWriteOperationCount;
+ public int IoWriteOperationCount;
///
/// Number of calls to other I/O functions.
///
- public uint IoOtherOperationCount;
+ public int IoOtherOperationCount;
///
/// The number of pages of physical memory available.
///
- public uint AvailablePages;
+ public int AvailablePages;
///
/// The number of pages of committed virtual memory.
///
- public uint CommittedPages;
+ public int CommittedPages;
///
/// The number of pages of virtual memory that could be committed
/// without extending the system's pagefiles.
///
- public uint CommitLimit;
+ public int CommitLimit;
///
/// The peak number of pages of committed virtual memory.
///
- public uint PeakCommitment;
+ public int PeakCommitment;
///
/// The total number of soft and hard page faults.
///
- public uint PageFaultCount;
+ public int PageFaultCount;
///
/// The number of copy-on-write page faults.
///
- public uint CopyOnWriteCount;
+ public int CopyOnWriteCount;
///
/// The number of soft page faults.
///
- public uint TransitionCount;
+ public int TransitionCount;
///
/// Something that the Native API reference book doesn't have.
///
- public uint CacheTransitionCount;
+ public int CacheTransitionCount;
///
/// The number of demand zero faults.
///
- public uint DemandZeroCount;
+ public int DemandZeroCount;
///
/// The number of pages read from disk to resolve page faults.
///
- public uint PageReadCount;
+ public int PageReadCount;
///
/// The number of read operations initiated to resolve page faults.
///
- public uint PageReadIoCount;
- public uint CacheReadCount;
- public uint CacheIoCount;
+ public int PageReadIoCount;
+ public int CacheReadCount;
+ public int CacheIoCount;
///
/// The number of pages written to the system's pagefiles.
///
- public uint DirtyPagesWriteCount;
+ public int DirtyPagesWriteCount;
///
/// The number of write operations performed on the system's pagefiles.
///
- public uint DirtyWriteIoCount;
+ public int DirtyWriteIoCount;
///
/// The number of pages written to mapped files.
///
- public uint MappedPagesWriteCount;
+ public int MappedPagesWriteCount;
///
/// The number of write operations performed on mapped files.
///
- public uint MappedWriteIoCount;
+ public int MappedWriteIoCount;
///
/// The number of pages used by the paged pool.
///
- public uint PagedPoolPages;
+ public int PagedPoolPages;
///
/// The number of pages used by the non-paged pool.
///
- public uint NonPagedPoolPages;
+ public int NonPagedPoolPages;
///
/// The number of allocations made from the paged pool.
///
- public uint PagedPoolAllocs;
+ public int PagedPoolAllocs;
///
/// The number of allocations returned to the paged pool.
///
- public uint PagedPoolFrees;
+ public int PagedPoolFrees;
///
/// The number of allocations made from the non-paged pool.
///
- public uint NonPagedPoolAllocs;
+ public int NonPagedPoolAllocs;
///
/// The number of allocations returned to the non-paged pool.
///
- public uint NonPagedPoolFrees;
+ public int NonPagedPoolFrees;
///
/// The number of available System Page Table Entries.
///
- public uint FreeSystemPtes;
+ public int FreeSystemPtes;
///
/// The number of pages of pageable OS code and data in physical
/// memory.
///
- public uint ResidentSystemCodePage;
+ public int ResidentSystemCodePage;
///
/// The number of pages of pageable driver code and data.
///
- public uint TotalSystemDriverPages;
+ public int TotalSystemDriverPages;
///
/// The number of pages of OS driver code and data.
///
- public uint TotalSystemCodePages;
+ public int TotalSystemCodePages;
///
/// The number of times an allocation could be statisfied by one of the
/// small non-paged lookaside lists.
///
- public uint NonPagedPoolLookasideHits;
+ public int NonPagedPoolLookasideHits;
///
/// The number of times an allocation could be statisfied by one of the
/// small paged lookaside lists.
///
- public uint PagedPoolLookasideHits;
+ public int PagedPoolLookasideHits;
///
/// The number of pages available for use by the paged pool.
///
- public uint AvailablePagedPoolPages;
+ public int AvailablePagedPoolPages;
///
/// The number of pages of the system cache in physical memory.
///
- public uint ResidentSystemCachePage;
+ public int ResidentSystemCachePage;
///
/// The number of pages of the paged pool in physical memory.
///
- public uint ResidentPagedPoolPage;
+ public int ResidentPagedPoolPage;
///
/// The number of pages of pageable driver code and data in physical memory.
///
- public uint ResidentSystemDriverPage;
+ public int ResidentSystemDriverPage;
///
/// The number of asynchronous fast read operations.
///
- public uint CcFastReadNoWait;
+ public int CcFastReadNoWait;
///
/// The number of synchronous fast read operations.
///
- public uint CcFastReadWait;
+ public int CcFastReadWait;
///
/// The number of fast read operations not possible because of resource
/// conflicts.
///
- public uint CcFastReadResourceMiss;
- public uint CcFastReadNotPossible;
- public uint CcFastMdlReadNoWait;
- public uint CcFastMdlReadWait;
- public uint CcFastMdlReadResourceMiss;
- public uint CcFastMdlReadNotPossible;
- public uint CcMapDataNoWait;
- public uint CcMapDataWait;
- public uint CcMapDataNoWaitMiss;
- public uint CcMapDataWaitMiss;
- public uint CcPinMappedDataCount;
- public uint CcPinReadNoWait;
- public uint CcPinReadWait;
- public uint CcPinReadNoWaitMiss;
- public uint CcPinReadWaitMiss;
- public uint CcCopyReadNoWait;
- public uint CcCopyReadWait;
- public uint CcCopyReadNoWaitMiss;
- public uint CcCopyReadWaitMiss;
- public uint CcMdlReadNoWait;
- public uint CcMdlReadWait;
- public uint CcMdlReadNoWaitMiss;
- public uint CcMdlReadWaitMiss;
- public uint CcReadAheadIos;
- public uint CcLazyWriteIos;
- public uint CcLazyWritePages;
- public uint CcDataFlushes;
- public uint CcDataPages;
- public uint ContextSwitches;
- public uint FirstLevelTbFills;
- public uint SecondLevelTbFills;
- public uint SystemCalls;
+ public int CcFastReadResourceMiss;
+ public int CcFastReadNotPossible;
+ public int CcFastMdlReadNoWait;
+ public int CcFastMdlReadWait;
+ public int CcFastMdlReadResourceMiss;
+ public int CcFastMdlReadNotPossible;
+ public int CcMapDataNoWait;
+ public int CcMapDataWait;
+ public int CcMapDataNoWaitMiss;
+ public int CcMapDataWaitMiss;
+ public int CcPinMappedDataCount;
+ public int CcPinReadNoWait;
+ public int CcPinReadWait;
+ public int CcPinReadNoWaitMiss;
+ public int CcPinReadWaitMiss;
+ public int CcCopyReadNoWait;
+ public int CcCopyReadWait;
+ public int CcCopyReadNoWaitMiss;
+ public int CcCopyReadWaitMiss;
+ public int CcMdlReadNoWait;
+ public int CcMdlReadWait;
+ public int CcMdlReadNoWaitMiss;
+ public int CcMdlReadWaitMiss;
+ public int CcReadAheadIos;
+ public int CcLazyWriteIos;
+ public int CcLazyWritePages;
+ public int CcDataFlushes;
+ public int CcDataPages;
+ public int ContextSwitches;
+ public int FirstLevelTbFills;
+ public int SecondLevelTbFills;
+ public int SystemCalls;
}
[StructLayout(LayoutKind.Sequential)]
public struct SystemProcessInformation
{
- public static readonly int SizeOf;
-
public int NextEntryOffset;
public int NumberOfThreads;
public long SpareLi1;
@@ -3047,23 +2698,11 @@ public int InheritedFromProcessId
get { return _inheritedFromProcessId.ToInt32(); }
set { _inheritedFromProcessId = value.ToIntPtr(); }
}
-
- static SystemProcessInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SystemProcessInformation));
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct SystemProcessorPerformanceInformation
{
- public static readonly int SizeOf;
-
- static SystemProcessorPerformanceInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SystemProcessorPerformanceInformation));
- }
-
public long IdleTime;
public long KernelTime;
public long UserTime;
@@ -3083,13 +2722,6 @@ public struct SystemSessionProcessInformation
[StructLayout(LayoutKind.Sequential)]
public struct SystemThreadInformation
{
- public static readonly int SizeOf;
-
- static SystemThreadInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SystemThreadInformation));
- }
-
public long KernelTime;
public long UserTime;
public long CreateTime;
@@ -3106,8 +2738,6 @@ static SystemThreadInformation()
[StructLayout(LayoutKind.Sequential)]
public struct SystemTimeOfDayInformation
{
- public static readonly int SizeOf;
-
public long BootTime;
public long CurrentTime;
public long TimeZoneBias;
@@ -3115,11 +2745,6 @@ public struct SystemTimeOfDayInformation
public int Reserved;
public long BootTimeBias;
public long SleepTimeBias;
-
- static SystemTimeOfDayInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(SystemTimeOfDayInformation));
- }
}
[StructLayout(LayoutKind.Sequential)]
@@ -3146,8 +2771,6 @@ public unsafe struct Teb
[StructLayout(LayoutKind.Sequential)]
public struct ThreadBasicInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(ThreadBasicInformation));
-
public NtStatus ExitStatus;
public IntPtr TebBaseAddress;
public ClientId ClientId;
@@ -3159,13 +2782,6 @@ public struct ThreadBasicInformation
[StructLayout(LayoutKind.Sequential)]
public struct TimerBasicInformation
{
- public static readonly int SizeOf;
-
- static TimerBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(TimerBasicInformation));
- }
-
public LargeInteger RemainingTime;
[MarshalAs(UnmanagedType.I1)]
public bool TimerState;
@@ -3174,13 +2790,6 @@ static TimerBasicInformation()
[StructLayout(LayoutKind.Sequential)]
public struct TmBasicInformation
{
- public static readonly int SizeOf;
-
- static TmBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(TmBasicInformation));
- }
-
public Guid TmIdentity;
public long VirtualClock;
}
@@ -3188,13 +2797,6 @@ static TmBasicInformation()
[StructLayout(LayoutKind.Sequential)]
public struct TmLogInformation
{
- public static readonly int SizeOf;
-
- static TmLogInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(TmLogInformation));
- }
-
public Guid LogIdentity;
}
@@ -3218,13 +2820,6 @@ public struct TmLogPathInformation
[StructLayout(LayoutKind.Sequential)]
public struct TmRecoveryInformation
{
- public static readonly int SizeOf;
-
- static TmRecoveryInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(TmRecoveryInformation));
- }
-
public long LastRecoveredLsn;
}
@@ -3242,14 +2837,8 @@ public TokenDefaultDacl(Acl defaultDacl)
[StructLayout(LayoutKind.Sequential)]
public struct TokenGroups
{
- public static readonly int SizeOf;
- public static readonly int GroupsOffset;
-
- static TokenGroups()
- {
- SizeOf = Marshal.SizeOf(typeof(TokenGroups));
- GroupsOffset = Marshal.OffsetOf(typeof(TokenGroups), "Groups").ToInt32();
- }
+ public static readonly int GroupsOffset =
+ Marshal.OffsetOf(typeof(TokenGroups), "Groups").ToInt32();
public TokenGroups(Sid[] sids)
{
@@ -3305,8 +2894,6 @@ public TokenPrivileges(PrivilegeSet privileges)
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TokenSource
{
- public static readonly int SizeOf;
-
public TokenSource(string sourceName, Luid sourceIdentifier)
{
if (sourceName.Length > 8)
@@ -3320,18 +2907,11 @@ public TokenSource(string sourceName, Luid sourceIdentifier)
public string SourceName;
public Luid SourceIdentifier;
-
- static TokenSource()
- {
- SizeOf = Marshal.SizeOf(typeof(TokenSource));
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct TokenStatistics
{
- public static readonly int SizeOf;
-
public Luid TokenId;
public Luid AuthenticationId;
public long ExpirationTime;
@@ -3342,11 +2922,6 @@ public struct TokenStatistics
public int GroupCount;
public int PrivilegeCount;
public Luid ModifiedId;
-
- static TokenStatistics()
- {
- SizeOf = Marshal.SizeOf(typeof(TokenStatistics));
- }
}
[StructLayout(LayoutKind.Sequential)]
@@ -3363,13 +2938,6 @@ public TokenUser(Sid user)
[StructLayout(LayoutKind.Sequential)]
public struct TransactionBasicInformation
{
- public static readonly int SizeOf;
-
- static TransactionBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(TransactionBasicInformation));
- }
-
public Guid TransactionId;
public TransactionState State;
public TransactionOutcome Outcome;
@@ -3425,11 +2993,9 @@ public struct TransactionPropertiesInformation
[StructLayout(LayoutKind.Sequential)]
public struct UnicodeString : IComparable, IEquatable, IDisposable
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(UnicodeString));
-
public UnicodeString(string str)
{
- if (!string.IsNullOrEmpty(str))
+ if (str != null)
{
UnicodeString newString;
@@ -3474,13 +3040,14 @@ public void Dispose()
///
public UnicodeString Duplicate()
{
+ NtStatus status;
UnicodeString newString;
- Win32.RtlDuplicateUnicodeString(
- RtlDuplicateUnicodeStringFlags.AllocateNullString | RtlDuplicateUnicodeStringFlags.NullTerminate,
- ref this,
- out newString
- ).ThrowIf();
+ if ((status = Win32.RtlDuplicateUnicodeString(
+ RtlDuplicateUnicodeStringFlags.AllocateNullString |
+ RtlDuplicateUnicodeStringFlags.NullTerminate,
+ ref this, out newString)) >= NtStatus.Error)
+ Win32.Throw(status);
return newString;
}
@@ -3502,14 +3069,12 @@ public override int GetHashCode()
public int Hash(HashStringAlgorithm algorithm, bool caseInsensitive)
{
+ NtStatus status;
int hash;
- Win32.RtlHashUnicodeString(
- ref this,
- caseInsensitive,
- algorithm,
- out hash
- ).ThrowIf();
+ if ((status = Win32.RtlHashUnicodeString(ref this,
+ caseInsensitive, algorithm, out hash)) >= NtStatus.Error)
+ Win32.Throw(status);
return hash;
}
@@ -3524,21 +3089,18 @@ public int Hash()
return this.Hash(HashStringAlgorithm.Default);
}
- public string Text
+ public string Read()
{
- get
- {
- if (this.Length == 0)
- return string.Empty;
+ if (this.Length == 0)
+ return "";
- return Marshal.PtrToStringUni(this.Buffer, this.Length / 2);
- }
+ return Marshal.PtrToStringUni(this.Buffer, this.Length / 2);
}
public string Read(ProcessHandle processHandle)
{
if (this.Length == 0)
- return string.Empty;
+ return "";
byte[] strData = processHandle.ReadMemory(this.Buffer, this.Length);
GCHandle strDataHandle = GCHandle.Alloc(strData, GCHandleType.Pinned);
@@ -3565,23 +3127,27 @@ public bool StartsWith(UnicodeString unicodeString)
public AnsiString ToAnsiString()
{
+ NtStatus status;
AnsiString ansiStr = new AnsiString();
- Win32.RtlUnicodeStringToAnsiString(ref ansiStr, ref this, true).ThrowIf();
+ if ((status = Win32.RtlUnicodeStringToAnsiString(ref ansiStr, ref this, true)) >= NtStatus.Error)
+ Win32.Throw(status);
return ansiStr;
}
public override string ToString()
{
- return this.Text;
+ return this.Read();
}
public AnsiString ToUpperAnsiString()
{
+ NtStatus status;
AnsiString ansiStr = new AnsiString();
- Win32.RtlUpcaseUnicodeStringToAnsiString(ref ansiStr, ref this, true).ThrowIf();
+ if ((status = Win32.RtlUpcaseUnicodeStringToAnsiString(ref ansiStr, ref this, true)) >= NtStatus.Error)
+ Win32.Throw(status);
return ansiStr;
}
@@ -3590,8 +3156,6 @@ public AnsiString ToUpperAnsiString()
[StructLayout(LayoutKind.Sequential)]
public struct VmCounters
{
- public static readonly int SizeOf;
-
public IntPtr PeakVirtualSize;
public IntPtr VirtualSize;
public int PageFaultCount;
@@ -3603,18 +3167,11 @@ public struct VmCounters
public IntPtr QuotaNonPagedPoolUsage;
public IntPtr PagefileUsage;
public IntPtr PeakPagefileUsage;
-
- static VmCounters()
- {
- SizeOf = Marshal.SizeOf(typeof(VmCounters));
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct VmCountersEx
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(VmCountersEx));
-
public IntPtr PeakVirtualSize;
public IntPtr VirtualSize;
public int PageFaultCount;
@@ -3632,8 +3189,6 @@ public struct VmCountersEx
[StructLayout(LayoutKind.Sequential)]
public struct VmCountersEx64
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(VmCountersEx64));
-
public VmCountersEx64(VmCountersEx vm)
{
this.PeakVirtualSize = vm.PeakVirtualSize.ToInt64();
@@ -3665,7 +3220,7 @@ public VmCountersEx64(VmCountersEx vm)
public VmCountersEx ToVmCountersEx()
{
- return new VmCountersEx
+ return new VmCountersEx()
{
PeakVirtualSize = this.PeakVirtualSize.ToIntPtr(),
VirtualSize = this.VirtualSize.ToIntPtr(),
diff --git a/1.x/trunk/ProcessHacker.Native/Api/NtStatus.cs b/1.x/trunk/ProcessHacker.Native/Api/NtStatus.cs
index 04999f842..71822955d 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/NtStatus.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/NtStatus.cs
@@ -20,7 +20,6 @@
* along with Process Hacker. If not, see .
*/
-using System;
namespace ProcessHacker.Native.Api
{
///
@@ -390,7 +389,7 @@ public static string GetMessage(this NtStatus status)
{
// Fix those messages which are formatted like:
// {Asdf}\r\nAsdf asdf asdf...
- if (message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
+ if (message.StartsWith("{"))
{
string[] split = message.Split('\n');
diff --git a/1.x/trunk/ProcessHacker.Native/Api/SamDefinitions.cs b/1.x/trunk/ProcessHacker.Native/Api/SamDefinitions.cs
index 8f5be7a46..a60892232 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/SamDefinitions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/SamDefinitions.cs
@@ -1,4 +1,8 @@
-namespace ProcessHacker.Native.Api
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ProcessHacker.Native.Api
{
public static partial class Win32
{
diff --git a/1.x/trunk/ProcessHacker.Native/Api/SamFunctions.cs b/1.x/trunk/ProcessHacker.Native/Api/SamFunctions.cs
index ff866d897..569560248 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/SamFunctions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/SamFunctions.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
using ProcessHacker.Native.Security;
diff --git a/1.x/trunk/ProcessHacker.Native/Api/SamStructs.cs b/1.x/trunk/ProcessHacker.Native/Api/SamStructs.cs
index 88a61be2d..feb291d87 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/SamStructs.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/SamStructs.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace ProcessHacker.Native.Api
@@ -123,13 +124,6 @@ public struct SamByteArray32K
[StructLayout(LayoutKind.Sequential)]
public struct SamRidEnumeration
{
- public static readonly int SizeOf;
-
- static SamRidEnumeration()
- {
- SizeOf = Marshal.SizeOf(typeof(SamRidEnumeration));
- }
-
public int RelativeId;
public UnicodeString Name;
}
@@ -137,13 +131,6 @@ static SamRidEnumeration()
[StructLayout(LayoutKind.Sequential)]
public struct SamSidEnumeration
{
- public static readonly int SizeOf;
-
- static SamSidEnumeration()
- {
- SizeOf = Marshal.SizeOf(typeof(SamSidEnumeration));
- }
-
public IntPtr Sid; // Sid*
public UnicodeString Name;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Api/Structs.cs b/1.x/trunk/ProcessHacker.Native/Api/Structs.cs
index d13a2d40f..4deaccf49 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/Structs.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/Structs.cs
@@ -31,6 +31,7 @@
using System;
using System.Drawing;
using System.Runtime.InteropServices;
+using ProcessHacker.Native.Objects;
namespace ProcessHacker.Native.Api
{
@@ -91,13 +92,6 @@ public struct CMsgSignerInfo
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CredUiInfo
{
- public static readonly int SizeOf;
-
- static CredUiInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(CredUiInfo));
- }
-
public int Size;
public IntPtr Parent;
public string MessageText;
@@ -161,25 +155,6 @@ public struct CryptProviderSgnr
public IntPtr ChainContext;
}
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- public struct DlgTemplate
- {
- public static readonly int SizeOf;
-
- public int style;
- public int dwExtendedStyle;
- public short cdit;
- public short x;
- public short y;
- public short cx;
- public short cy;
-
- static DlgTemplate()
- {
- SizeOf = Marshal.SizeOf(typeof(DlgTemplate));
- }
- }
-
[StructLayout(LayoutKind.Sequential)]
public struct EnumServiceStatus
{
@@ -196,13 +171,6 @@ public struct EnumServiceStatus
[StructLayout(LayoutKind.Sequential)]
public struct EnumServiceStatusProcess
{
- public static readonly int SizeOf;
-
- static EnumServiceStatusProcess()
- {
- SizeOf = Marshal.SizeOf(typeof(EnumServiceStatusProcess));
- }
-
[MarshalAs(UnmanagedType.LPTStr)]
public string ServiceName;
@@ -235,13 +203,6 @@ public struct FpoData
[StructLayout(LayoutKind.Sequential)]
public struct HeapEntry32
{
- public static readonly int SizeOf;
-
- static HeapEntry32()
- {
- SizeOf = Marshal.SizeOf(typeof(HeapEntry32));
- }
-
public int dwSize;
public IntPtr hHandle;
public IntPtr dwAddress;
@@ -256,13 +217,6 @@ static HeapEntry32()
[StructLayout(LayoutKind.Sequential)]
public struct HeapList32
{
- public static readonly int SizeOf;
-
- static HeapList32()
- {
- SizeOf = Marshal.SizeOf(typeof(HeapList32));
- }
-
public int dwSize;
public int th32ProcessID;
public IntPtr th32HeapID;
@@ -335,13 +289,6 @@ public struct LoadedImage
[StructLayout(LayoutKind.Sequential)]
public struct LuidAndAttributes
{
- public static readonly int SizeOf;
-
- static LuidAndAttributes()
- {
- SizeOf = Marshal.SizeOf(typeof(LuidAndAttributes));
- }
-
public Luid Luid;
public SePrivilegeAttributes Attributes;
}
@@ -349,8 +296,6 @@ static LuidAndAttributes()
[StructLayout(LayoutKind.Sequential)]
public struct MemoryBasicInformation
{
- public static readonly int SizeOf;
-
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public MemoryProtection AllocationProtect;
@@ -358,11 +303,6 @@ public struct MemoryBasicInformation
public MemoryState State;
public MemoryProtection Protect;
public MemoryType Type;
-
- static MemoryBasicInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(MemoryBasicInformation));
- }
}
[StructLayout(LayoutKind.Sequential, Pack = 16)]
@@ -371,12 +311,12 @@ public struct MemoryBasicInformation64
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public MemoryProtection AllocationProtect;
- public int _alignment1;
+ private int _alignment1;
public ulong RegionSize;
public MemoryState State;
public MemoryProtection Protect;
public MemoryType Type;
- public int _alignment2;
+ private int _alignment2;
}
[StructLayout(LayoutKind.Sequential)]
@@ -418,13 +358,6 @@ public struct MibTcp6Row2
[StructLayout(LayoutKind.Sequential)]
public struct MibTcpRowOwnerPid
{
- public static readonly int SizeOf;
-
- static MibTcpRowOwnerPid()
- {
- SizeOf = Marshal.SizeOf(typeof(MibTcpRowOwnerPid));
- }
-
public MibTcpState State;
public uint LocalAddress;
public int LocalPort;
@@ -435,14 +368,7 @@ static MibTcpRowOwnerPid()
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MibTcp6RowOwnerPid
- {
- public static readonly int SizeOf;
-
- static MibTcp6RowOwnerPid()
- {
- SizeOf = Marshal.SizeOf(typeof(MibTcp6RowOwnerPid));
- }
-
+ {
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] LocalAddress;
public uint LocalScopeId;
@@ -534,14 +460,7 @@ public struct MibUdp6Table
[StructLayout(LayoutKind.Sequential)]
public struct MibUdpRowOwnerPid
- {
- public static readonly int SizeOf;
-
- static MibUdpRowOwnerPid()
- {
- SizeOf = Marshal.SizeOf(typeof(MibUdpRowOwnerPid));
- }
-
+ {
public uint LocalAddress;
public int LocalPort;
public int OwningProcessId;
@@ -550,13 +469,6 @@ static MibUdpRowOwnerPid()
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MibUdp6RowOwnerPid
{
- public static readonly int SizeOf;
-
- static MibUdp6RowOwnerPid()
- {
- SizeOf = Marshal.SizeOf(typeof(MibUdp6RowOwnerPid));
- }
-
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] LocalAddress;
public uint LocalScopeId;
@@ -626,13 +538,6 @@ public struct ModuleEntry32
[StructLayout(LayoutKind.Sequential)]
public struct ModuleInfo
{
- public static readonly int SizeOf;
-
- static ModuleInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(ModuleInfo));
- }
-
public IntPtr BaseOfDll;
public int SizeOfImage;
public IntPtr EntryPoint;
@@ -647,84 +552,23 @@ public struct MonitorInformation
public uint Flags;
}
- ///
- /// Contains performance information.
- ///
- /// http://msdn.microsoft.com/en-us/library/ms684824.aspx
[StructLayout(LayoutKind.Sequential)]
public struct PerformanceInformation
{
- public static readonly int SizeOf = Marshal.SizeOf(typeof(PerformanceInformation));
-
- ///
- /// The size of this structure, in bytes.
- ///
- public int cbSize;
-
- ///
- /// The number of pages currently committed by the system. Note that committing pages (using VirtualAlloc with MEM_COMMIT) changes this value immediately; however, the physical memory is not charged until the pages are accessed.
- ///
+ public int Size;
public IntPtr CommitTotal;
-
- ///
- /// The current maximum number of pages that can be committed by the system without extending the paging file(s). This number can change if memory is added or deleted, or if pagefiles have grown, shrunk, or been added. If the paging file can be extended, this is a soft limit.
- ///
public IntPtr CommitLimit;
-
- ///
- /// The maximum number of pages that were simultaneously in the committed state since the last system reboot.
- ///
public IntPtr CommitPeak;
-
- ///
- /// The amount of actual physical memory, in pages.
- ///
public IntPtr PhysicalTotal;
-
- ///
- /// The amount of physical memory currently available, in pages. This is the amount of physical memory that can be immediately reused without having to write its contents to disk first. It is the sum of the size of the standby, free, and zero lists.
- ///
public IntPtr PhysicalAvailable;
-
- ///
- /// The amount of system cache memory, in pages. This is the size of the standby list plus the system working set.
- ///
public IntPtr SystemCache;
-
- ///
- /// The sum of the memory currently in the paged and nonpaged kernel pools, in pages.
- ///
public IntPtr KernelTotal;
-
- ///
- /// The memory currently in the paged kernel pool, in pages.
- ///
public IntPtr KernelPaged;
-
- ///
- /// The memory currently in the nonpaged kernel pool, in pages.
- ///
public IntPtr KernelNonPaged;
-
- ///
- /// The size of a page, in bytes.
- ///
public IntPtr PageSize;
-
- ///
- /// The current number of open handles.
- ///
- public uint HandlesCount;
-
- ///
- /// The current number of processes.
- ///
- public uint ProcessCount;
-
- ///
- /// The current number of threads.
- ///
- public uint ThreadCount;
+ public int HandlesCount;
+ public int ProcessCount;
+ public int ThreadCount;
}
[StructLayout(LayoutKind.Sequential)]
@@ -753,32 +597,6 @@ public struct ProcessInformation
public int ThreadId;
}
- [StructLayout(LayoutKind.Sequential)]
- public struct PropSheetPageW
- {
- public static readonly int SizeOf;
-
- static PropSheetPageW()
- {
- SizeOf = Marshal.SizeOf(typeof(PropSheetPageW));
- }
-
- public int dwSize;
- public PropSheetPageFlags dwFlags;
- public IntPtr hInstance;
-
- public IntPtr pResource; // pszTemplate
- public IntPtr hIcon;
- public IntPtr pszTitle;
- public IntPtr pfnDlgProc;
- public IntPtr lParam;
- public IntPtr pfnCallback;
- public IntPtr pcRefParent;
- public IntPtr pszHeaderTitle;
- public IntPtr pszHeaderSubTitle;
- public IntPtr hActCtx;
- }
-
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ProfileInformation
{
@@ -847,13 +665,6 @@ public struct ScAction
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SecPkgInfo
{
- public static readonly int SizeOf;
-
- static SecPkgInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(SecPkgInfo));
- }
-
public int Capabilities;
public ushort Version;
public ushort RpcId;
@@ -884,13 +695,6 @@ public struct ServiceStatus
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatusProcess
{
- public static readonly int SizeOf;
-
- static ServiceStatusProcess()
- {
- SizeOf = Marshal.SizeOf(typeof(ServiceStatusProcess));
- }
-
public ServiceType ServiceType;
public ServiceState CurrentState;
public ServiceAccept ControlsAccepted;
@@ -905,13 +709,6 @@ static ServiceStatusProcess()
[StructLayout(LayoutKind.Sequential)]
public struct ShellExecuteInfo
{
- public static readonly int SizeOf;
-
- static ShellExecuteInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(ShellExecuteInfo));
- }
-
public int cbSize;
public uint fMask;
public IntPtr hWnd;
@@ -933,13 +730,6 @@ static ShellExecuteInfo()
[StructLayout(LayoutKind.Sequential)]
public struct ShFileInfo
{
- public static readonly int SizeOf;
-
- static ShFileInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(ShFileInfo));
- }
-
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
@@ -952,13 +742,6 @@ static ShFileInfo()
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SiAccess
{
- public static readonly int SizeOf;
-
- static SiAccess()
- {
- SizeOf = Marshal.SizeOf(typeof(SiAccess));
- }
-
public IntPtr Guid;
public int Mask;
public IntPtr Name; // string
@@ -1010,13 +793,6 @@ public struct StackFrame64
[StructLayout(LayoutKind.Sequential)]
public struct StartupInfo
{
- public static readonly int SizeOf;
-
- static StartupInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(StartupInfo));
- }
-
public int Size;
[MarshalAs(UnmanagedType.LPWStr)]
public string Reserved;
@@ -1043,8 +819,7 @@ static StartupInfo()
[StructLayout(LayoutKind.Sequential)]
public struct SymbolInfo
{
- public static readonly int SizeOf;
- public static readonly int NameOffset;
+ public static readonly int NameOffset = Marshal.OffsetOf(typeof(SymbolInfo), "Name").ToInt32();
public int SizeOfStruct;
public int TypeIndex;
@@ -1061,12 +836,6 @@ public struct SymbolInfo
public int NameLen;
public int MaxNameLen;
public byte Name;
-
- static SymbolInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(SymbolInfo));
- NameOffset = Marshal.OffsetOf(typeof(SymbolInfo), "Name").ToInt32();
- }
}
[StructLayout(LayoutKind.Sequential)]
@@ -1090,8 +859,8 @@ public struct WindowClass
public int Styles;
[MarshalAs(UnmanagedType.FunctionPtr)]
public WndProcDelegate WindowsProc;
- public int ExtraClassData;
- public int ExtraWindowData;
+ private int ExtraClassData;
+ private int ExtraWindowData;
public IntPtr InstanceHandle;
public IntPtr IconHandle;
public IntPtr CursorHandle;
@@ -1105,13 +874,6 @@ public struct WindowClass
[StructLayout(LayoutKind.Sequential)]
public struct WindowPlacement
{
- public static readonly int SizeOf;
-
- static WindowPlacement()
- {
- SizeOf = Marshal.SizeOf(typeof(WindowPlacement));
- }
-
public int Length;
public WindowPlacementFlags Flags;
public ShowWindowType ShowState;
@@ -1123,13 +885,6 @@ static WindowPlacement()
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WintrustCatalogInfo
{
- public static readonly int SizeOf;
-
- static WintrustCatalogInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(WintrustCatalogInfo));
- }
-
public int Size;
public int CatalogVersion;
public string CatalogFilePath;
@@ -1144,13 +899,6 @@ static WintrustCatalogInfo()
[StructLayout(LayoutKind.Sequential)]
public struct WintrustData
{
- public static readonly int SizeOf;
-
- static WintrustData()
- {
- SizeOf = Marshal.SizeOf(typeof(WintrustData));
- }
-
public int Size;
public IntPtr PolicyCallbackData;
public IntPtr SIPClientData;
@@ -1168,13 +916,6 @@ static WintrustData()
[StructLayout(LayoutKind.Sequential)]
public struct WintrustFileInfo
{
- public static readonly int SizeOf;
-
- static WintrustFileInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(WintrustFileInfo));
- }
-
public int Size;
public IntPtr FilePath;
public IntPtr FileHandle;
@@ -1200,13 +941,6 @@ public struct WtsClientDisplay
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WtsProcessInfo
{
- public static readonly int SizeOf;
-
- static WtsProcessInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(WtsProcessInfo));
- }
-
public int SessionId;
public int ProcessId;
public IntPtr ProcessName;
@@ -1216,13 +950,6 @@ static WtsProcessInfo()
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WtsSessionInfo
{
- public static readonly int SizeOf;
-
- static WtsSessionInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(WtsSessionInfo));
- }
-
public int SessionID;
public string WinStationName;
public WtsConnectStateClass State;
diff --git a/1.x/trunk/ProcessHacker.Native/Api/Win32.cs b/1.x/trunk/ProcessHacker.Native/Api/Win32.cs
index 537ca5121..2cb1d0393 100644
--- a/1.x/trunk/ProcessHacker.Native/Api/Win32.cs
+++ b/1.x/trunk/ProcessHacker.Native/Api/Win32.cs
@@ -39,20 +39,18 @@ namespace ProcessHacker.Native.Api
public delegate IntPtr WndProcDelegate(IntPtr hWnd, WindowMessage msg, IntPtr wParam, IntPtr lParam);
public delegate bool SymEnumSymbolsProc(IntPtr SymInfo, int SymbolSize, int UserContext);
- public delegate bool ReadProcessMemoryProc64(IntPtr ProcessHandle, ulong BaseAddress, IntPtr Buffer, int Size, out int BytesRead);
+ public unsafe delegate bool ReadProcessMemoryProc64(IntPtr ProcessHandle, ulong BaseAddress, IntPtr Buffer,
+ int Size, out int BytesRead);
public delegate IntPtr FunctionTableAccessProc64(IntPtr ProcessHandle, ulong AddrBase);
public delegate ulong GetModuleBaseProc64(IntPtr ProcessHandle, ulong Address);
- public delegate int PropSheetPageCallback(IntPtr hwnd, PropSheetPageCallbackMessage uMsg, IntPtr ppsp);
- public delegate bool DialogProc(IntPtr hwndDlg, WindowMessage uMsg, IntPtr wParam, IntPtr lParam);
-
///
/// Provides interfacing to the Win32 and Native APIs.
///
[SuppressUnmanagedCodeSecurity]
public static partial class Win32
{
- private static readonly FastMutex _dbgHelpLock = new FastMutex();
+ private static FastMutex _dbgHelpLock = new FastMutex();
///
/// A mutex which controls access to the dbghelp.dll functions.
@@ -95,12 +93,7 @@ public static string GetLastErrorMessage()
///
public static void Throw()
{
- Win32Error last = GetLastErrorCode();
-
- if (last != Win32Error.Success)
- {
- Throw(last);
- }
+ Throw(GetLastErrorCode());
}
public static void Throw(NtStatus status)
@@ -122,7 +115,7 @@ public static void Throw(Win32Error error)
#region Handles
- public static void DuplicateObject(
+ public unsafe static void DuplicateObject(
IntPtr sourceProcessHandle,
IntPtr sourceHandle,
int desiredAccess,
@@ -143,7 +136,7 @@ DuplicateOptions options
);
}
- public static void DuplicateObject(
+ public unsafe static void DuplicateObject(
IntPtr sourceProcessHandle,
IntPtr sourceHandle,
IntPtr targetProcessHandle,
@@ -153,15 +146,34 @@ public static void DuplicateObject(
DuplicateOptions options
)
{
- NtDuplicateObject(
- sourceProcessHandle,
- sourceHandle,
- targetProcessHandle,
- out targetHandle,
- desiredAccess,
- handleAttributes,
- options
- ).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ int target;
+
+ KProcessHacker.Instance.KphDuplicateObject(
+ sourceProcessHandle.ToInt32(),
+ sourceHandle.ToInt32(),
+ targetProcessHandle.ToInt32(),
+ out target,
+ desiredAccess,
+ handleAttributes,
+ options);
+ targetHandle = new IntPtr(target);
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = NtDuplicateObject(
+ sourceProcessHandle,
+ sourceHandle,
+ targetProcessHandle,
+ out targetHandle,
+ desiredAccess,
+ handleAttributes,
+ options)) >= NtStatus.Error)
+ Throw(status);
+ }
}
#endregion
@@ -181,7 +193,7 @@ public static int GetProcessSessionId(int ProcessId)
{
using (ProcessHandle phandle = new ProcessHandle(ProcessId, OSVersion.MinProcessQueryInfoAccess))
{
- return phandle.GetToken(TokenAccess.Query).SessionId;
+ return phandle.GetToken(TokenAccess.Query).GetSessionId();
}
}
@@ -190,43 +202,6 @@ public static int GetProcessSessionId(int ProcessId)
#endregion
- #region Property Sheets
-
- [DllImport("comctl32.dll")]
- public static extern IntPtr CreatePropertySheetPageW(
- ref PropSheetPageW lppsp
- );
-
- [DllImport("user32.dll")]
- public static extern bool MapDialogRect(
- IntPtr hDlg,
- ref Rect lpRect
- );
-
- [DllImport("user32.dll")]
- public static extern IntPtr SetParent(
- IntPtr hWndChild,
- IntPtr hWndNewParent
- );
-
- [DllImport("user32.dll")]
- public static extern IntPtr SendMessage(
- IntPtr hWnd,
- int Msg,
- IntPtr wParam,
- IntPtr lParam
- );
-
- [StructLayout(LayoutKind.Sequential)]
- public struct NmHdr
- {
- public IntPtr hwndFrom;
- public IntPtr idFrom;
- public uint code;
- }
-
- #endregion
-
#region TCP
public static MibTcpStats GetTcpStats()
@@ -253,7 +228,7 @@ public static MibTcpTableOwnerPid GetTcpTable()
table.Table = new MibTcpRowOwnerPid[count];
for (int i = 0; i < count; i++)
- table.Table[i] = mem.ReadStruct(sizeof(int), MibTcpRowOwnerPid.SizeOf, i);
+ table.Table[i] = mem.ReadStruct(sizeof(int), i);
}
return table;
@@ -274,11 +249,13 @@ public unsafe static WtsEnumProcessesFastData TSEnumProcessesFast()
{
IntPtr processes;
int count;
+ int[] pids;
+ IntPtr[] sids;
WTSEnumerateProcesses(IntPtr.Zero, 0, 1, out processes, out count);
- int[] pids = new int[count];
- IntPtr[] sids = new IntPtr[count];
+ pids = new int[count];
+ sids = new IntPtr[count];
WtsMemoryAlloc data = new WtsMemoryAlloc(processes);
WtsProcessInfo* dataP = (WtsProcessInfo*)data.Memory;
@@ -289,12 +266,7 @@ public unsafe static WtsEnumProcessesFastData TSEnumProcessesFast()
sids[i] = dataP[i].Sid;
}
- return new WtsEnumProcessesFastData
- {
- PIDs = pids,
- SIDs = sids,
- Memory = data
- };
+ return new WtsEnumProcessesFastData() { PIDs = pids, SIDs = sids, Memory = data };
}
#endregion
@@ -325,7 +297,7 @@ public static MibUdpTableOwnerPid GetUdpTable()
table.Table = new MibUdpRowOwnerPid[count];
for (int i = 0; i < count; i++)
- table.Table[i] = mem.ReadStruct(sizeof(int), MibTcpRowOwnerPid.SizeOf, i);
+ table.Table[i] = mem.ReadStruct(sizeof(int), i);
}
return table;
@@ -358,7 +330,7 @@ public unsafe static string[] GetMultiString(IntPtr ptr)
string str = currentString.ToString();
- if (string.IsNullOrEmpty(str))
+ if (str == "")
{
break;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Cryptography.cs b/1.x/trunk/ProcessHacker.Native/Cryptography.cs
index 857f409e9..10d1aba91 100644
--- a/1.x/trunk/ProcessHacker.Native/Cryptography.cs
+++ b/1.x/trunk/ProcessHacker.Native/Cryptography.cs
@@ -56,7 +56,7 @@ public static class Cryptography
new Guid("{fc451c16-ac75-11d1-b4b8-00c04fb66ea0}");
public static readonly Guid WintrustActionGenericVerifyV2 =
new Guid("{00aac56b-cd44-11d0-8cc2-00c04fc295ee}");
- public static readonly Guid WintrustActionTrustProviderTest =
+ public static readonly System.Guid WintrustActionTrustProviderTest =
new Guid("{573e31f8-ddba-11d0-8ccb-00c04fc295ee}");
private static string GetX500Value(string subject, string keyName)
@@ -106,12 +106,14 @@ private static string GetSignerNameFromStateData(IntPtr stateData)
// Well, here's a shitload of indirection for you...
// 1. State data -> Provider data
+
IntPtr provData = Win32.WTHelperProvDataFromStateData(stateData);
if (provData == IntPtr.Zero)
return null;
// 2. Provider data -> Provider signer
+
IntPtr signerInfo = Win32.WTHelperGetProvSignerFromChain(provData, 0, false, 0);
if (signerInfo == IntPtr.Zero)
@@ -125,22 +127,25 @@ private static string GetSignerNameFromStateData(IntPtr stateData)
return null;
// 3. Provider signer -> Provider cert
+
CryptProviderCert cert = (CryptProviderCert)Marshal.PtrToStructure(sngr.CertChain, typeof(CryptProviderCert));
if (cert.Cert == IntPtr.Zero)
return null;
// 4. Provider cert -> Cert context
+
CertContext context = (CertContext)Marshal.PtrToStructure(cert.Cert, typeof(CertContext));
if (context.CertInfo != IntPtr.Zero)
{
// 5. Cert context -> Cert info
+
CertInfo certInfo = (CertInfo)Marshal.PtrToStructure(context.CertInfo, typeof(CertInfo));
unsafe
{
- using (MemoryAlloc buffer = new MemoryAlloc(0x200))
+ using (var buffer = new MemoryAlloc(0x200))
{
int length;
@@ -168,12 +173,13 @@ private static string GetSignerNameFromStateData(IntPtr stateData)
}
string name = buffer.ReadUnicodeString(0);
+ string value;
// 7. Subject X.500 string -> CN or OU value
- string value = GetX500Value(name, "CN");
+ value = GetX500Value(name, "CN");
- if (string.IsNullOrEmpty(value))
+ if (value == null)
value = GetX500Value(name, "OU");
return value;
@@ -186,23 +192,20 @@ private static string GetSignerNameFromStateData(IntPtr stateData)
public static VerifyResult StatusToVerifyResult(uint status)
{
- switch (status)
- {
- case 0:
- return VerifyResult.Trusted;
- case 0x800b0100:
- return VerifyResult.NoSignature;
- case 0x800b0101:
- return VerifyResult.Expired;
- case 0x800b010c:
- return VerifyResult.Revoked;
- case 0x800b0111:
- return VerifyResult.Distrust;
- case 0x80092026:
- return VerifyResult.SecuritySettings;
- default:
- return VerifyResult.SecuritySettings;
- }
+ if (status == 0)
+ return VerifyResult.Trusted;
+ else if (status == 0x800b0100)
+ return VerifyResult.NoSignature;
+ else if (status == 0x800b0101)
+ return VerifyResult.Expired;
+ else if (status == 0x800b010c)
+ return VerifyResult.Revoked;
+ else if (status == 0x800b0111)
+ return VerifyResult.Distrust;
+ else if (status == 0x80092026)
+ return VerifyResult.SecuritySettings;
+ else
+ return VerifyResult.SecuritySettings;
}
public static VerifyResult VerifyFile(string fileName)
@@ -214,7 +217,7 @@ public static VerifyResult VerifyFile(string fileName)
public static VerifyResult VerifyFile(string fileName, out string signerName)
{
- VerifyResult result;
+ VerifyResult result = VerifyResult.NoSignature;
using (MemoryAlloc strMem = new MemoryAlloc(fileName.Length * 2 + 2))
{
@@ -223,25 +226,24 @@ public static VerifyResult VerifyFile(string fileName, out string signerName)
strMem.WriteUnicodeString(0, fileName);
strMem.WriteInt16(fileName.Length * 2, 0);
- fileInfo.Size = WintrustFileInfo.SizeOf;
+ fileInfo.Size = Marshal.SizeOf(fileInfo);
fileInfo.FilePath = strMem;
- WintrustData trustData = new WintrustData
- {
- Size = WintrustData.SizeOf,
- UIChoice = 2, // WTD_UI_NONE
- UnionChoice = 1, // WTD_CHOICE_FILE
- RevocationChecks = WtdRevocationChecks.None,
- ProvFlags = WtdProvFlags.Safer,
- StateAction = WtdStateAction.Verify
- };
+ WintrustData trustData = new WintrustData();
+
+ trustData.Size = Marshal.SizeOf(typeof(WintrustData));
+ trustData.UIChoice = 2; // WTD_UI_NONE
+ trustData.UnionChoice = 1; // WTD_CHOICE_FILE
+ trustData.RevocationChecks = WtdRevocationChecks.None;
+ trustData.ProvFlags = WtdProvFlags.Safer;
+ trustData.StateAction = WtdStateAction.Verify;
if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
trustData.ProvFlags |= WtdProvFlags.CacheOnlyUrlRetrieval;
using (MemoryAlloc mem = new MemoryAlloc(fileInfo.Size))
{
- mem.WriteStruct(fileInfo);
+ mem.WriteStruct(fileInfo);
trustData.UnionData = mem;
uint winTrustResult = Win32.WinVerifyTrust(IntPtr.Zero, WintrustActionGenericVerifyV2, ref trustData);
@@ -268,7 +270,8 @@ public static VerifyResult VerifyFile(string fileName, out string signerName)
signerName = null;
- using (FileHandle sourceFile = FileHandle.CreateWin32(fileName, FileAccess.GenericRead, FileShareMode.Read, FileCreationDispositionWin32.OpenExisting))
+ using (FileHandle sourceFile = FileHandle.CreateWin32(fileName, FileAccess.GenericRead, FileShareMode.Read,
+ FileCreationDispositionWin32.OpenExisting))
{
byte[] hash = new byte[256];
int hashLength = 256;
@@ -308,29 +311,27 @@ public static VerifyResult VerifyFile(string fileName, out string signerName)
return VerifyResult.NoSignature;
}
- WintrustCatalogInfo wci = new WintrustCatalogInfo
- {
- Size = WintrustCatalogInfo.SizeOf,
- CatalogFilePath = ci.CatalogFile,
- MemberFilePath = fileName,
- MemberTag = memberTag.ToString()
- };
+ WintrustCatalogInfo wci = new WintrustCatalogInfo();
- WintrustData trustData = new WintrustData
- {
- Size = WintrustData.SizeOf,
- UIChoice = 1,
- UnionChoice = 2,
- RevocationChecks = WtdRevocationChecks.None,
- StateAction = WtdStateAction.Verify
- };
+ wci.Size = Marshal.SizeOf(wci);
+ wci.CatalogFilePath = ci.CatalogFile;
+ wci.MemberFilePath = fileName;
+ wci.MemberTag = memberTag.ToString();
+
+ WintrustData trustData = new WintrustData();
+
+ trustData.Size = Marshal.SizeOf(typeof(WintrustData));
+ trustData.UIChoice = 1;
+ trustData.UnionChoice = 2;
+ trustData.RevocationChecks = WtdRevocationChecks.None;
+ trustData.StateAction = WtdStateAction.Verify;
if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
trustData.ProvFlags = WtdProvFlags.CacheOnlyUrlRetrieval;
using (MemoryAlloc mem = new MemoryAlloc(wci.Size))
{
- mem.WriteStruct(wci);
+ mem.WriteStruct(wci);
try
{
diff --git a/1.x/trunk/ProcessHacker.Native/Debugging/DebugBuffer.cs b/1.x/trunk/ProcessHacker.Native/Debugging/DebugBuffer.cs
index 1a89a5ea3..72213a4c4 100644
--- a/1.x/trunk/ProcessHacker.Native/Debugging/DebugBuffer.cs
+++ b/1.x/trunk/ProcessHacker.Native/Debugging/DebugBuffer.cs
@@ -37,7 +37,7 @@ namespace ProcessHacker.Native.Debugging
///
public sealed class DebugBuffer : BaseObject
{
- private readonly IntPtr _buffer;
+ private IntPtr _buffer;
///
/// Creates a new debug buffer.
@@ -64,7 +64,7 @@ protected override void DisposeObject(bool disposing)
/// The callback for the enumeration.
public void EnumHeaps(DebugEnumHeapsDelegate callback)
{
- RtlDebugInformation debugInfo = this.GetDebugInformation();
+ var debugInfo = this.GetDebugInformation();
if (debugInfo.Heaps == IntPtr.Zero)
throw new InvalidOperationException("Heap information does not exist.");
@@ -74,7 +74,7 @@ public void EnumHeaps(DebugEnumHeapsDelegate callback)
for (int i = 0; i < heaps.NumberOfHeaps; i++)
{
- RtlHeapInformation heap = heapInfo.ReadStruct(RtlProcessHeaps.HeapsOffset, RtlHeapInformation.SizeOf, i);
+ var heap = heapInfo.ReadStruct(RtlProcessHeaps.HeapsOffset, i);
if (!callback(new HeapInformation(heap)))
break;
@@ -97,7 +97,7 @@ public void EnumLocks(DebugEnumLocksDelegate callback)
for (int i = 0; i < locks.NumberOfLocks; i++)
{
- var lock_ = locksInfo.ReadStruct(sizeof(int), RtlProcessLockInformation.SizeOf, i);
+ var lock_ = locksInfo.ReadStruct(sizeof(int), i);
if (!callback(new LockInformation(lock_)))
break;
@@ -110,17 +110,17 @@ public void EnumLocks(DebugEnumLocksDelegate callback)
/// The callback for the enumeration.
public void EnumModules(DebugEnumModulesDelegate callback)
{
- RtlDebugInformation debugInfo = this.GetDebugInformation();
+ var debugInfo = this.GetDebugInformation();
if (debugInfo.Modules == IntPtr.Zero)
throw new InvalidOperationException("Module information does not exist.");
MemoryRegion modulesInfo = new MemoryRegion(debugInfo.Modules);
- RtlProcessModules modules = modulesInfo.ReadStruct();
+ var modules = modulesInfo.ReadStruct();
for (int i = 0; i < modules.NumberOfModules; i++)
{
- var module = modulesInfo.ReadStruct(RtlProcessModules.ModulesOffset, RtlProcessModuleInformation.SizeOf, i);
+ var module = modulesInfo.ReadStruct(RtlProcessModules.ModulesOffset, i);
if (!callback(new ModuleInformation(module)))
break;
@@ -146,7 +146,7 @@ public HeapInformation[] GetHeaps()
{
List heaps = new List();
- this.EnumHeaps(heap =>
+ this.EnumHeaps((heap) =>
{
heaps.Add(heap);
return true;
@@ -163,7 +163,7 @@ public LockInformation[] GetLocks()
{
List locks = new List();
- this.EnumLocks(lock_ =>
+ this.EnumLocks((lock_) =>
{
locks.Add(lock_);
return true;
@@ -180,7 +180,7 @@ public ModuleInformation[] GetModules()
{
List modules = new List();
- this.EnumModules(module =>
+ this.EnumModules((module) =>
{
modules.Add(module);
return true;
@@ -195,7 +195,7 @@ public ModuleInformation[] GetModules()
/// The information to query.
public void Query(RtlQueryProcessDebugFlags flags)
{
- this.Query(ProcessHandle.CurrentId, flags);
+ this.Query(ProcessHandle.GetCurrentId(), flags);
}
///
@@ -205,11 +205,14 @@ public void Query(RtlQueryProcessDebugFlags flags)
/// The information to query.
public void Query(int pid, RtlQueryProcessDebugFlags flags)
{
- Win32.RtlQueryProcessDebugInformation(
+ NtStatus status;
+
+ if ((status = Win32.RtlQueryProcessDebugInformation(
pid.ToIntPtr(),
flags,
_buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -217,7 +220,10 @@ public void Query(int pid, RtlQueryProcessDebugFlags flags)
///
public void QueryBackTraces()
{
- Win32.RtlQueryProcessBackTraceInformation(_buffer).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.RtlQueryProcessBackTraceInformation(_buffer)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -225,7 +231,10 @@ public void QueryBackTraces()
///
public void QueryHeaps()
{
- Win32.RtlQueryProcessHeapInformation(_buffer).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.RtlQueryProcessHeapInformation(_buffer)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -233,7 +242,10 @@ public void QueryHeaps()
///
public void QueryLocks()
{
- Win32.RtlQueryProcessLockInformation(_buffer).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.RtlQueryProcessLockInformation(_buffer)) >= NtStatus.Error)
+ Win32.Throw(status);
}
//public void QueryModules()
@@ -243,11 +255,14 @@ public void QueryLocks()
//public void QueryModules(ProcessHandle processHandle, RtlQueryProcessDebugFlags flags)
//{
- // Win32.RtlQueryProcessModuleInformation(
+ // NtStatus status;
+
+ // if ((status = Win32.RtlQueryProcessModuleInformation(
// processHandle ?? IntPtr.Zero,
// flags,
// _buffer
- // ).ThrowIf();
+ // )) >= NtStatus.Error)
+ // Win32.ThrowLastError(status);
//}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/FileUtils.cs b/1.x/trunk/ProcessHacker.Native/FileUtils.cs
index cc4097790..401f77ec6 100644
--- a/1.x/trunk/ProcessHacker.Native/FileUtils.cs
+++ b/1.x/trunk/ProcessHacker.Native/FileUtils.cs
@@ -23,6 +23,8 @@
using System;
using System.Collections.Generic;
using System.Drawing;
+using System.Runtime.InteropServices;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -42,18 +44,20 @@ static FileUtils()
///
/// Used to resolve device prefixes (\Device\Harddisk1) into DOS drive names.
///
- private static Dictionary _fileNamePrefixes;
+ private static Dictionary _fileNamePrefixes = new Dictionary();
public static string FindFile(string basePath, string fileName)
{
- if (!string.IsNullOrEmpty(basePath))
+ string path;
+
+ if (basePath != null)
{
// Search the base path first.
if (System.IO.File.Exists(basePath + "\\" + fileName))
return System.IO.Path.Combine(basePath, fileName);
}
- string path = Environment.GetEnvironmentVariable("Path");
+ path = Environment.GetEnvironmentVariable("Path");
string[] directories = path.Split(';');
@@ -68,11 +72,12 @@ public static string FindFile(string basePath, string fileName)
public static string FindFileWin32(string fileName)
{
- using (MemoryAlloc data = new MemoryAlloc(0x400))
+ using (var data = new MemoryAlloc(0x400))
{
+ int retLength;
IntPtr filePart;
- int retLength = Win32.SearchPath(null, fileName, null, data.Size / 2, data, out filePart);
+ retLength = Win32.SearchPath(null, fileName, null, data.Size / 2, data, out filePart);
if (retLength * 2 > data.Size)
{
@@ -94,26 +99,24 @@ public static Icon GetFileIcon(string fileName)
public static Icon GetFileIcon(string fileName, bool large)
{
+ ShFileInfo shinfo = new ShFileInfo();
+
if (string.IsNullOrEmpty(fileName))
throw new Exception("File name cannot be empty.");
try
{
- ShFileInfo shinfo;
-
- if (Win32.SHGetFileInfo(
- fileName,
- 0,
- out shinfo,
- (uint)ShFileInfo.SizeOf,
+ if (Win32.SHGetFileInfo(fileName, 0, out shinfo,
+ (uint)Marshal.SizeOf(shinfo),
Win32.ShgFiIcon |
- (large ? Win32.ShgFiLargeIcon : Win32.ShgFiSmallIcon)
- ) == 0)
+ (large ? Win32.ShgFiLargeIcon : Win32.ShgFiSmallIcon)) == 0)
{
return null;
}
-
- return Icon.FromHandle(shinfo.hIcon);
+ else
+ {
+ return Icon.FromHandle(shinfo.hIcon);
+ }
}
catch
{
@@ -121,43 +124,6 @@ public static Icon GetFileIcon(string fileName, bool large)
}
}
- public static unsafe string GetVistaFileName(int pid)
- {
- using (MemoryAlloc buffer = new MemoryAlloc(0x100))
- {
- SystemProcessImageNameInformation info;
-
- info.ProcessId = pid;
- info.ImageName.Length = 0;
- info.ImageName.MaximumLength = 0x100;
- info.ImageName.Buffer = buffer;
-
- NtStatus status = Win32.NtQuerySystemInformation(
- SystemInformationClass.SystemProcessImageName,
- &info,
- SystemProcessImageNameInformation.SizeOf,
- null
- );
-
- if (status == NtStatus.InfoLengthMismatch)
- {
- // Our buffer was too small. The required buffer length is stored in MaximumLength.
- buffer.ResizeNew(info.ImageName.MaximumLength);
-
- status = Win32.NtQuerySystemInformation(
- SystemInformationClass.SystemProcessImageName,
- &info,
- SystemProcessImageNameInformation.SizeOf,
- null
- );
- }
-
- status.ThrowIf();
-
- return GetFileName(info.ImageName.Text);
- }
- }
-
public static string GetFileName(string fileName)
{
return GetFileName(fileName, false);
@@ -180,23 +146,25 @@ public static string GetFileName(string fileName, bool canonicalize)
alreadyCanonicalized = true;
}
// If the path starts with "\??\", we can remove it and we will have the path.
- else if (fileName.StartsWith("\\??\\", StringComparison.OrdinalIgnoreCase))
+ else if (fileName.StartsWith("\\??\\"))
{
fileName = fileName.Substring(4);
}
// If the path still starts with a backslash, we probably need to
// resolve any native object name to a DOS drive letter.
- if (fileName.StartsWith("\\", StringComparison.OrdinalIgnoreCase))
+ if (fileName.StartsWith("\\"))
{
- foreach (KeyValuePair pair in _fileNamePrefixes)
+ var prefixes = _fileNamePrefixes;
+
+ foreach (var pair in prefixes)
{
- if (fileName.StartsWith(pair.Key + "\\", StringComparison.OrdinalIgnoreCase))
+ if (fileName.StartsWith(pair.Key + "\\"))
{
fileName = pair.Value + "\\" + fileName.Substring(pair.Key.Length + 1);
break;
}
- if (fileName == pair.Key)
+ else if (fileName == pair.Key)
{
fileName = pair.Value;
break;
@@ -217,44 +185,42 @@ public static string GetPathForDosDrive(char driveLetter)
if (driveLetter < 'A' || driveLetter > 'Z')
throw new ArgumentException("The drive letter must be between A to Z (inclusive).");
- using (SymbolicLinkHandle shandle = new SymbolicLinkHandle(@"\??\" + driveLetter + ":", SymbolicLinkAccess.Query))
+ using (var shandle = new SymbolicLinkHandle(@"\??\" + driveLetter + ":", SymbolicLinkAccess.Query))
{
- return shandle.Target;
+ return shandle.GetTarget();
}
}
public static void RefreshFileNamePrefixes()
{
- if (_fileNamePrefixes == null)
- {
- // Just create a new dictionary to avoid having to lock the existing one.
- _fileNamePrefixes = new Dictionary();
+ // Just create a new dictionary to avoid having to lock the existing one.
+ var newPrefixes = new Dictionary();
- for (char c = 'A'; c <= 'Z'; c++)
+ for (char c = 'A'; c <= 'Z'; c++)
+ {
+ using (var data = new MemoryAlloc(1024))
{
- using (MemoryAlloc data = new MemoryAlloc(1024))
- {
- int length;
+ int length;
- if ((length = Win32.QueryDosDevice(c.ToString() + ":", data, data.Size/2)) > 2)
- {
- _fileNamePrefixes.Add(data.ReadUnicodeString(0, length - 2), c.ToString() + ":");
- }
+ if ((length = Win32.QueryDosDevice(c.ToString() + ":", data, data.Size / 2)) > 2)
+ {
+ newPrefixes.Add(data.ReadUnicodeString(0, length - 2), c.ToString() + ":");
}
}
}
+
+ _fileNamePrefixes = newPrefixes;
}
public static void ShowProperties(string fileName)
{
- ShellExecuteInfo info = new ShellExecuteInfo
- {
- cbSize = ShellExecuteInfo.SizeOf,
- lpFile = fileName,
- nShow = ShowWindowType.Show,
- fMask = Win32.SeeMaskInvokeIdList,
- lpVerb = "properties"
- };
+ var info = new ShellExecuteInfo();
+
+ info.cbSize = Marshal.SizeOf(info);
+ info.lpFile = fileName;
+ info.nShow = ShowWindowType.Show;
+ info.fMask = Win32.SeeMaskInvokeIdList;
+ info.lpVerb = "properties";
Win32.ShellExecuteEx(ref info);
}
diff --git a/1.x/trunk/ProcessHacker.Native/ILoadedModule.cs b/1.x/trunk/ProcessHacker.Native/ILoadedModule.cs
index 3af0dd656..5dd450ca2 100644
--- a/1.x/trunk/ProcessHacker.Native/ILoadedModule.cs
+++ b/1.x/trunk/ProcessHacker.Native/ILoadedModule.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native
diff --git a/1.x/trunk/ProcessHacker.Native/Image/ImageExports.cs b/1.x/trunk/ProcessHacker.Native/Image/ImageExports.cs
index 881867446..8cb4349f0 100644
--- a/1.x/trunk/ProcessHacker.Native/Image/ImageExports.cs
+++ b/1.x/trunk/ProcessHacker.Native/Image/ImageExports.cs
@@ -21,7 +21,11 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
+using ProcessHacker.Native.Objects;
+using ProcessHacker.Native.Security;
namespace ProcessHacker.Native.Image
{
@@ -29,12 +33,12 @@ public unsafe sealed class ImageExports
{
public delegate bool EnumEntriesDelegate(ImageExportEntry entry);
- private readonly MappedImage _mappedImage;
- private readonly ImageDataDirectory* _dataDirectory;
- private readonly ImageExportDirectory* _exportDirectory;
- private readonly int* _addressTable;
- private readonly int* _namePointerTable;
- private readonly short* _ordinalTable;
+ private MappedImage _mappedImage;
+ private ImageDataDirectory* _dataDirectory;
+ private ImageExportDirectory* _exportDirectory;
+ private int* _addressTable;
+ private int* _namePointerTable;
+ private short* _ordinalTable;
internal ImageExports(MappedImage mappedImage)
{
@@ -56,8 +60,8 @@ public int Count
{
if (_exportDirectory != null)
return _exportDirectory->NumberOfFunctions;
-
- return 0;
+ else
+ return 0;
}
}
@@ -68,10 +72,9 @@ public ImageExportEntry GetEntry(int index)
if (index >= _exportDirectory->NumberOfFunctions)
return ImageExportEntry.Empty;
- ImageExportEntry entry = new ImageExportEntry
- {
- Ordinal = (short)(this._ordinalTable[index] + this._exportDirectory->Base)
- };
+ ImageExportEntry entry = new ImageExportEntry();
+
+ entry.Ordinal = (short)(_ordinalTable[index] + _exportDirectory->Base);
if (index < _exportDirectory->NumberOfNames)
entry.Name = new string((sbyte*)_mappedImage.RvaToVa(_namePointerTable[index]));
@@ -84,7 +87,9 @@ public ImageExportFunction GetFunction(string name)
if (_exportDirectory == null || _namePointerTable == null || _ordinalTable == null)
return ImageExportFunction.Empty;
- int index = this.LookupName(name);
+ int index;
+
+ index = this.LookupName(name);
if (index == -1)
return ImageExportFunction.Empty;
@@ -107,17 +112,13 @@ public ImageExportFunction GetFunction(short ordinal)
)
{
// This is a forwarder RVA.
- return new ImageExportFunction
- {
- ForwardedName = new string((sbyte*)_mappedImage.RvaToVa(rva))
- };
+ return new ImageExportFunction() { ForwardedName = new string((sbyte*)_mappedImage.RvaToVa(rva)) };
+ }
+ else
+ {
+ // This is a function RVA.
+ return new ImageExportFunction() { Function = (IntPtr)_mappedImage.RvaToVa(rva) };
}
-
- // This is a function RVA.
- return new ImageExportFunction
- {
- Function = (IntPtr)this._mappedImage.RvaToVa(rva)
- };
}
private int LookupName(string name)
@@ -154,7 +155,7 @@ private int LookupName(string name)
public struct ImageExportEntry
{
- public static readonly ImageExportEntry Empty;
+ public static readonly ImageExportEntry Empty = new ImageExportEntry();
public string Name;
public short Ordinal;
@@ -162,7 +163,7 @@ public struct ImageExportEntry
public struct ImageExportFunction
{
- public static readonly ImageExportFunction Empty;
+ public static readonly ImageExportFunction Empty = new ImageExportFunction();
public IntPtr Function;
public string ForwardedName;
diff --git a/1.x/trunk/ProcessHacker.Native/Image/ImageImports.cs b/1.x/trunk/ProcessHacker.Native/Image/ImageImports.cs
index c8c8e7c80..db466a7fb 100644
--- a/1.x/trunk/ProcessHacker.Native/Image/ImageImports.cs
+++ b/1.x/trunk/ProcessHacker.Native/Image/ImageImports.cs
@@ -28,10 +28,10 @@ public unsafe sealed class ImageImports
{
public delegate bool EnumEntriesDelegate(ImageExportEntry entry);
- private readonly MappedImage _mappedImage;
- private readonly int _count;
- private readonly ImageImportDescriptor* _descriptorTable;
- private readonly ImageImportDll[] _dlls;
+ private MappedImage _mappedImage;
+ private int _count;
+ private ImageImportDescriptor* _descriptorTable;
+ private ImageImportDll[] _dlls;
internal ImageImports(MappedImage mappedImage)
{
@@ -82,11 +82,11 @@ public ImageImportDll GetDll(int index)
public unsafe sealed class ImageImportDll
{
- private readonly MappedImage _mappedImage;
- private readonly ImageImportDescriptor* _descriptor;
+ private MappedImage _mappedImage;
+ private ImageImportDescriptor* _descriptor;
private string _name;
- private readonly void* _lookupTable;
- private readonly int _count;
+ private void* _lookupTable;
+ private int _count;
internal ImageImportDll(MappedImage mappedImage, ImageImportDescriptor* descriptor)
{
@@ -144,50 +144,45 @@ public ImageImportEntry GetEntry(int index)
if (index >= _count)
return ImageImportEntry.Empty;
- switch (this._mappedImage.Magic)
+ if (_mappedImage.Magic == Win32.Pe32Magic)
{
- case Win32.Pe32Magic:
+ int entry = ((int*)_lookupTable)[index];
+
+ // Is this entry using an ordinal?
+ if ((entry & 0x80000000) != 0)
+ {
+ return new ImageImportEntry() { Ordinal = (short)(entry & 0xffff) };
+ }
+ else
+ {
+ ImageImportByName* nameEntry = (ImageImportByName*)_mappedImage.RvaToVa(entry);
+
+ return new ImageImportEntry()
{
- int entry = ((int*)this._lookupTable)[index];
-
- // Is this entry using an ordinal?
- if ((entry & 0x80000000) != 0)
- {
- return new ImageImportEntry
- {
- Ordinal = (short)(entry & 0xffff)
- };
- }
-
- ImageImportByName* nameEntry = (ImageImportByName*)this._mappedImage.RvaToVa(entry);
-
- return new ImageImportEntry
- {
- NameHint = nameEntry->Hint,
- Name = new string((sbyte*)&nameEntry->Name)
- };
- }
- case Win32.Pe32PlusMagic:
+ NameHint = nameEntry->Hint,
+ Name = new string((sbyte*)&nameEntry->Name)
+ };
+ }
+ }
+ else if (_mappedImage.Magic == Win32.Pe32PlusMagic)
+ {
+ long entry = ((long*)_lookupTable)[index];
+
+ // Is this entry using an ordinal?
+ if (((ulong)entry & 0x8000000000000000) != 0)
+ {
+ return new ImageImportEntry() { Ordinal = (short)(entry & 0xffff) };
+ }
+ else
+ {
+ ImageImportByName* nameEntry = (ImageImportByName*)_mappedImage.RvaToVa((int)(entry & 0xffffffff));
+
+ return new ImageImportEntry()
{
- long entry = ((long*)this._lookupTable)[index];
-
- // Is this entry using an ordinal?
- if (((ulong)entry & 0x8000000000000000) != 0)
- {
- return new ImageImportEntry
- {
- Ordinal = (short)(entry & 0xffff)
- };
- }
-
- ImageImportByName* nameEntry = (ImageImportByName*)this._mappedImage.RvaToVa((int)(entry & 0xffffffff));
-
- return new ImageImportEntry
- {
- NameHint = nameEntry->Hint,
- Name = new string((sbyte*)&nameEntry->Name)
- };
- }
+ NameHint = nameEntry->Hint,
+ Name = new string((sbyte*)&nameEntry->Name)
+ };
+ }
}
return ImageImportEntry.Empty;
diff --git a/1.x/trunk/ProcessHacker.Native/Image/MappedImage.cs b/1.x/trunk/ProcessHacker.Native/Image/MappedImage.cs
index b49cf4c63..e86324798 100644
--- a/1.x/trunk/ProcessHacker.Native/Image/MappedImage.cs
+++ b/1.x/trunk/ProcessHacker.Native/Image/MappedImage.cs
@@ -157,41 +157,52 @@ public int GetChecksum(out int oldChecksum)
public ImageDataDirectory* GetDataEntry(ImageDataEntry entry)
{
- switch (this._magic)
+ if (_magic == Win32.Pe32Magic)
{
- case Win32.Pe32Magic:
- if ((int)entry >= this._ntHeaders->OptionalHeader.NumberOfRvaAndSizes)
- return null;
- return &(&this._ntHeaders->OptionalHeader.DataDirectory)[(int)entry];
- case Win32.Pe32PlusMagic:
- if ((int)entry >= this.GetOptionalHeader64()->NumberOfRvaAndSizes)
- return null;
- return &(&this.GetOptionalHeader64()->DataDirectory)[(int)entry];
- default:
+ if ((int)entry >= _ntHeaders->OptionalHeader.NumberOfRvaAndSizes)
return null;
+
+ return &(&_ntHeaders->OptionalHeader.DataDirectory)[(int)entry];
+ }
+ else if (_magic == Win32.Pe32PlusMagic)
+ {
+ if ((int)entry >= this.GetOptionalHeader64()->NumberOfRvaAndSizes)
+ return null;
+
+ return &(&this.GetOptionalHeader64()->DataDirectory)[(int)entry];
+ }
+ else
+ {
+ return null;
}
}
public ImageExportDirectory* GetExportDirectory()
{
- ImageDataDirectory* dataEntry = this.GetDataEntry(ImageDataEntry.Export);
+ ImageDataDirectory* dataEntry;
+
+ dataEntry = this.GetDataEntry(ImageDataEntry.Export);
return (ImageExportDirectory*)this.RvaToVa(dataEntry->VirtualAddress);
}
public ImageImportDescriptor* GetImportDirectory()
{
- ImageDataDirectory* dataEntry = this.GetDataEntry(ImageDataEntry.Import);
+ ImageDataDirectory* dataEntry;
+
+ dataEntry = this.GetDataEntry(ImageDataEntry.Import);
return (ImageImportDescriptor*)this.RvaToVa(dataEntry->VirtualAddress);
}
private void* GetLoadConfig(short magic)
{
+ ImageDataDirectory* dataEntry;
+
if (_magic != magic)
return null;
- ImageDataDirectory* dataEntry = this.GetDataEntry(ImageDataEntry.LoadConfig);
+ dataEntry = this.GetDataEntry(ImageDataEntry.LoadConfig);
if (dataEntry == null)
return null;
@@ -211,14 +222,17 @@ public int GetChecksum(out int oldChecksum)
private ImageNtHeaders* GetNtHeaders()
{
- int offset = *((int*)((byte*)this._memory + 0x3c));
+ int offset;
+ ImageNtHeaders* ntHeaders;
+
+ offset = *((int*)((byte*)_memory + 0x3c));
if (offset == 0)
throw new Exception("Invalid NT headers offset.");
if (offset >= 0x10000000 || offset >= _size)
throw new Exception("The NT headers offset is too large.");
- ImageNtHeaders* ntHeaders = (ImageNtHeaders*)((byte*)this._memory + offset);
+ ntHeaders = (ImageNtHeaders*)((byte*)_memory + offset);
return ntHeaders;
}
@@ -271,7 +285,7 @@ private void MapAndLoad(FileHandle fileHandle, bool readOnly)
readOnly ? MemoryProtection.ExecuteRead : MemoryProtection.ExecuteReadWrite
))
{
- _size = (int)fileHandle.FileSize;
+ _size = (int)fileHandle.GetSize();
_view = section.MapView(_size);
this.Load(_view);
@@ -299,7 +313,9 @@ private void MapAndLoad(FileHandle fileHandle, bool readOnly)
public void* RvaToVa(int rva)
{
- ImageSectionHeader* section = this.RvaToSection(rva);
+ ImageSectionHeader* section;
+
+ section = this.RvaToSection(rva);
if (section == null)
return null;
diff --git a/1.x/trunk/ProcessHacker.Native/ImpersonationContext.cs b/1.x/trunk/ProcessHacker.Native/ImpersonationContext.cs
index f35c10a0b..cfba70324 100644
--- a/1.x/trunk/ProcessHacker.Native/ImpersonationContext.cs
+++ b/1.x/trunk/ProcessHacker.Native/ImpersonationContext.cs
@@ -6,7 +6,7 @@ namespace ProcessHacker.Native
{
public class ImpersonationContext : IDisposable
{
- private bool _disposed;
+ private bool _disposed = false;
public ImpersonationContext(TokenHandle token)
{
@@ -16,11 +16,11 @@ public ImpersonationContext(TokenHandle token)
public void Dispose()
{
- if (_disposed)
- return;
-
- Win32.RevertToSelf();
- this._disposed = true;
+ if (!_disposed)
+ {
+ Win32.RevertToSelf();
+ _disposed = true;
+ }
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/IntPtrExtensions.cs b/1.x/trunk/ProcessHacker.Native/IntPtrExtensions.cs
index 192721828..664fa81f3 100644
--- a/1.x/trunk/ProcessHacker.Native/IntPtrExtensions.cs
+++ b/1.x/trunk/ProcessHacker.Native/IntPtrExtensions.cs
@@ -22,6 +22,7 @@
*/
using System;
+using System.Runtime.InteropServices;
namespace ProcessHacker.Native
{
@@ -34,34 +35,26 @@ public static IntPtr Align(this IntPtr ptr, int alignment)
public static IntPtr And(this IntPtr ptr, int value)
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(ptr.ToInt32() & value);
- default:
- return new IntPtr(ptr.ToInt64() & value);
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(ptr.ToInt32() & value);
+ else
+ return new IntPtr(ptr.ToInt64() & value);
}
public static IntPtr And(this IntPtr ptr, IntPtr value)
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(ptr.ToInt32() & value.ToInt32());
- default:
- return new IntPtr(ptr.ToInt64() & value.ToInt64());
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(ptr.ToInt32() & value.ToInt32());
+ else
+ return new IntPtr(ptr.ToInt64() & value.ToInt64());
}
public static int CompareTo(this IntPtr ptr, IntPtr ptr2)
{
if (ptr.ToUInt64() > ptr2.ToUInt64())
return 1;
-
if (ptr.ToUInt64() < ptr2.ToUInt64())
return -1;
-
return 0;
}
@@ -74,22 +67,17 @@ public static int CompareTo(this IntPtr ptr, uint ptr2)
{
if (ptr.ToUInt64() > ptr2)
return 1;
-
if (ptr.ToUInt64() < ptr2)
return -1;
-
return 0;
}
public static IntPtr Decrement(this IntPtr ptr, IntPtr ptr2)
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(ptr.ToInt32() - ptr2.ToInt32());
- default:
- return new IntPtr(ptr.ToInt64() - ptr2.ToInt64());
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(ptr.ToInt32() - ptr2.ToInt32());
+ else
+ return new IntPtr(ptr.ToInt64() - ptr2.ToInt64());
}
public static IntPtr Decrement(this IntPtr ptr, int value)
@@ -102,6 +90,13 @@ public static IntPtr Decrement(this IntPtr ptr, long value)
return Increment(ptr, -value);
}
+ public static T ElementAt(this IntPtr ptr, int index)
+ {
+ var offset = Marshal.SizeOf(typeof(T)) * index;
+ var offsetPtr = ptr.Increment(offset);
+ return (T)Marshal.PtrToStructure(offsetPtr, typeof(T));
+ }
+
public static bool Equals(this IntPtr ptr, IntPtr ptr2)
{
return ptr == ptr2;
@@ -131,13 +126,10 @@ public static IntPtr Increment(this IntPtr ptr, int value)
{
unchecked
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(ptr.ToInt32() + value);
- default:
- return new IntPtr(ptr.ToInt64() + value);
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(ptr.ToInt32() + value);
+ else
+ return new IntPtr(ptr.ToInt64() + value);
}
}
@@ -145,13 +137,10 @@ public static IntPtr Increment(this IntPtr ptr, long value)
{
unchecked
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr((int)(ptr.ToInt32() + value));
- default:
- return new IntPtr(ptr.ToInt64() + value);
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr((int)(ptr.ToInt32() + value));
+ else
+ return new IntPtr(ptr.ToInt64() + value);
}
}
@@ -159,16 +148,18 @@ public static IntPtr Increment(this IntPtr ptr, IntPtr ptr2)
{
unchecked
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(ptr.ToInt32() + ptr2.ToInt32());
- default:
- return new IntPtr(ptr.ToInt64() + ptr2.ToInt64());
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(ptr.ToInt32() + ptr2.ToInt32());
+ else
+ return new IntPtr(ptr.ToInt64() + ptr2.ToInt64());
}
}
+ public static IntPtr Increment(this IntPtr ptr)
+ {
+ return ptr.Increment(Marshal.SizeOf(typeof(T)));
+ }
+
public static bool IsGreaterThanOrEqualTo(this IntPtr ptr, IntPtr ptr2)
{
return ptr.CompareTo(ptr2) >= 0;
@@ -181,40 +172,40 @@ public static bool IsLessThanOrEqualTo(this IntPtr ptr, IntPtr ptr2)
public static IntPtr Not(this IntPtr ptr)
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(~ptr.ToInt32());
- default:
- return new IntPtr(~ptr.ToInt64());
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(~ptr.ToInt32());
+ else
+ return new IntPtr(~ptr.ToInt64());
}
public static IntPtr Or(this IntPtr ptr, IntPtr value)
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(ptr.ToInt32() | value.ToInt32());
- default:
- return new IntPtr(ptr.ToInt64() | value.ToInt64());
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(ptr.ToInt32() | value.ToInt32());
+ else
+ return new IntPtr(ptr.ToInt64() | value.ToInt64());
}
- public unsafe static uint ToUInt32(this IntPtr ptr)
+ public static uint ToUInt32(this IntPtr ptr)
{
// Avoid sign-extending the pointer - we want it zero-extended.
- void* voidPtr = (void*)ptr;
+ unsafe
+ {
+ void* voidPtr = (void*)ptr;
- return (uint)voidPtr;
+ return (uint)voidPtr;
+ }
}
- public unsafe static ulong ToUInt64(this IntPtr ptr)
+ public static ulong ToUInt64(this IntPtr ptr)
{
// Avoid sign-extending the pointer - we want it zero-extended.
- void* voidPtr = (void*)ptr;
+ unsafe
+ {
+ void* voidPtr = (void*)ptr;
- return (ulong)voidPtr;
+ return (ulong)voidPtr;
+ }
}
public static IntPtr ToIntPtr(this int value)
@@ -251,13 +242,10 @@ public static IntPtr ToIntPtr(this ulong value)
public static IntPtr Xor(this IntPtr ptr, IntPtr value)
{
- switch (IntPtr.Size)
- {
- case sizeof(int):
- return new IntPtr(ptr.ToInt32() ^ value.ToInt32());
- default:
- return new IntPtr(ptr.ToInt64() ^ value.ToInt64());
- }
+ if (IntPtr.Size == sizeof(Int32))
+ return new IntPtr(ptr.ToInt32() ^ value.ToInt32());
+ else
+ return new IntPtr(ptr.ToInt64() ^ value.ToInt64());
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Io/BeepDevice.cs b/1.x/trunk/ProcessHacker.Native/Io/BeepDevice.cs
index 355b95db6..68ab2c533 100644
--- a/1.x/trunk/ProcessHacker.Native/Io/BeepDevice.cs
+++ b/1.x/trunk/ProcessHacker.Native/Io/BeepDevice.cs
@@ -13,15 +13,8 @@ public static class BeepDevice
[StructLayout(LayoutKind.Sequential)]
public struct BeepSetParameters
{
- public static readonly int SizeOf;
-
public int Frequency;
public int Duration;
-
- static BeepSetParameters()
- {
- SizeOf = Marshal.SizeOf(typeof(BeepSetParameters));
- }
}
public const int BeepFrequencyMinimum = 0x25;
@@ -29,15 +22,18 @@ static BeepSetParameters()
public static readonly int IoCtlSet = Win32.CtlCode(DeviceType.Beep, 0, DeviceControlMethod.Buffered, DeviceControlAccess.Any);
- public static unsafe void Beep(int frequency, int duration)
+ public static void Beep(int frequency, int duration)
{
- BeepSetParameters p;
+ unsafe
+ {
+ BeepSetParameters p;
- p.Frequency = frequency;
- p.Duration = duration;
+ p.Frequency = frequency;
+ p.Duration = duration;
- using (var fhandle = OpenBeepDevice(FileAccess.GenericRead))
- fhandle.IoControl(IoCtlSet, &p, BeepSetParameters.SizeOf, null, 0);
+ using (var fhandle = OpenBeepDevice(FileAccess.GenericRead))
+ fhandle.IoControl(IoCtlSet, &p, Marshal.SizeOf(typeof(BeepSetParameters)), null, 0);
+ }
}
private static FileHandle OpenBeepDevice(FileAccess access)
diff --git a/1.x/trunk/ProcessHacker.Native/Io/DiskDevice.cs b/1.x/trunk/ProcessHacker.Native/Io/DiskDevice.cs
index 845d17b88..8894a1925 100644
--- a/1.x/trunk/ProcessHacker.Native/Io/DiskDevice.cs
+++ b/1.x/trunk/ProcessHacker.Native/Io/DiskDevice.cs
@@ -1,5 +1,8 @@
-using System.Runtime.InteropServices;
-
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Text;
+using ProcessHacker.Native;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -8,7 +11,7 @@ namespace ProcessHacker.Native.Io
{
public static class DiskDevice
{
- public enum DiskCacheState
+ public enum DiskCacheState : int
{
Normal,
WriteThroughNotSupported,
@@ -19,17 +22,10 @@ public enum DiskCacheState
[StructLayout(LayoutKind.Sequential)]
public struct DiskCacheSetting
{
- public static readonly int SizeOf;
-
public int Version;
public DiskCacheState State;
[MarshalAs(UnmanagedType.I1)]
public bool IsPowerProtected;
-
- static DiskCacheSetting()
- {
- SizeOf = Marshal.SizeOf(typeof(DiskCacheSetting));
- }
}
[StructLayout(LayoutKind.Sequential)]
@@ -71,21 +67,24 @@ public static DiskCacheState GetCacheSetting(string fileName, out bool isPowerPr
return GetCacheSetting(fhandle, out isPowerProtected);
}
- public static unsafe DiskCacheState GetCacheSetting(FileHandle fileHandle, out bool isPowerProtected)
+ public static DiskCacheState GetCacheSetting(FileHandle fileHandle, out bool isPowerProtected)
{
- DiskCacheSetting diskCacheSetting;
+ unsafe
+ {
+ DiskCacheSetting diskCacheSetting;
- fileHandle.IoControl(
- IoCtlGetCacheSetting,
- null,
- 0,
- &diskCacheSetting,
- DiskCacheSetting.SizeOf
- );
+ fileHandle.IoControl(
+ IoCtlGetCacheSetting,
+ null,
+ 0,
+ &diskCacheSetting,
+ Marshal.SizeOf(typeof(DiskCacheSetting))
+ );
- isPowerProtected = diskCacheSetting.IsPowerProtected;
+ isPowerProtected = diskCacheSetting.IsPowerProtected;
- return diskCacheSetting.State;
+ return diskCacheSetting.State;
+ }
}
public static void SetCacheSetting(string fileName, DiskCacheState state, bool isPowerProtected)
@@ -94,21 +93,24 @@ public static void SetCacheSetting(string fileName, DiskCacheState state, bool i
SetCacheSetting(fhandle, state, isPowerProtected);
}
- public static unsafe void SetCacheSetting(FileHandle fileHandle, DiskCacheState state, bool isPowerProtected)
+ public static void SetCacheSetting(FileHandle fileHandle, DiskCacheState state, bool isPowerProtected)
{
- DiskCacheSetting diskCacheSetting;
-
- diskCacheSetting.Version = DiskCacheSetting.SizeOf;
- diskCacheSetting.State = state;
- diskCacheSetting.IsPowerProtected = isPowerProtected;
-
- fileHandle.IoControl(
- IoCtlSetCacheSetting,
- &diskCacheSetting,
- DiskCacheSetting.SizeOf,
- null,
- 0
- );
+ unsafe
+ {
+ DiskCacheSetting diskCacheSetting;
+
+ diskCacheSetting.Version = Marshal.SizeOf(typeof(DiskCacheSetting));
+ diskCacheSetting.State = state;
+ diskCacheSetting.IsPowerProtected = isPowerProtected;
+
+ fileHandle.IoControl(
+ IoCtlSetCacheSetting,
+ &diskCacheSetting,
+ Marshal.SizeOf(typeof(DiskCacheSetting)),
+ null,
+ 0
+ );
+ }
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Io/MountManager.cs b/1.x/trunk/ProcessHacker.Native/Io/MountManager.cs
index 4091332cc..cd9e2eee0 100644
--- a/1.x/trunk/ProcessHacker.Native/Io/MountManager.cs
+++ b/1.x/trunk/ProcessHacker.Native/Io/MountManager.cs
@@ -21,7 +21,10 @@
*/
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Text;
+using ProcessHacker.Native;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -44,12 +47,7 @@ public struct MountMgrCreatePointInput
[StructLayout(LayoutKind.Sequential)]
public struct MountMgrMountPoint
{
- public static readonly int SizeOf;
-
- static MountMgrMountPoint()
- {
- SizeOf = Marshal.SizeOf(typeof(MountMgrMountPoint));
- }
+ public static readonly int Size = Marshal.SizeOf(typeof(MountMgrMountPoint));
public int SymbolicLinkNameOffset;
public ushort SymbolicLinkNameLength;
@@ -96,17 +94,12 @@ public struct MountMgrDriveLetterInformation
[StructLayout(LayoutKind.Sequential)]
public struct MountMgrVolumeMountPoint
{
- public static readonly int SizeOf;
+ public static readonly int Size = Marshal.SizeOf(typeof(MountMgrVolumeMountPoint));
public ushort SourceVolumeNameOffset;
public ushort SourceVolumeNameLength;
public ushort TargetVolumeNameOffset;
public ushort TargetVolumeNameLength;
-
- static MountMgrVolumeMountPoint()
- {
- SizeOf = Marshal.SizeOf(typeof(MountMgrVolumeMountPoint));
- }
}
// Input, output for IoCtlChangeNotify
@@ -172,16 +165,14 @@ public struct MountDevName
private static void DeleteSymbolicLink(string path)
{
- using (MemoryAlloc data = new MemoryAlloc(MountMgrMountPoint.SizeOf + path.Length * 2))
- using (MemoryAlloc outData = new MemoryAlloc(1600))
+ using (var data = new MemoryAlloc(MountMgrMountPoint.Size + path.Length * 2))
+ using (var outData = new MemoryAlloc(1600))
{
- MountMgrMountPoint mountPoint = new MountMgrMountPoint
- {
- SymbolicLinkNameLength = (ushort)(path.Length*2),
- SymbolicLinkNameOffset = MountMgrMountPoint.SizeOf
- };
+ MountMgrMountPoint mountPoint = new MountMgrMountPoint();
- data.WriteStruct(mountPoint);
+ mountPoint.SymbolicLinkNameLength = (ushort)(path.Length * 2);
+ mountPoint.SymbolicLinkNameOffset = MountMgrMountPoint.Size;
+ data.WriteStruct(mountPoint);
data.WriteUnicodeString(mountPoint.SymbolicLinkNameOffset, path);
using (var fhandle = OpenMountManager(FileAccess.GenericRead | FileAccess.GenericWrite))
@@ -201,7 +192,7 @@ private static void DeleteSymbolicLink(string path)
/// The device name associated with the DOS drive.
public static string GetDeviceName(string fileName)
{
- using (FileHandle fhandle = new FileHandle(
+ using (var fhandle = new FileHandle(
fileName,
FileShareMode.ReadWrite,
FileCreateOptions.SynchronousIoNonAlert,
@@ -212,7 +203,7 @@ public static string GetDeviceName(string fileName)
public static string GetDeviceName(FileHandle fhandle)
{
- using (MemoryAlloc data = new MemoryAlloc(600))
+ using (var data = new MemoryAlloc(600))
{
fhandle.IoControl(IoCtlQueryDeviceName, IntPtr.Zero, 0, data, data.Size);
@@ -224,7 +215,7 @@ public static string GetDeviceName(FileHandle fhandle)
private static string GetReparsePointTarget(FileHandle fhandle)
{
- using (MemoryAlloc data = new MemoryAlloc(FileSystem.MaximumReparseDataBufferSize))
+ using (var data = new MemoryAlloc(FileSystem.MaximumReparseDataBufferSize))
{
fhandle.IoControl(FileSystem.FsCtlGetReparsePoint, IntPtr.Zero, 0, data, data.Size);
@@ -299,15 +290,13 @@ public static string GetVolumeName(char driveLetter)
public static string GetVolumeName(string deviceName)
{
- using (MemoryAlloc data = new MemoryAlloc(MountMgrMountPoint.SizeOf + deviceName.Length * 2))
+ using (var data = new MemoryAlloc(MountMgrMountPoint.Size + deviceName.Length * 2))
{
- MountMgrMountPoint mountPoint = new MountMgrMountPoint
- {
- DeviceNameLength = (ushort)(deviceName.Length*2),
- DeviceNameOffset = MountMgrMountPoint.SizeOf
- };
+ MountMgrMountPoint mountPoint = new MountMgrMountPoint();
- data.WriteStruct(mountPoint);
+ mountPoint.DeviceNameLength = (ushort)(deviceName.Length * 2);
+ mountPoint.DeviceNameOffset = MountMgrMountPoint.Size;
+ data.WriteStruct(mountPoint);
data.WriteUnicodeString(mountPoint.DeviceNameOffset, deviceName);
using (var fhandle = OpenMountManager((FileAccess)StandardRights.Synchronize))
@@ -315,7 +304,7 @@ public static string GetVolumeName(string deviceName)
NtStatus status;
int retLength;
- using (MemoryAlloc outData = new MemoryAlloc(0x100))
+ using (var outData = new MemoryAlloc(0x100))
{
while (true)
{
@@ -339,7 +328,8 @@ out retLength
}
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
MountMgrMountPoints mountPoints = outData.ReadStruct();
@@ -349,11 +339,11 @@ out retLength
{
MountMgrMountPoint mp = outData.ReadStruct(
MountMgrMountPoints.MountPointsOffset,
- MountMgrMountPoint.SizeOf,
i
);
+ string symLinkName;
- string symLinkName = Marshal.PtrToStringUni(
+ symLinkName = Marshal.PtrToStringUni(
outData.Memory.Increment(mp.SymbolicLinkNameOffset),
mp.SymbolicLinkNameLength / 2
);
@@ -372,20 +362,20 @@ public static bool IsDriveLetterPath(string path)
{
if (
path.Length == 14 &&
- path.StartsWith(@"\DosDevices\", StringComparison.OrdinalIgnoreCase) &&
+ path.StartsWith(@"\DosDevices\") &&
path[12] >= 'A' && path[12] <= 'Z' &&
path[13] == ':'
)
return true;
-
- return false;
+ else
+ return false;
}
public static bool IsVolumePath(string path)
{
if (
(path.Length == 48 || (path.Length == 49 && path[48] == '\\')) &&
- (path.StartsWith(@"\??\Volume", StringComparison.OrdinalIgnoreCase) || path.StartsWith(@"\\?\Volume", StringComparison.OrdinalIgnoreCase)) &&
+ (path.StartsWith(@"\??\Volume") || path.StartsWith(@"\\?\Volume")) &&
path[10] == '{' &&
path[19] == '-' &&
path[24] == '-' &&
@@ -394,32 +384,31 @@ public static bool IsVolumePath(string path)
path[47] == '}'
)
return true;
-
- return false;
+ else
+ return false;
}
private static void Notify(bool created, string sourceVolumeName, string targetVolumeName)
{
- using (MemoryAlloc data = new MemoryAlloc(
- MountMgrVolumeMountPoint.SizeOf +
+ using (var data = new MemoryAlloc(
+ MountMgrVolumeMountPoint.Size +
sourceVolumeName.Length * 2 +
targetVolumeName.Length * 2
))
{
- MountMgrVolumeMountPoint mountPoint = new MountMgrVolumeMountPoint
- {
- SourceVolumeNameLength = (ushort)(sourceVolumeName.Length * 2),
- SourceVolumeNameOffset = (ushort)MountMgrVolumeMountPoint.SizeOf,
- TargetVolumeNameLength = (ushort)(targetVolumeName.Length * 2)
- };
+ MountMgrVolumeMountPoint mountPoint = new MountMgrVolumeMountPoint();
- mountPoint.TargetVolumeNameOffset = (ushort)(mountPoint.SourceVolumeNameOffset + mountPoint.SourceVolumeNameLength);
+ mountPoint.SourceVolumeNameLength = (ushort)(sourceVolumeName.Length * 2);
+ mountPoint.SourceVolumeNameOffset = (ushort)MountMgrVolumeMountPoint.Size;
+ mountPoint.TargetVolumeNameLength = (ushort)(targetVolumeName.Length * 2);
+ mountPoint.TargetVolumeNameOffset =
+ (ushort)(mountPoint.SourceVolumeNameOffset + mountPoint.SourceVolumeNameLength);
- data.WriteStruct(mountPoint);
+ data.WriteStruct(mountPoint);
data.WriteUnicodeString(mountPoint.SourceVolumeNameOffset, sourceVolumeName);
data.WriteUnicodeString(mountPoint.TargetVolumeNameOffset, targetVolumeName);
- using (FileHandle fhandle = OpenMountManager(FileAccess.GenericRead | FileAccess.GenericWrite))
+ using (var fhandle = OpenMountManager(FileAccess.GenericRead | FileAccess.GenericWrite))
{
fhandle.IoControl(
created ? IoCtlVolumeMountPointCreated : IoCtlVolumeMountPointDeleted,
diff --git a/1.x/trunk/ProcessHacker.Native/Io/StorageDevice.cs b/1.x/trunk/ProcessHacker.Native/Io/StorageDevice.cs
index 8184df4db..532831101 100644
--- a/1.x/trunk/ProcessHacker.Native/Io/StorageDevice.cs
+++ b/1.x/trunk/ProcessHacker.Native/Io/StorageDevice.cs
@@ -23,8 +23,6 @@ public struct StoragePreventMediaRemoval
[StructLayout(LayoutKind.Sequential)]
public struct StorageHotplugInfo
{
- public static readonly int SizeOf;
-
public int Size;
[MarshalAs(UnmanagedType.I1)]
public bool MediaRemovable;
@@ -34,11 +32,6 @@ public struct StorageHotplugInfo
public bool DeviceHotplug;
[MarshalAs(UnmanagedType.I1)]
public bool WriteCacheEnableOverride;
-
- static StorageHotplugInfo()
- {
- SizeOf = Marshal.SizeOf(typeof(StorageHotplugInfo));
- }
}
public static readonly int IoCtlMediaRemoval = Win32.CtlCode(DeviceType.MassStorage, 0x0201, DeviceControlMethod.Buffered, DeviceControlAccess.Read);
@@ -68,13 +61,16 @@ public static StorageHotplugInfo GetHotplugInfo(string fileName)
return GetHotplugInfo(fhandle);
}
- public static unsafe StorageHotplugInfo GetHotplugInfo(FileHandle fileHandle)
+ public static StorageHotplugInfo GetHotplugInfo(FileHandle fileHandle)
{
- StorageHotplugInfo hotplugInfo;
+ unsafe
+ {
+ StorageHotplugInfo hotplugInfo;
- fileHandle.IoControl(IoCtlGetHotplugInfo, null, 0, &hotplugInfo, StorageHotplugInfo.SizeOf);
+ fileHandle.IoControl(IoCtlGetHotplugInfo, null, 0, &hotplugInfo, Marshal.SizeOf(typeof(StorageHotplugInfo)));
- return hotplugInfo;
+ return hotplugInfo;
+ }
}
public static FileHandle OpenStorageDevice(string fileName, FileAccess access)
diff --git a/1.x/trunk/ProcessHacker.Native/Ipc/IpcCircularBuffer.cs b/1.x/trunk/ProcessHacker.Native/Ipc/IpcCircularBuffer.cs
index dc560f6e8..d8f935285 100644
--- a/1.x/trunk/ProcessHacker.Native/Ipc/IpcCircularBuffer.cs
+++ b/1.x/trunk/ProcessHacker.Native/Ipc/IpcCircularBuffer.cs
@@ -28,18 +28,11 @@
namespace ProcessHacker.Native.Ipc
{
- public unsafe class IpcCircularBuffer : IDisposable
+ public unsafe class IpcCircularBuffer
{
[StructLayout(LayoutKind.Sequential)]
- public struct BufferHeader
+ private struct BufferHeader
{
- public static readonly int SizeOf;
-
- static BufferHeader()
- {
- SizeOf = Marshal.SizeOf(typeof(BufferHeader));
- }
-
public int BlockSize;
public int NumberOfBlocks;
@@ -57,21 +50,22 @@ public static IpcCircularBuffer Create(string name, int blockSize, int numberOfB
Random r = new Random();
long readSemaphoreId = ((long)r.Next() << 32) + r.Next();
long writeSemaphoreId = ((long)r.Next() << 32) + r.Next();
+ Section section;
- Section section = new Section(name, blockSize * numberOfBlocks, MemoryProtection.ReadWrite);
+ section = new Section(name, blockSize * numberOfBlocks, MemoryProtection.ReadWrite);
- using (SectionView view = section.MapView(BufferHeader.SizeOf))
+ using (var view = section.MapView(Marshal.SizeOf(typeof(BufferHeader))))
{
- BufferHeader header = new BufferHeader
- {
- BlockSize = blockSize,
- NumberOfBlocks = numberOfBlocks,
- ReadSemaphoreId = readSemaphoreId,
- WriteSemaphoreId = writeSemaphoreId,
- ReadPosition = 0, WritePosition = 0
- };
-
- view.WriteStruct(header);
+ BufferHeader header = new BufferHeader();
+
+ header.BlockSize = blockSize;
+ header.NumberOfBlocks = numberOfBlocks;
+ header.ReadSemaphoreId = readSemaphoreId;
+ header.WriteSemaphoreId = writeSemaphoreId;
+ header.ReadPosition = 0;
+ header.WritePosition = 0;
+
+ view.WriteStruct(header);
}
return new IpcCircularBuffer(
@@ -87,13 +81,13 @@ public static IpcCircularBuffer Open(string name)
return new IpcCircularBuffer(new Section(name, SectionAccess.All), name, null, null);
}
- private readonly Section _section;
- private readonly SectionView _sectionView;
- private readonly Semaphore _readSemaphore;
- private readonly Semaphore _writeSemaphore;
+ private Section _section;
+ private SectionView _sectionView;
+ private Semaphore _readSemaphore;
+ private Semaphore _writeSemaphore;
- private readonly BufferHeader* _header;
- private readonly void* _data;
+ private BufferHeader* _header;
+ private void* _data;
private IpcCircularBuffer(Section section, string sectionName, Semaphore readSemaphore, Semaphore writeSemaphore)
{
@@ -101,7 +95,7 @@ private IpcCircularBuffer(Section section, string sectionName, Semaphore readSem
_section = section;
- _sectionView = section.MapView(BufferHeader.SizeOf);
+ _sectionView = section.MapView(Marshal.SizeOf(typeof(BufferHeader)));
header = _sectionView.ReadStruct();
_sectionView.Dispose();
@@ -121,17 +115,16 @@ private IpcCircularBuffer(Section section, string sectionName, Semaphore readSem
_data = &_header->Data;
}
- public T Read() where T : struct
+ public T Read()
+ where T : struct
{
- using (MemoryAlloc data = this.Read())
- {
+ using (var data = this.Read())
return data.ReadStruct();
- }
}
public MemoryAlloc Read()
{
- MemoryAlloc data = new MemoryAlloc(_header->BlockSize);
+ var data = new MemoryAlloc(_header->BlockSize);
this.Read(data);
@@ -175,12 +168,13 @@ public void Read(void* buffer)
_writeSemaphore.Release();
}
- public void Write(int size, T s) where T : struct
+ public void Write(T s)
+ where T : struct
{
- using (MemoryAlloc data = new MemoryAlloc(size))
+ using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(T))))
{
- data.WriteStruct(s);
- this.Write(data);
+ data.WriteStruct(s);
+ this.Write((MemoryRegion)data);
}
}
@@ -225,14 +219,5 @@ public void Write(void* buffer)
// Release the read semaphore to allow a reader to read one more block.
_readSemaphore.Release();
}
-
- public void Dispose()
- {
- if (_readSemaphore != null)
- _readSemaphore.Dispose();
-
- if (_writeSemaphore != null)
- _writeSemaphore.Dispose();
- }
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/KProcessHacker.cs b/1.x/trunk/ProcessHacker.Native/KProcessHacker.cs
index 4c31da159..2d3d6b06c 100644
--- a/1.x/trunk/ProcessHacker.Native/KProcessHacker.cs
+++ b/1.x/trunk/ProcessHacker.Native/KProcessHacker.cs
@@ -2,7 +2,7 @@
* Process Hacker -
* KProcessHacker interfacing code
*
- * Copyright (C) 2009-2011 wj32
+ * Copyright (C) 2009 wj32
*
* This file is part of Process Hacker.
*
@@ -23,96 +23,134 @@
// The private field 'field' is assigned but its value is never used
#pragma warning disable 0414
+using System;
using System.Runtime.InteropServices;
+using System.Text;
using System.Windows.Forms;
-using ProcessHacker.Native;
+using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
+using ProcessHacker.Native.SsLogging;
-namespace System
+namespace ProcessHacker.Native
{
///
/// Provides an interface to KProcessHacker.
///
- public sealed unsafe class KProcessHacker2 : IDisposable
+ public sealed unsafe class KProcessHacker
{
- public static KProcessHacker2 Instance;
+ private static KProcessHacker _instance;
- public bool KphIsConnected
+ public static KProcessHacker Instance
{
- get { return _fileHandle != null; }
+ get { return _instance; }
+ set { _instance = value; }
}
- public static int KphCtlCode(int x)
+ ///
+ /// A control code used by KProcessHacker to represent a specific function.
+ ///
+ private enum Control : uint
{
- return Win32.CtlCode((DeviceType)KphDeviceType, 0x800 + x, DeviceControlMethod.Neither, DeviceControlAccess.Any);
+ ClientCloseHandle = 0,
+ SsQueryClientEntry,
+ Reserved1,
+ KphOpenProcess,
+ KphOpenThread,
+ KphOpenProcessToken,
+ GetProcessProtected,
+ SetProcessProtected,
+ KphTerminateProcess,
+ KphSuspendProcess,
+ KphResumeProcess,
+ KphReadVirtualMemory,
+ KphWriteVirtualMemory,
+ SetProcessToken,
+ GetThreadStartAddress,
+ SetHandleAttributes,
+ GetHandleObjectName,
+ KphOpenProcessJob,
+ KphGetContextThread,
+ KphSetContextThread,
+ KphGetThreadWin32Thread,
+ KphDuplicateObject,
+ ZwQueryObject,
+ KphGetProcessId,
+ KphGetThreadId,
+ KphTerminateThread,
+ GetFeatures,
+ KphSetHandleGrantedAccess,
+ KphAssignImpersonationToken,
+ ProtectAdd,
+ ProtectRemove,
+ ProtectQuery,
+ KphUnsafeReadVirtualMemory,
+ SetExecuteOptions,
+ KphQueryProcessHandles,
+ KphOpenThreadProcess,
+ KphCaptureStackBackTraceThread,
+ KphDangerousTerminateThread,
+ KphOpenType,
+ KphOpenDriver,
+ KphQueryInformationDriver,
+ KphOpenDirectoryObject,
+ SsRef,
+ SsUnref,
+ SsCreateClientEntry,
+ SsCreateRuleSetEntry,
+ SsRemoveRule,
+ SsAddProcessIdRule,
+ SsAddThreadIdRule,
+ SsAddPreviousModeRule,
+ SsAddNumberRule,
+ SsEnableClientEntry,
+ KphOpenNamedObject,
+ KphQueryInformationProcess,
+ KphQueryInformationThread,
+ KphSetInformationProcess,
+ KphSetInformationThread,
}
- public const int KphDeviceType = 0x9999;
-
- // General
- public static readonly int IoCtlGetFeatures = KphCtlCode(0);
-
- // Processes
- public static readonly int IoCtlOpenProcess = KphCtlCode(50);
- public static readonly int IoCtlOpenProcessToken = KphCtlCode(51);
- public static readonly int IoCtlOpenProcessJob = KphCtlCode(52);
- public static readonly int IoCtlSuspendProcess = KphCtlCode(53);
- public static readonly int IoCtlResumeProcess = KphCtlCode(54);
- public static readonly int IoCtlTerminateProcess = KphCtlCode(55);
- public static readonly int IoCtlReadVirtualMemory = KphCtlCode(56);
- public static readonly int IoCtlWriteVirtualMemory = KphCtlCode(57);
- public static readonly int IoCtlReadVirtualMemoryUnsafe = KphCtlCode(58);
- public static readonly int IoCtlQueryInformationProcess = KphCtlCode(59);
- public static readonly int IoCtlSetInformationProcess = KphCtlCode(60);
-
- // Threads
- public static readonly int IoCtlOpenThread = KphCtlCode(100);
- public static readonly int IoCtlOpenThreadProcess = KphCtlCode(101);
- public static readonly int IoCtlTerminateThread = KphCtlCode(102);
- public static readonly int IoCtlTerminateThreadUnsafe = KphCtlCode(103);
- public static readonly int IoCtlGetContextThread = KphCtlCode(104);
- public static readonly int IoCtlSetContextThread = KphCtlCode(105);
- public static readonly int IoCtlCaptureStackBackTraceThread = KphCtlCode(106);
- public static readonly int IoCtlQueryInformationThread = KphCtlCode(107);
- public static readonly int IoCtlSetInformationThread = KphCtlCode(108);
-
- // Handles
- public static readonly int IoCtlEnumerateProcessHandles = KphCtlCode(150);
- public static readonly int IoCtlQueryInformationObject = KphCtlCode(151);
- public static readonly int IoCtlSetInformationObject = KphCtlCode(152);
- public static readonly int IoCtlDuplicateObject = KphCtlCode(153);
-
- // Misc.
- public static readonly int IoCtlOpenDriver = KphCtlCode(200);
- public static readonly int IoCtlQueryInformationDriver = KphCtlCode(201);
-
[Flags]
- public enum KphFeatures
+ public enum KphFeatures : int
{
- None = 0 // none so far
+ PsTerminateProcess = 0x1,
+ PspTerminateThreadByPointer = 0x2
}
- private readonly string _deviceName;
+ private string _deviceName;
private FileHandle _fileHandle;
- private readonly KphFeatures _features;
+ private uint _baseControlNumber;
+ private KphFeatures _features;
+
+ ///
+ /// Creates a connection to KProcessHacker.
+ ///
+ public KProcessHacker()
+ : this("KProcessHacker")
+ { }
///
/// Creates a connection to KProcessHacker.
///
- public KProcessHacker2()
- : this("KProcessHacker2")
+ /// The name of the KProcessHacker service and device.
+ public KProcessHacker(string deviceName)
+ : this(deviceName, Application.StartupPath + "\\kprocesshacker.sys")
{ }
///
/// Creates a connection to KProcessHacker.
///
/// The name of the KProcessHacker service and device.
- public KProcessHacker2(string deviceName)
+ /// The file name of the KProcessHacker driver.
+ public KProcessHacker(string deviceName, string fileName)
{
_deviceName = deviceName;
+ if (OSVersion.Architecture != OSArch.I386)
+ throw new NotSupportedException("KProcessHacker does not support 64-bit Windows.");
+
try
{
_fileHandle = new FileHandle(
@@ -129,7 +167,53 @@ public KProcessHacker2(string deviceName)
ex.Status == NtStatus.ObjectNameNotFound
)
{
- LoadService();
+ // Attempt to load the driver, then try again.
+ ServiceHandle shandle;
+ bool created = false;
+
+ try
+ {
+ using (shandle = new ServiceHandle("KProcessHacker", ServiceAccess.Start))
+ {
+ shandle.Start();
+ }
+ }
+ catch
+ {
+ using (var scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
+ {
+ shandle = scm.CreateService(
+ deviceName,
+ deviceName,
+ ServiceType.KernelDriver,
+ fileName
+ );
+ shandle.Start();
+ created = true;
+ }
+ }
+
+ try
+ {
+ _fileHandle = new FileHandle(
+ @"\Device\" + deviceName,
+ 0,
+ FileAccess.GenericRead | FileAccess.GenericWrite
+ );
+ }
+ finally
+ {
+ if (shandle != null)
+ {
+ if (created)
+ {
+ // The SCM will delete the service when it is stopped.
+ shandle.Delete();
+ }
+
+ shandle.Dispose();
+ }
+ }
}
else
{
@@ -138,7 +222,18 @@ public KProcessHacker2(string deviceName)
}
_fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, Win32HandleFlags.ProtectFromClose);
- _features = this.KphGetFeatures();
+
+ byte[] bytes = _fileHandle.Read(4);
+
+ fixed (byte* bytesPtr = bytes)
+ _baseControlNumber = *(uint*)bytesPtr;
+
+ try
+ {
+ _features = this.GetFeatures();
+ }
+ catch
+ { }
}
public string DeviceName
@@ -151,635 +246,984 @@ public KphFeatures Features
get { return _features; }
}
+ private int CtlCode(Control ctl)
+ {
+ return (int)(_baseControlNumber + ((uint)ctl * 4));
+ }
+
+ ///
+ /// Closes the connection to KProcessHacker.
+ ///
+ public void Close()
+ {
+ _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, 0);
+ _fileHandle.Dispose();
+ }
+
+ public void ClientCloseHandle(IntPtr handle)
+ {
+ byte* inData = stackalloc byte[4];
+
+ *(int*)inData = handle.ToInt32();
+
+ _fileHandle.IoControl(CtlCode(Control.ClientCloseHandle), inData, 4, null, 0);
+ }
+
+ public KphFeatures GetFeatures()
+ {
+ byte* outData = stackalloc byte[4];
+
+ _fileHandle.IoControl(CtlCode(Control.GetFeatures), null, 0, outData, 4);
+
+ return (KphFeatures)(*(int*)outData);
+ }
- public void LoadService()
+ public string GetHandleObjectName(ProcessHandle processHandle, IntPtr handle)
{
- // Attempt to load the driver, then try again.
- ServiceHandle shandle;
- bool created = false;
+ byte* inData = stackalloc byte[8];
+ byte[] outData = new byte[2048];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 4) = handle.ToInt32();
try
{
- using (shandle = new ServiceHandle(_deviceName, ServiceAccess.Start))
- {
- shandle.Start();
- }
+ int len = _fileHandle.IoControl(CtlCode(Control.GetHandleObjectName),
+ inData, 8, outData);
+
+ return Encoding.Unicode.GetString(outData, 8, len - 8).TrimEnd('\0');
}
catch
+ { }
+
+ return null;
+ }
+
+ public bool GetProcessProtected(int pid)
+ {
+ byte[] result = new byte[1];
+
+ _fileHandle.IoControl(CtlCode(Control.GetProcessProtected),
+ (byte*)&pid, 4, result);
+
+ return result[0] != 0;
+ }
+
+ public uint GetThreadStartAddress(ThreadHandle threadHandle)
+ {
+ byte* outData = stackalloc byte[4];
+ int threadHandleInt = threadHandle;
+
+ _fileHandle.IoControl(CtlCode(Control.GetThreadStartAddress),
+ (byte*)&threadHandleInt, 4, outData, 4);
+
+ return *(uint*)outData;
+ }
+
+ public void KphAssignImpersonationToken(ThreadHandle threadHandle, TokenHandle tokenHandle)
+ {
+ byte* inData = stackalloc byte[8];
+
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 4) = tokenHandle;
+
+ _fileHandle.IoControl(CtlCode(Control.KphAssignImpersonationToken), inData, 8, null, 0);
+ }
+
+ public unsafe int KphCaptureStackBackTraceThread(
+ ThreadHandle threadHandle,
+ int framesToSkip,
+ int framesToCapture,
+ IntPtr[] backTrace,
+ out int backTraceHash
+ )
+ {
+ byte* inData = stackalloc byte[6 * sizeof(int)];
+ int capturedFramesLocal;
+ int backTraceHashLocal;
+
+ if (framesToCapture > backTrace.Length)
+ throw new ArgumentOutOfRangeException("Back trace buffer is too small.");
+
+ fixed (IntPtr* backTracePtr = backTrace)
{
- using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
- {
- shandle = scm.CreateService(
- _deviceName,
- _deviceName,
- ServiceType.KernelDriver,
- Application.StartupPath + "\\kprocesshacker.sys"
- );
- shandle.Start();
- created = true;
- }
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 0x4) = framesToSkip;
+ *(int*)(inData + 0x8) = framesToCapture;
+ *(int*)(inData + 0xc) = (int)backTracePtr;
+ *(int*)(inData + 0x10) = (int)&capturedFramesLocal;
+ *(int*)(inData + 0x14) = (int)&backTraceHashLocal;
+
+ _fileHandle.IoControl(CtlCode(Control.KphCaptureStackBackTraceThread), inData, 6 * sizeof(int), null, 0);
+ backTraceHash = backTraceHashLocal;
+
+ return capturedFramesLocal;
}
+ }
+
+ public void KphDangerousTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
+ {
+ byte* inData = stackalloc byte[8];
+
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 4) = (int)exitStatus;
+
+ _fileHandle.IoControl(CtlCode(Control.KphDangerousTerminateThread), inData, 8, null, 0);
+ }
+
+ public void KphDuplicateObject(
+ int sourceProcessHandle,
+ int sourceHandle,
+ int targetProcessHandle,
+ out int targetHandle,
+ int desiredAccess,
+ HandleFlags handleAttributes,
+ DuplicateOptions options
+ )
+ {
+ int handle;
+
+ KphDuplicateObject(
+ sourceProcessHandle,
+ sourceHandle,
+ targetProcessHandle,
+ (int)&handle,
+ desiredAccess,
+ handleAttributes,
+ options
+ );
+
+ targetHandle = handle;
+ }
+
+ public void KphDuplicateObject(
+ int sourceProcessHandle,
+ int sourceHandle,
+ int targetProcessHandle,
+ int targetHandle,
+ int desiredAccess,
+ HandleFlags handleAttributes,
+ DuplicateOptions options
+ )
+ {
+ byte[] data = new byte[7 * sizeof(int)];
+
+ fixed (byte* dataPtr = data)
+ {
+ *(int*)(dataPtr + 0x0) = sourceProcessHandle;
+ *(int*)(dataPtr + 0x4) = sourceHandle;
+ *(int*)(dataPtr + 0x8) = targetProcessHandle;
+ *(int*)(dataPtr + 0xc) = targetHandle;
+ *(int*)(dataPtr + 0x10) = desiredAccess;
+ *(int*)(dataPtr + 0x14) = (int)handleAttributes;
+ *(int*)(dataPtr + 0x18) = (int)options;
+
+ _fileHandle.IoControl(CtlCode(Control.KphDuplicateObject), data, null);
+ }
+ }
+
+ public void KphGetContextThread(ThreadHandle threadHandle, Context* context)
+ {
+ byte* inData = stackalloc byte[8];
+
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 4) = (int)context;
+
+ _fileHandle.IoControl(CtlCode(Control.KphGetContextThread), inData, 8, null, 0);
+ }
+
+ public int KphGetProcessId(ProcessHandle processHandle, IntPtr handle)
+ {
+ byte* inData = stackalloc byte[8];
+ byte* outData = stackalloc byte[4];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 4) = handle.ToInt32();
+
+ _fileHandle.IoControl(CtlCode(Control.KphGetProcessId), inData, 8, outData, 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphGetThreadId(ProcessHandle processHandle, IntPtr handle, out int processId)
+ {
+ byte* inData = stackalloc byte[8];
+ byte* outData = stackalloc byte[8];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 4) = handle.ToInt32();
+
+ _fileHandle.IoControl(CtlCode(Control.KphGetThreadId), inData, 8, outData, 8);
+ processId = *(int*)(outData + 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphGetThreadWin32Thread(ThreadHandle threadHandle)
+ {
+ int threadHandleInt = threadHandle;
+ byte* outData = stackalloc byte[4];
+
+ _fileHandle.IoControl(CtlCode(Control.KphGetThreadWin32Thread), (byte*)&threadHandleInt, 4, outData, 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphOpenDirectoryObject(DirectoryAccess access, ObjectAttributes objectAttributes)
+ {
+ byte* inData = stackalloc byte[0xc];
+ int directoryObjectHandle;
+
+ *(int*)inData = (int)&directoryObjectHandle;
+ *(int*)(inData + 0x4) = (int)access;
+ *(int*)(inData + 0x8) = (int)&objectAttributes;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenDirectoryObject), inData, 0xc, null, 0);
+
+ return directoryObjectHandle;
+ }
+
+ public int KphOpenDriver(ObjectAttributes objectAttributes)
+ {
+ byte* inData = stackalloc byte[8];
+ int driverHandle;
+
+ *(int*)inData = (int)&driverHandle;
+ *(int*)(inData + 4) = (int)&objectAttributes;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenDriver), inData, 8, null, 0);
+
+ return driverHandle;
+ }
+
+ public int KphOpenNamedObject(int access, ObjectAttributes objectAttributes)
+ {
+ byte* inData = stackalloc byte[0xc];
+ int handle;
+
+ *(int*)inData = (int)&handle;
+ *(int*)(inData + 4) = access;
+ *(int*)(inData + 8) = (int)&objectAttributes;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenNamedObject), inData, 0xc, null, 0);
+
+ return handle;
+ }
+
+ public int KphOpenProcess(int pid, ProcessAccess desiredAccess)
+ {
+ byte* inData = stackalloc byte[8];
+ byte* outData = stackalloc byte[4];
+
+ *(int*)inData = pid;
+ *(uint*)(inData + 4) = (uint)desiredAccess;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenProcess), inData, 8, outData, 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphOpenProcessJob(ProcessHandle processHandle, JobObjectAccess desiredAccess)
+ {
+ byte* inData = stackalloc byte[8];
+ byte* outData = stackalloc byte[4];
+
+ *(int*)inData = processHandle;
+ *(uint*)(inData + 4) = (uint)desiredAccess;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenProcessJob), inData, 8, outData, 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphOpenProcessToken(ProcessHandle processHandle, TokenAccess desiredAccess)
+ {
+ byte* inData = stackalloc byte[8];
+ byte* outData = stackalloc byte[4];
+
+ *(int*)inData = processHandle;
+ *(uint*)(inData + 4) = (uint)desiredAccess;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenProcessToken), inData, 8, outData, 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphOpenThread(int tid, ThreadAccess desiredAccess)
+ {
+ byte* inData = stackalloc byte[8];
+ byte* outData = stackalloc byte[4];
+
+ *(int*)inData = tid;
+ *(uint*)(inData + 4) = (uint)desiredAccess;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenThread), inData, 8, outData, 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphOpenThreadProcess(ThreadHandle threadHandle, ProcessAccess desiredAccess)
+ {
+ byte* inData = stackalloc byte[8];
+ byte* outData = stackalloc byte[4];
+
+ *(int*)inData = threadHandle;
+ *(uint*)(inData + 4) = (uint)desiredAccess;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenThreadProcess), inData, 8, outData, 4);
+
+ return *(int*)outData;
+ }
+
+ public int KphOpenType(ObjectAttributes objectAttributes)
+ {
+ byte* inData = stackalloc byte[8];
+ int typeHandle;
+
+ *(int*)inData = (int)&typeHandle;
+ *(int*)(inData + 4) = (int)&objectAttributes;
+
+ _fileHandle.IoControl(CtlCode(Control.KphOpenType), inData, 8, null, 0);
+
+ return typeHandle;
+ }
+
+ public void KphQueryInformationDriver(
+ DriverHandle driverHandle,
+ DriverInformationClass driverInformationClass,
+ IntPtr driverInformation,
+ int driverInformationLength,
+ out int returnLength
+ )
+ {
+ byte* inData = stackalloc byte[0x14];
+ int returnLengthLocal;
+
+ *(int*)inData = driverHandle;
+ *(int*)(inData + 0x4) = (int)driverInformationClass;
+ *(int*)(inData + 0x8) = driverInformation.ToInt32();
+ *(int*)(inData + 0xc) = driverInformationLength;
+ *(int*)(inData + 0x10) = (int)&returnLengthLocal;
try
{
- _fileHandle = new FileHandle(
- @"\Device\" + _deviceName,
- 0,
- FileAccess.GenericRead | FileAccess.GenericWrite
- );
+ _fileHandle.IoControl(CtlCode(Control.KphQueryInformationDriver), inData, 0x14, null, 0);
}
finally
{
- if (created)
- {
- // The SCM will delete the service when it is stopped.
- shandle.Delete();
- }
+ returnLength = returnLengthLocal;
+ }
+ }
- shandle.Dispose();
+ public void KphQueryInformationProcess(
+ ProcessHandle processHandle,
+ ProcessInformationClass processInformationClass,
+ IntPtr processInformation,
+ int processInformationLength,
+ out int returnLength
+ )
+ {
+ byte* inData = stackalloc byte[0x14];
+ int returnLengthLocal;
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = (int)processInformationClass;
+ *(int*)(inData + 0x8) = processInformation.ToInt32();
+ *(int*)(inData + 0xc) = processInformationLength;
+ *(int*)(inData + 0x10) = (int)&returnLengthLocal;
+
+ try
+ {
+ _fileHandle.IoControl(CtlCode(Control.KphQueryInformationProcess), inData, 0x14, null, 0);
+ }
+ finally
+ {
+ returnLength = returnLengthLocal;
}
}
- public KphFeatures KphGetFeatures()
+ public void KphQueryInformationThread(
+ ThreadHandle threadHandle,
+ ThreadInformationClass threadInformationClass,
+ IntPtr threadInformation,
+ int threadInformationLength,
+ out int returnLength
+ )
{
- KphGetFeaturesInput input;
- int features;
+ byte* inData = stackalloc byte[0x14];
+ int returnLengthLocal;
- input.Features = &features;
- _fileHandle.IoControl(IoCtlGetFeatures, &input, sizeof(KphGetFeaturesInput), null, 0);
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 0x4) = (int)threadInformationClass;
+ *(int*)(inData + 0x8) = threadInformation.ToInt32();
+ *(int*)(inData + 0xc) = threadInformationLength;
+ *(int*)(inData + 0x10) = (int)&returnLengthLocal;
- return (KphFeatures)features;
+ try
+ {
+ _fileHandle.IoControl(CtlCode(Control.KphQueryInformationThread), inData, 0x14, null, 0);
+ }
+ finally
+ {
+ returnLength = returnLengthLocal;
+ }
}
- public IntPtr KphOpenProcess(int pid, ProcessAccess desiredAccess)
+ public void KphQueryProcessHandles(ProcessHandle processHandle, IntPtr buffer, int bufferLength, out int returnLength)
{
- KphOpenProcessInput input;
- IntPtr processHandle;
- ClientId clientId;
+ byte* inData = stackalloc byte[0x10];
+ int returnLengthLocal;
- clientId.UniqueProcess = (IntPtr)pid;
- clientId.UniqueThread = IntPtr.Zero;
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = buffer.ToInt32();
+ *(int*)(inData + 0x8) = bufferLength;
+ *(int*)(inData + 0xc) = (int)&returnLengthLocal;
- input.ProcessHandle = &processHandle;
- input.DesiredAccess = (int)desiredAccess;
- input.ClientId = &clientId;
- _fileHandle.IoControl(IoCtlOpenProcess, &input, sizeof(KphOpenProcessInput), null, 0);
+ try
+ {
+ _fileHandle.IoControl(CtlCode(Control.KphQueryProcessHandles), inData, 0x10, null, 0);
+ }
+ finally
+ {
+ returnLength = returnLengthLocal;
+ }
+ }
- return processHandle;
+ public void KphReadVirtualMemory(ProcessHandle processHandle, int baseAddress, byte[] buffer, int length, out int bytesRead)
+ {
+ fixed (byte* bufferPtr = buffer)
+ {
+ this.KphReadVirtualMemory(processHandle, baseAddress, new IntPtr(bufferPtr), length, out bytesRead);
+ }
}
- public IntPtr KphOpenProcessToken(ProcessHandle processHandle, TokenAccess desiredAccess)
+ public void KphReadVirtualMemory(ProcessHandle processHandle, int baseAddress, IntPtr buffer, int length, out int bytesRead)
{
- KphOpenProcessTokenInput input;
- IntPtr tokenHandle;
+ NtStatus status;
- input.ProcessHandle = processHandle;
- input.DesiredAccess = (int)desiredAccess;
- input.TokenHandle = &tokenHandle;
- _fileHandle.IoControl(IoCtlOpenProcessToken, &input, sizeof(KphOpenProcessTokenInput), null, 0);
+ status = KphReadVirtualMemorySafe(processHandle, baseAddress, buffer, length, out bytesRead);
- return tokenHandle;
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
}
- public IntPtr KphOpenProcessJob(ProcessHandle processHandle, TokenAccess desiredAccess)
+ public NtStatus KphReadVirtualMemorySafe(ProcessHandle processHandle, int baseAddress, IntPtr buffer, int length, out int bytesRead)
{
- KphOpenProcessJobInput input;
- IntPtr jobHandle;
+ NtStatus status;
+ byte* inData = stackalloc byte[0x14];
+ int returnLength;
+ int br;
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = baseAddress;
+ *(int*)(inData + 0x8) = (int)buffer;
+ *(int*)(inData + 0xc) = length;
+ *(int*)(inData + 0x10) = (int)&br;
+
+ status = _fileHandle.IoControl(CtlCode(Control.KphReadVirtualMemory), (IntPtr)inData, 0x14, IntPtr.Zero, 0, out returnLength);
- input.ProcessHandle = processHandle;
- input.DesiredAccess = (int)desiredAccess;
- input.JobHandle = &jobHandle;
- _fileHandle.IoControl(IoCtlOpenProcessJob, &input, sizeof(KphOpenProcessJobInput), null, 0);
+ bytesRead = br;
- return jobHandle;
+ return status;
}
- public void KphSuspendProcess(ProcessHandle processHandle)
+ public NtStatus KphReadVirtualMemoryUnsafe(ProcessHandle processHandle, int baseAddress, void* buffer, int length, out int bytesRead)
{
- KphSuspendProcessInput input;
-
- input.ProcessHandle = processHandle;
- _fileHandle.IoControl(IoCtlSuspendProcess, &input, sizeof(KphSuspendProcessInput), null, 0);
+ return KphReadVirtualMemoryUnsafe(processHandle, baseAddress, new IntPtr(buffer), length, out bytesRead);
}
+ public NtStatus KphReadVirtualMemoryUnsafe(ProcessHandle processHandle, int baseAddress, IntPtr buffer, int length, out int bytesRead)
+ {
+ NtStatus status;
+ byte* inData = stackalloc byte[0x14];
+ int returnLength;
+ int br;
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = baseAddress;
+ *(int*)(inData + 0x8) = (int)buffer;
+ *(int*)(inData + 0xc) = length;
+ *(int*)(inData + 0x10) = (int)&br;
+
+ status = _fileHandle.IoControl(CtlCode(Control.KphUnsafeReadVirtualMemory), (IntPtr)inData, 0x14, IntPtr.Zero, 0, out returnLength);
+
+ bytesRead = br;
+
+ return status;
+ }
public void KphResumeProcess(ProcessHandle processHandle)
{
- KphResumeProcessInput input;
+ int processHandleInt = processHandle;
- input.ProcessHandle = processHandle;
- _fileHandle.IoControl(IoCtlResumeProcess, &input, sizeof(KphResumeProcessInput), null, 0);
+ _fileHandle.IoControl(CtlCode(Control.KphResumeProcess),
+ (byte*)&processHandleInt, 4, null, 0);
+ }
+
+ public void KphSetContextThread(ThreadHandle threadHandle, Context* context)
+ {
+ byte* inData = stackalloc byte[8];
+
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 4) = (int)context;
+
+ _fileHandle.IoControl(CtlCode(Control.KphSetContextThread), inData, 8, null, 0);
+ }
+
+ public void KphSetHandleGrantedAccess(IntPtr handle, int grantedAccess)
+ {
+ byte* inData = stackalloc byte[8];
+
+ *(int*)inData = handle.ToInt32();
+ *(int*)(inData + 4) = grantedAccess;
+
+ _fileHandle.IoControl(CtlCode(Control.KphSetHandleGrantedAccess), inData, 8, null, 0);
+ }
+
+ public void KphSetInformationProcess(
+ ProcessHandle processHandle,
+ ProcessInformationClass processInformationClass,
+ IntPtr processInformation,
+ int processInformationLength
+ )
+ {
+ byte* inData = stackalloc byte[0x10];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = (int)processInformationClass;
+ *(int*)(inData + 0x8) = processInformation.ToInt32();
+ *(int*)(inData + 0xc) = processInformationLength;
+
+ _fileHandle.IoControl(CtlCode(Control.KphSetInformationProcess), inData, 0x10, null, 0);
+ }
+
+ public void KphSetInformationThread(
+ ThreadHandle threadHandle,
+ ThreadInformationClass threadInformationClass,
+ IntPtr threadInformation,
+ int threadInformationLength
+ )
+ {
+ byte* inData = stackalloc byte[0x10];
+
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 0x4) = (int)threadInformationClass;
+ *(int*)(inData + 0x8) = threadInformation.ToInt32();
+ *(int*)(inData + 0xc) = threadInformationLength;
+
+ _fileHandle.IoControl(CtlCode(Control.KphSetInformationThread), inData, 0x10, null, 0);
+ }
+
+ public void KphSuspendProcess(ProcessHandle processHandle)
+ {
+ int processHandleInt = processHandle;
+
+ _fileHandle.IoControl(CtlCode(Control.KphSuspendProcess),
+ (byte*)&processHandleInt, 4, null, 0);
}
public void KphTerminateProcess(ProcessHandle processHandle, NtStatus exitStatus)
{
- KphTerminateProcessInput input;
+ byte* inData = stackalloc byte[8];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 4) = (int)exitStatus;
- input.ProcessHandle = processHandle;
- input.ExitStatus = exitStatus;
- _fileHandle.IoControl(IoCtlTerminateProcess, &input, sizeof(KphTerminateProcessInput), null, 0);
+ try
+ {
+ _fileHandle.IoControl(CtlCode(Control.KphTerminateProcess), inData, 8, null, 0);
+ }
+ catch (WindowsException ex)
+ {
+ // STATUS_CANT_TERMINATE_SELF means we tried to terminate ourself. Kernel-mode can't do it,
+ // so we do it now.
+ if (ex.Status == NtStatus.CantTerminateSelf)
+ Win32.TerminateProcess(new IntPtr(-1), (int)exitStatus);
+ else
+ throw ex;
+ }
}
+ public void KphTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
+ {
+ byte* inData = stackalloc byte[8];
+ *(int*)inData = threadHandle;
+ *(int*)(inData + 4) = (int)exitStatus;
- public void KphReadVirtualMemory(ProcessHandle processHandle, IntPtr baseAddress, IntPtr buffer, IntPtr bufferSize, void* numberOfBytesRead)
+ try
+ {
+ _fileHandle.IoControl(CtlCode(Control.KphTerminateThread), inData, 8, null, 0);
+ }
+ catch (WindowsException ex)
+ {
+ if (ex.Status == NtStatus.CantTerminateSelf)
+ Win32.TerminateThread(new IntPtr(-2), (int)exitStatus);
+ else
+ throw ex;
+ }
+ }
+
+ public void KphWriteVirtualMemory(ProcessHandle processHandle, int baseAddress, byte[] buffer, int length, out int bytesWritten)
+ {
+ fixed (byte* bufferPtr = buffer)
+ this.KphWriteVirtualMemory(processHandle, baseAddress, new IntPtr(bufferPtr), length, out bytesWritten);
+ }
+
+ public void KphWriteVirtualMemory(ProcessHandle processHandle, int baseAddress, IntPtr buffer, int length, out int bytesWritten)
{
- KphReadVirtualMemoryInput input;
+ byte* inData = stackalloc byte[0x14];
+ int returnLength;
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = baseAddress;
+ *(int*)(inData + 0x8) = (int)buffer;
+ *(int*)(inData + 0xc) = length;
+ *(int*)(inData + 0x10) = (int)&returnLength;
- input.ProcessHandle = processHandle;
- input.BaseAddress = baseAddress;
- input.Buffer = buffer;
- input.BufferSize = bufferSize;
- input.NumberOfBytesRead = (IntPtr*)(&numberOfBytesRead);
- _fileHandle.IoControl(IoCtlReadVirtualMemory, &input, sizeof(KphReadVirtualMemoryInput), null, 0);
+ try
+ {
+ _fileHandle.IoControl(CtlCode(Control.KphWriteVirtualMemory), inData, 0x14, null, 0);
+ }
+ finally
+ {
+ bytesWritten = returnLength;
+ }
}
- public void KphWriteVirtualMemory(ProcessHandle processHandle, IntPtr baseAddress, IntPtr buffer, IntPtr bufferSize, void* numberOfBytesWritten)
+ public void ProtectAdd(ProcessHandle processHandle, bool allowKernelMode, ProcessAccess ProcessAllowMask, ThreadAccess ThreadAllowMask)
{
- KphWriteVirtualMemoryInput input;
+ byte* inData = stackalloc byte[16];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = allowKernelMode ? 1 : 0;
+ *(int*)(inData + 0x8) = (int)ProcessAllowMask;
+ *(int*)(inData + 0xc) = (int)ThreadAllowMask;
- input.ProcessHandle = processHandle;
- input.BaseAddress = baseAddress;
- input.Buffer = buffer;
- input.BufferSize = bufferSize;
- input.NumberOfBytesWritten = (IntPtr*)(&numberOfBytesWritten);
- _fileHandle.IoControl(IoCtlWriteVirtualMemory, &input, sizeof(KphWriteVirtualMemoryInput), null, 0);
+ _fileHandle.IoControl(CtlCode(Control.ProtectAdd), inData, 16, null, 0);
}
+ public void ProtectQuery(ProcessHandle processHandle, out bool AllowKernelMode, out ProcessAccess ProcessAllowMask, out ThreadAccess ThreadAllowMask)
+ {
+ byte* inData = stackalloc byte[16];
+ int allowKernelMode;
+ ProcessAccess processAllowMask;
+ ThreadAccess threadAllowMask;
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = (int)&allowKernelMode;
+ *(int*)(inData + 0x8) = (int)&processAllowMask;
+ *(int*)(inData + 0xc) = (int)&threadAllowMask;
+
+ _fileHandle.IoControl(CtlCode(Control.ProtectQuery), inData, 16, null, 0);
- public void KphReadVirtualMemoryUnsafe(ProcessHandle processHandle, IntPtr baseAddress, IntPtr buffer, IntPtr bufferSize, void* numberOfBytesRead)
+ AllowKernelMode = allowKernelMode != 0;
+ ProcessAllowMask = processAllowMask;
+ ThreadAllowMask = threadAllowMask;
+ }
+
+ public void ProtectRemove(ProcessHandle processHandle)
{
- KphReadVirtualMemoryUnsafeInput input;
+ int processHandleInt = processHandle;
+
+ _fileHandle.IoControl(CtlCode(Control.ProtectRemove),
+ (byte*)&processHandleInt, 4, null, 0);
+ }
- input.ProcessHandle = processHandle;
- input.BaseAddress = baseAddress;
- input.Buffer = buffer;
- input.BufferSize = bufferSize;
+ public void SetExecuteOptions(ProcessHandle processHandle, MemExecuteOptions executeOptions)
+ {
+ byte* inData = stackalloc byte[8];
- input.NumberOfBytesRead = (IntPtr*)(&numberOfBytesRead);
+ *(int*)inData = processHandle;
+ *(int*)(inData + 4) = (int)executeOptions;
- _fileHandle.IoControl(IoCtlReadVirtualMemoryUnsafe, &input, sizeof(KphReadVirtualMemoryUnsafeInput), null, 0);
+ _fileHandle.IoControl(CtlCode(Control.SetExecuteOptions), inData, 8, null, 0);
}
+ public void SetHandleAttributes(ProcessHandle processHandle, IntPtr handle, HandleFlags flags)
+ {
+ byte* inData = stackalloc byte[12];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 4) = handle.ToInt32();
+ *(int*)(inData + 8) = (int)flags;
+
+ _fileHandle.IoControl(CtlCode(Control.SetHandleAttributes), inData, 12, null, 0);
+ }
- public void KphQueryInformationProcess(ProcessHandle processHandle, KphProcessInformationClass processInformationClass, IntPtr processInformation, int processInformationLength, out int returnLength)
+ public void SetProcessProtected(int pid, bool protecte)
{
- KphQueryInformationProcessInput input;
+ byte* inData = stackalloc byte[5];
+
+ *(int*)inData = pid;
+ inData[4] = (byte)(protecte ? 1 : 0);
- input.ProcessHandle = processHandle;
- input.ProcessInformationClass = processInformationClass;
- input.ProcessInformation = processInformation;
- input.ProcessInformationLength = processInformationLength;
+ _fileHandle.IoControl(CtlCode(Control.SetProcessProtected), inData, 5, null, 0);
+ }
+
+ public void SetProcessToken(int sourcePid, int targetPid)
+ {
+ byte* inData = stackalloc byte[8];
- returnLength = 0;
- input.ReturnLength = returnLength;
+ *(int*)inData = sourcePid;
+ *(int*)(inData + 4) = targetPid;
- _fileHandle.IoControl(IoCtlQueryInformationProcess, &input, sizeof(KphQueryInformationProcessInput), null, 0);
+ _fileHandle.IoControl(CtlCode(Control.SetProcessToken), inData, 8, null, 0);
}
- public void Dispose()
+ public IntPtr SsAddProcessIdRule(
+ KphSsRuleSetEntryHandle ruleSetEntryHandle,
+ KphSsFilterType filterType,
+ IntPtr processId
+ )
{
- if (_fileHandle != null)
- {
- try
- {
- _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, 0);
- _fileHandle.Dispose();
- }
- catch (Exception)
- { }
- }
+ byte* inData = stackalloc byte[0xc];
+ byte* outData = stackalloc byte[4];
+
+ *(int*)inData = ruleSetEntryHandle.Handle.ToInt32();
+ *(int*)(inData + 0x4) = (int)filterType;
+ *(int*)(inData + 0x8) = processId.ToInt32();
+
+ _fileHandle.IoControl(CtlCode(Control.SsAddProcessIdRule), inData, 0xc, outData, 4);
+
+ return (*(int*)outData).ToIntPtr();
}
- }
- public enum KphSecurityLevel
- {
- KphSecurityNone = 0, // all clients are allowed
- KphSecurityPrivilegeCheck = 1, // require SeDebugPrivilege
- KphMaxSecurityLevel
- }
+ public IntPtr SsAddThreadIdRule(
+ KphSsRuleSetEntryHandle ruleSetEntryHandle,
+ KphSsFilterType filterType,
+ IntPtr threadId
+ )
+ {
+ byte* inData = stackalloc byte[0xc];
+ byte* outData = stackalloc byte[4];
- public enum KphProcessInformationClass
- {
- KphProcessProtectionInformation = 1,
- KphProcessExecuteFlags = 2,
- KphProcessIoPriority = 3,
- MaxKphProcessInfoClass
- }
+ *(int*)inData = ruleSetEntryHandle.Handle.ToInt32();
+ *(int*)(inData + 0x4) = (int)filterType;
+ *(int*)(inData + 0x8) = threadId.ToInt32();
- [StructLayout(LayoutKind.Sequential)]
- public struct KphProcessProtectionInformation
- {
- public byte IsProtectedProcess;
- }
+ _fileHandle.IoControl(CtlCode(Control.SsAddThreadIdRule), inData, 0xc, outData, 4);
- public enum KphThreadInformationClass
- {
- KphThreadWin32Thread = 1,
- KphThreadImpersonationToken = 2,
- KphThreadIoPriority = 3,
- MaxKphThreadInfoClass
- }
+ return (*(int*)outData).ToIntPtr();
+ }
- [StructLayout(LayoutKind.Sequential)]
- public struct KphProcessHandle
- {
- public IntPtr Handle;
- public IntPtr Object;
- public int GrantedAccess;
- public short ObjectTypeIndex;
- public short Reserved1;
- public int HandleAttributes;
- private int Reserved2;
- }
+ public IntPtr SsAddPreviousModeRule(
+ KphSsRuleSetEntryHandle ruleSetEntryHandle,
+ KphSsFilterType filterType,
+ KProcessorMode previousMode
+ )
+ {
+ byte* inData = stackalloc byte[0x9];
+ byte* outData = stackalloc byte[4];
- [StructLayout(LayoutKind.Sequential)]
- public struct KphProcessHandleInformation
- {
- public static readonly int HandlesOffset =
- Marshal.OffsetOf(typeof(KphProcessHandleInformation), "Handles").ToInt32();
+ *(int*)inData = ruleSetEntryHandle.Handle.ToInt32();
+ *(int*)(inData + 0x4) = (int)filterType;
+ *(byte*)(inData + 0x8) = (byte)previousMode;
- public int HandleCount;
- public KphProcessHandle Handles;
- }
+ _fileHandle.IoControl(CtlCode(Control.SsAddPreviousModeRule), inData, 0x9, outData, 4);
- public enum KphObjectInformationClass
- {
- KphObjectBasicInformation,
- KphObjectNameInformation,
- KphObjectTypeInformation,
- KphObjectHandleFlagInformation,
- KphObjectProcessBasicInformation,
- KphObjectThreadBasicInformation,
- KphObjectEtwRegBasicInformation,
- MaxKphObjectInfoClass
- }
+ return (*(int*)outData).ToIntPtr();
+ }
- public enum DriverInformationClass
- {
- DriverBasicInformation,
- DriverNameInformation,
- DriverServiceKeyNameInformation,
- MaxDriverInfoClass
- }
+ public IntPtr SsAddNumberRule(
+ KphSsRuleSetEntryHandle ruleSetEntryHandle,
+ KphSsFilterType filterType,
+ int number
+ )
+ {
+ byte* inData = stackalloc byte[0xc];
+ byte* outData = stackalloc byte[4];
- [StructLayout(LayoutKind.Sequential)]
- public struct DriverBasicInformation
- {
- public int Flags;
- public IntPtr DriverStart;
- public int DriverSize;
- }
+ *(int*)inData = ruleSetEntryHandle.Handle.ToInt32();
+ *(int*)(inData + 0x4) = (int)filterType;
+ *(int*)(inData + 0x8) = number;
- //[StructLayout(LayoutKind.Sequential)]
- //public struct DriverBasicInformation
- //{
- // public UnicodeString DriverName;
- //}
+ _fileHandle.IoControl(CtlCode(Control.SsAddNumberRule), inData, 0xc, outData, 4);
- [StructLayout(LayoutKind.Sequential)]
- public struct DriverServiceKeyNameInformation
- {
- public UnicodeString ServiceKeyName;
- }
+ return (*(int*)outData).ToIntPtr();
+ }
- [StructLayout(LayoutKind.Sequential)]
- public struct EtwRegBasicInformation
- {
- public Guid Guid;
- public IntPtr SessionId;
- }
+ public KphSsClientEntryHandle SsCreateClientEntry(
+ ProcessHandle processHandle,
+ SemaphoreHandle readSemaphoreHandle,
+ SemaphoreHandle writeSemaphoreHandle,
+ IntPtr bufferBase,
+ int bufferSize
+ )
+ {
+ byte* inData = stackalloc byte[0x14];
+ byte* outData = stackalloc byte[4];
+ *(int*)inData = processHandle;
+ *(int*)(inData + 0x4) = readSemaphoreHandle;
+ *(int*)(inData + 0x8) = writeSemaphoreHandle;
+ *(int*)(inData + 0xc) = bufferBase.ToInt32();
+ *(int*)(inData + 0x10) = bufferSize;
- [StructLayout(LayoutKind.Sequential)]
- public unsafe struct KphOpenProcessJobInput
- {
- public IntPtr ProcessHandle;
- public int DesiredAccess;
- public IntPtr* JobHandle;
- }
+ _fileHandle.IoControl(CtlCode(Control.SsCreateClientEntry), inData, 0x14, outData, 4);
- [StructLayout(LayoutKind.Sequential)]
- public unsafe struct KphGetFeaturesInput
- {
- public int* Features;
- }
+ return new KphSsClientEntryHandle((*(int*)outData).ToIntPtr());
+ }
- [StructLayout(LayoutKind.Sequential)]
- public unsafe struct KphOpenProcessInput
- {
- public IntPtr* ProcessHandle;
- public int DesiredAccess;
- public ClientId* ClientId;
- }
+ public KphSsRuleSetEntryHandle SsCreateRuleSetEntry(
+ KphSsClientEntryHandle clientEntryHandle,
+ KphSsFilterType defaultFilterType,
+ KphSsRuleSetAction action
+ )
+ {
+ byte* inData = stackalloc byte[0xc];
+ byte* outData = stackalloc byte[4];
- [StructLayout(LayoutKind.Sequential)]
- public unsafe struct KphOpenProcessTokenInput
- {
- public IntPtr ProcessHandle;
- public int DesiredAccess;
- public IntPtr* TokenHandle;
- }
+ *(int*)inData = clientEntryHandle.Handle.ToInt32();
+ *(int*)(inData + 0x4) = (int)defaultFilterType;
+ *(int*)(inData + 0x8) = (int)action;
- [StructLayout(LayoutKind.Sequential)]
- public struct KphSuspendProcessInput
- {
- public IntPtr ProcessHandle;
- }
+ _fileHandle.IoControl(CtlCode(Control.SsCreateRuleSetEntry), inData, 0xc, outData, 4);
- [StructLayout(LayoutKind.Sequential)]
- public struct KphResumeProcessInput
- {
- public IntPtr ProcessHandle;
+ return new KphSsRuleSetEntryHandle((*(int*)outData).ToIntPtr());
+ }
+
+ public void SsEnableClientEntry(
+ KphSsClientEntryHandle clientEntryHandle,
+ bool enable
+ )
+ {
+ byte* inData = stackalloc byte[5];
+
+ *(int*)inData = clientEntryHandle.Handle.ToInt32();
+ *(byte*)(inData + 4) = (byte)(enable ? 1 : 0);
+
+ _fileHandle.IoControl(CtlCode(Control.SsEnableClientEntry), inData, 5, null, 0);
+ }
+
+ public void SsQueryClientEntry(
+ KphSsClientEntryHandle clientEntryHandle,
+ out KphSsClientInformation clientInformation,
+ int clientInformationLength,
+ out int returnLength
+ )
+ {
+ fixed (KphSsClientInformation *clientInfoPtr = &clientInformation)
+ fixed (int* retLengthPtr = &returnLength)
+ {
+ byte* inData = stackalloc byte[0x10];
+
+ *(int*)inData = clientEntryHandle.Handle.ToInt32();
+ *(int*)(inData + 0x4) = (int)clientInfoPtr;
+ *(int*)(inData + 0x8) = clientInformationLength;
+ *(int*)(inData + 0xc) = (int)retLengthPtr;
+
+ _fileHandle.IoControl(CtlCode(Control.SsQueryClientEntry), inData, 0x10, null, 0);
+ }
+ }
+
+ public void SsRemoveRule(
+ KphSsRuleSetEntryHandle ruleSetEntryHandle,
+ IntPtr ruleEntryHandle
+ )
+ {
+ byte* inData = stackalloc byte[8];
+
+ *(int*)inData = ruleSetEntryHandle.Handle.ToInt32();
+ *(int*)(inData + 4) = ruleEntryHandle.ToInt32();
+
+ _fileHandle.IoControl(CtlCode(Control.SsRemoveRule), inData, 8, null, 0);
+ }
+
+ public void SsRef()
+ {
+ _fileHandle.IoControl(CtlCode(Control.SsRef), null, null);
+ }
+
+ public void SsUnref()
+ {
+ _fileHandle.IoControl(CtlCode(Control.SsUnref), null, null);
+ }
+
+ public NtStatus ZwQueryObject(
+ ProcessHandle processHandle,
+ IntPtr handle,
+ ObjectInformationClass objectInformationClass,
+ IntPtr buffer,
+ int bufferLength,
+ out int returnLength,
+ out int baseAddress
+ )
+ {
+ byte* inData = stackalloc byte[12];
+ byte[] outData = new byte[bufferLength + 12];
+
+ *(int*)inData = processHandle;
+ *(int*)(inData + 4) = handle.ToInt32();
+ *(int*)(inData + 8) = (int)objectInformationClass;
+
+ _fileHandle.IoControl(CtlCode(Control.ZwQueryObject), inData, 12, outData);
+
+ NtStatus status;
+
+ fixed (byte* outDataPtr = outData)
+ {
+ status = *(NtStatus*)outDataPtr;
+ returnLength = *(int*)(outDataPtr + 4);
+ baseAddress = *(int*)(outDataPtr + 8);
+ }
+
+ if (buffer != IntPtr.Zero)
+ Marshal.Copy(outData, 12, buffer, bufferLength);
+
+ return status;
+ }
}
- [StructLayout(LayoutKind.Sequential)]
- public struct KphTerminateProcessInput
+ public enum DriverInformationClass
{
- public IntPtr ProcessHandle;
- public NtStatus ExitStatus;
+ DriverBasicInformation = 0,
+ DriverNameInformation,
+ DriverServiceKeyNameInformation
}
- [StructLayout(LayoutKind.Sequential)]
- public unsafe struct KphReadVirtualMemoryInput
+ public class KphHandle : BaseObject
{
- public IntPtr ProcessHandle;
- public IntPtr BaseAddress;
- public IntPtr Buffer;
- public IntPtr BufferSize;
- public IntPtr* NumberOfBytesRead;
- }
+ private IntPtr _handle;
+ protected KphHandle(IntPtr handle)
+ {
+ _handle = handle;
+ }
- [StructLayout(LayoutKind.Sequential)]
- public unsafe struct KphWriteVirtualMemoryInput
- {
- public IntPtr ProcessHandle;
- public IntPtr BaseAddress;
- public IntPtr Buffer;
- public IntPtr BufferSize;
- public IntPtr* NumberOfBytesWritten;
+ protected override void DisposeObject(bool disposing)
+ {
+ KProcessHacker.Instance.ClientCloseHandle(_handle);
+ }
+
+ public IntPtr Handle
+ {
+ get { return _handle; }
+ }
}
[StructLayout(LayoutKind.Sequential)]
- public unsafe struct KphReadVirtualMemoryUnsafeInput
+ public struct DriverBasicInformation
{
- public IntPtr ProcessHandle;
- public IntPtr BaseAddress;
- public IntPtr Buffer;
- public IntPtr BufferSize;
- public IntPtr* NumberOfBytesRead;
+ public int Flags;
+ public IntPtr DriverStart;
+ public int DriverSize;
}
+
[StructLayout(LayoutKind.Sequential)]
- public struct KphQueryInformationProcessInput
+ public struct ProcessHandleInformation
{
- public IntPtr ProcessHandle;
- public KphProcessInformationClass ProcessInformationClass;
- public IntPtr ProcessInformation;
- public int ProcessInformationLength;
- public int ReturnLength;
- }
+ public IntPtr Handle;
+ public IntPtr Object;
+ public int GrantedAccess;
+ public HandleFlags HandleAttributes; // should be an int
+ private byte Pad1;
+ private short Pad2;
+ private void Dummy()
+ {
+ Pad1 = 0;
+ Pad2 = 0;
+ }
+ }
}
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphOpenProcessToken(
-// __in HANDLE ProcessHandle,
-// __in ACCESS_MASK DesiredAccess,
-// __out PHANDLE TokenHandle
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphOpenProcessJob(
-// __in HANDLE ProcessHandle,
-// __in ACCESS_MASK DesiredAccess,
-// __out PHANDLE JobHandle
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphSuspendProcess(
-// __in HANDLE ProcessHandle
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphResumeProcess(
-// __in HANDLE ProcessHandle
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphTerminateProcess(
-// __in HANDLE ProcessHandle,
-// __in NTSTATUS ExitStatus
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphReadVirtualMemory(
-// __in HANDLE ProcessHandle,
-// __in PVOID BaseAddress,
-// __out_bcount(BufferSize) PVOID Buffer,
-// __in SIZE_T BufferSize,
-// __out_opt PSIZE_T NumberOfBytesRead
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphWriteVirtualMemory(
-// __in HANDLE ProcessHandle,
-// __in_opt PVOID BaseAddress,
-// __in_bcount(BufferSize) PVOID Buffer,
-// __in SIZE_T BufferSize,
-// __out_opt PSIZE_T NumberOfBytesWritten
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphReadVirtualMemoryUnsafe(
-// __in_opt HANDLE ProcessHandle,
-// __in PVOID BaseAddress,
-// __out_bcount(BufferSize) PVOID Buffer,
-// __in SIZE_T BufferSize,
-// __out_opt PSIZE_T NumberOfBytesRead
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphQueryInformationProcess(
-// __in HANDLE ProcessHandle,
-// __in KPH_PROCESS_INFORMATION_CLASS ProcessInformationClass,
-// __out_bcount(ProcessInformationLength) PVOID ProcessInformation,
-// __in ULONG ProcessInformationLength,
-// __out_opt PULONG ReturnLength
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphSetInformationProcess(
-// __in HANDLE ProcessHandle,
-// __in KPH_PROCESS_INFORMATION_CLASS ProcessInformationClass,
-// __in_bcount(ProcessInformationLength) PVOID ProcessInformation,
-// __in ULONG ProcessInformationLength
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphOpenThread(
-// __out PHANDLE ThreadHandle,
-// __in ACCESS_MASK DesiredAccess,
-// __in PCLIENT_ID ClientId
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphOpenThreadProcess(
-// __in HANDLE ThreadHandle,
-// __in ACCESS_MASK DesiredAccess,
-// __out PHANDLE ProcessHandle
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphTerminateThread(
-// __in HANDLE ThreadHandle,
-// __in NTSTATUS ExitStatus
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphTerminateThreadUnsafe(
-// __in HANDLE ThreadHandle,
-// __in NTSTATUS ExitStatus
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphGetContextThread(
-// __in HANDLE ThreadHandle,
-// __inout PCONTEXT ThreadContext
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphSetContextThread(
-// __in HANDLE ThreadHandle,
-// __in PCONTEXT ThreadContext
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphCaptureStackBackTraceThread(
-// __in HANDLE ThreadHandle,
-// __in ULONG FramesToSkip,
-// __in ULONG FramesToCapture,
-// __out_ecount(FramesToCapture) PVOID *BackTrace,
-// __out_opt PULONG CapturedFrames,
-// __out_opt PULONG BackTraceHash
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphQueryInformationThread(
-// __in HANDLE ThreadHandle,
-// __in KPH_THREAD_INFORMATION_CLASS ThreadInformationClass,
-// __out_bcount(ProcessInformationLength) PVOID ThreadInformation,
-// __in ULONG ThreadInformationLength,
-// __out_opt PULONG ReturnLength
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphSetInformationThread(
-// __in HANDLE ThreadHandle,
-// __in KPH_THREAD_INFORMATION_CLASS ThreadInformationClass,
-// __in_bcount(ThreadInformationLength) PVOID ThreadInformation,
-// __in ULONG ThreadInformationLength
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphEnumerateProcessHandles(
-// __in HANDLE ProcessHandle,
-// __out_bcount(BufferLength) PVOID Buffer,
-// __in_opt ULONG BufferLength,
-// __out_opt PULONG ReturnLength
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphQueryInformationObject(
-// __in HANDLE ProcessHandle,
-// __in HANDLE Handle,
-// __in KPH_OBJECT_INFORMATION_CLASS ObjectInformationClass,
-// __out_bcount(ObjectInformationLength) PVOID ObjectInformation,
-// __in ULONG ObjectInformationLength,
-// __out_opt PULONG ReturnLength
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphSetInformationObject(
-// __in HANDLE ProcessHandle,
-// __in HANDLE Handle,
-// __in KPH_OBJECT_INFORMATION_CLASS ObjectInformationClass,
-// __in_bcount(ObjectInformationLength) PVOID ObjectInformation,
-// __in ULONG ObjectInformationLength
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphDuplicateObject(
-// __in HANDLE SourceProcessHandle,
-// __in HANDLE SourceHandle,
-// __in_opt HANDLE TargetProcessHandle,
-// __out_opt PHANDLE TargetHandle,
-// __in ACCESS_MASK DesiredAccess,
-// __in ULONG HandleAttributes,
-// __in ULONG Options
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphOpenDriver(
-// __out PHANDLE DriverHandle,
-// __in POBJECT_ATTRIBUTES ObjectAttributes
-// );
-
-//PHLIBAPI
-//NTSTATUS
-//NTAPI
-//KphQueryInformationDriver(
-// __in HANDLE DriverHandle,
-// __in DRIVER_INFORMATION_CLASS DriverInformationClass,
-// __out_bcount(DriverInformationLength) PVOID DriverInformation,
-// __in ULONG DriverInformationLength,
-// __out_opt PULONG ReturnLength
-// );
diff --git a/1.x/trunk/ProcessHacker.Native/Loader.cs b/1.x/trunk/ProcessHacker.Native/Loader.cs
index bbb8ba184..3d26f1dec 100644
--- a/1.x/trunk/ProcessHacker.Native/Loader.cs
+++ b/1.x/trunk/ProcessHacker.Native/Loader.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native
diff --git a/1.x/trunk/ProcessHacker.Native/Lpc/PortMessage.cs b/1.x/trunk/ProcessHacker.Native/Lpc/PortMessage.cs
index 68bcbf489..c824603cb 100644
--- a/1.x/trunk/ProcessHacker.Native/Lpc/PortMessage.cs
+++ b/1.x/trunk/ProcessHacker.Native/Lpc/PortMessage.cs
@@ -1,4 +1,5 @@
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
@@ -6,6 +7,8 @@ namespace ProcessHacker.Native.Lpc
{
public class PortMessage : BaseObject
{
+ private static readonly int _portMessageSize = Marshal.SizeOf(typeof(PortMessageStruct));
+
public static MemoryAlloc AllocateBuffer()
{
return new MemoryAlloc(Win32.PortMessageMaxLength);
@@ -40,7 +43,7 @@ public PortMessage(PortMessage existingMessage, MemoryRegion data, short dataLen
internal PortMessage(MemoryRegion headerAndData)
{
_message = headerAndData.ReadStruct();
- _data = new MemoryRegion(headerAndData, PortMessageStruct.SizeOf, _message.DataLength);
+ _data = new MemoryRegion(headerAndData, _portMessageSize, _message.DataLength);
_referencedData = headerAndData;
_referencedData.Reference();
@@ -89,12 +92,11 @@ private void InitializeMessage(PortMessage existingMessage, MemoryRegion data, s
if (dataLength < 0)
throw new ArgumentOutOfRangeException("Data length cannot be negative.");
- _message = new PortMessageStruct
- {
- DataLength = dataLength,
- TotalLength = (short)(PortMessageStruct.SizeOf + dataLength),
- DataInfoOffset = 0
- };
+ _message = new PortMessageStruct();
+
+ _message.DataLength = dataLength;
+ _message.TotalLength = (short)(_portMessageSize + dataLength);
+ _message.DataInfoOffset = 0;
if (existingMessage != null)
{
@@ -115,10 +117,10 @@ internal void SetHeader(MemoryRegion data)
public MemoryAlloc ToMemory()
{
- MemoryAlloc data = new MemoryAlloc(PortMessageStruct.SizeOf + _message.DataLength);
+ MemoryAlloc data = new MemoryAlloc(_portMessageSize + _message.DataLength);
- data.WriteStruct(_message);
- data.WriteMemory(PortMessageStruct.SizeOf, _data, _message.DataLength);
+ data.WriteStruct(_message);
+ data.WriteMemory(_portMessageSize, _data, _message.DataLength);
return data;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/AlignedMemoryAlloc.cs b/1.x/trunk/ProcessHacker.Native/Memory/AlignedMemoryAlloc.cs
index 2151bb091..101684cbc 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/AlignedMemoryAlloc.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/AlignedMemoryAlloc.cs
@@ -1,21 +1,23 @@
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Common;
namespace ProcessHacker.Native
{
- public sealed class AlignedMemoryAlloc : MemoryAlloc
+ public class AlignedMemoryAlloc : MemoryAlloc
{
- private readonly IntPtr _realMemory;
+ private IntPtr _realMemory;
public AlignedMemoryAlloc(int size, int alignment)
{
// Make sure the alignment is positive and a power of two.
- if (alignment <= 0 || alignment.CountBits() != 1)
+ if (alignment <= 0 || Utils.CountBits(alignment) != 1)
throw new ArgumentOutOfRangeException("alignment");
// Since we are going to align our pointer, we need to account for
// any padding at the beginning.
- _realMemory = PrivateHeap.Allocate(size + alignment - 1);
+ _realMemory = MemoryAlloc.PrivateHeap.Allocate(0, size + alignment - 1);
// aligned memory = (memory + alignment - 1) & ~(alignment - 1)
this.Memory = _realMemory.Align(alignment);
@@ -24,7 +26,7 @@ public AlignedMemoryAlloc(int size, int alignment)
protected override void Free()
{
- PrivateHeap.Free(_realMemory);
+ MemoryAlloc.PrivateHeap.Free(0, _realMemory);
}
public override void Resize(int newSize)
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/Heap.cs b/1.x/trunk/ProcessHacker.Native/Memory/Heap.cs
index 21ef5c251..7696c7215 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/Heap.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/Heap.cs
@@ -60,13 +60,11 @@ public static Heap[] GetHeaps()
return heaps;
}
- private readonly IntPtr _heap;
- private readonly HeapFlags _flags;
+ private IntPtr _heap;
private Heap(IntPtr heap)
{
_heap = heap;
- _flags = 0;
}
public Heap(HeapFlags flags)
@@ -86,8 +84,6 @@ public Heap(HeapFlags flags, int reserveSize, int commitSize)
if (_heap == IntPtr.Zero)
throw new OutOfMemoryException();
-
- _flags = flags;
}
public IntPtr Address
@@ -95,9 +91,9 @@ public IntPtr Address
get { return _heap; }
}
- public IntPtr Allocate(int size)
+ public IntPtr Allocate(HeapFlags flags, int size)
{
- IntPtr memory = Win32.RtlAllocateHeap(_heap, _flags, size.ToIntPtr());
+ IntPtr memory = Win32.RtlAllocateHeap(_heap, flags, size.ToIntPtr());
if (memory == IntPtr.Zero)
throw new OutOfMemoryException();
@@ -105,9 +101,9 @@ public IntPtr Allocate(int size)
return memory;
}
- public int Compact()
+ public int Compact(HeapFlags flags)
{
- return Win32.RtlCompactHeap(_heap, _flags).ToInt32();
+ return Win32.RtlCompactHeap(_heap, flags).ToInt32();
}
public void Destroy()
@@ -115,19 +111,19 @@ public void Destroy()
Win32.RtlDestroyHeap(_heap);
}
- public void Free(IntPtr memory)
+ public void Free(HeapFlags flags, IntPtr memory)
{
- Win32.RtlFreeHeap(_heap, _flags, memory);
+ Win32.RtlFreeHeap(_heap, flags, memory);
}
- public int GetBlockSize(IntPtr memory)
+ public int GetBlockSize(HeapFlags flags, IntPtr memory)
{
- return Win32.RtlSizeHeap(_heap, _flags, memory).ToInt32();
+ return Win32.RtlSizeHeap(_heap, flags, memory).ToInt32();
}
- public IntPtr Reallocate(IntPtr memory, int size)
+ public IntPtr Reallocate(HeapFlags flags, IntPtr memory, int size)
{
- IntPtr newMemory = Win32.RtlReAllocateHeap(_heap, _flags, memory, size.ToIntPtr());
+ IntPtr newMemory = Win32.RtlReAllocateHeap(_heap, flags, memory, size.ToIntPtr());
if (newMemory == IntPtr.Zero)
throw new OutOfMemoryException();
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/LsaMemoryAlloc.cs b/1.x/trunk/ProcessHacker.Native/Memory/LsaMemoryAlloc.cs
index ce3a3fcd2..b9503fab7 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/LsaMemoryAlloc.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/LsaMemoryAlloc.cs
@@ -31,7 +31,7 @@ namespace ProcessHacker.Native
///
public sealed class LsaMemoryAlloc : MemoryAlloc
{
- private readonly bool _secur32;
+ private bool _secur32;
public LsaMemoryAlloc(IntPtr memory)
: this(memory, false)
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/MemoryAlloc.cs b/1.x/trunk/ProcessHacker.Native/Memory/MemoryAlloc.cs
index 05caa373f..0bd646fec 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/MemoryAlloc.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/MemoryAlloc.cs
@@ -20,11 +20,13 @@
* along with Process Hacker. If not, see .
*/
-#if DEBUG
#define ENABLE_STATISTICS
-#endif
using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Text;
+using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native
@@ -34,13 +36,13 @@ namespace ProcessHacker.Native
///
public class MemoryAlloc : MemoryRegion
{
- private static int _allocatedCount;
- private static int _freedCount;
- private static int _reallocatedCount;
+ private static int _allocatedCount = 0;
+ private static int _freedCount = 0;
+ private static int _reallocatedCount = 0;
// A private heap just for the client.
private static Heap _privateHeap = new Heap(HeapFlags.Class1 | HeapFlags.Growable);
- //private static Heap _processHeap = Heap.GetDefault();
+ private static Heap _processHeap = Heap.GetDefault();
public static int AllocatedCount
{
@@ -67,6 +69,7 @@ public static int ReallocatedCount
/// You must set the pointer using the Memory property.
///
protected MemoryAlloc()
+ : base()
{ }
public MemoryAlloc(IntPtr memory)
@@ -96,25 +99,21 @@ public MemoryAlloc(int size)
/// Any flags to use.
public MemoryAlloc(int size, HeapFlags flags)
{
- this.Memory = _privateHeap.Allocate(size);
+ this.Memory = _privateHeap.Allocate(flags, size);
this.Size = size;
#if ENABLE_STATISTICS
System.Threading.Interlocked.Increment(ref _allocatedCount);
#endif
- if (this.Size > 0)
- GC.AddMemoryPressure(this.Size);
}
protected override void Free()
{
- _privateHeap.Free(this);
+ _privateHeap.Free(0, this);
#if ENABLE_STATISTICS
System.Threading.Interlocked.Increment(ref _freedCount);
#endif
- if (this.Size > 0)
- GC.RemoveMemoryPressure(this.Size);
}
///
@@ -123,17 +122,12 @@ protected override void Free()
/// The new size of the allocation.
public virtual void Resize(int newSize)
{
- if (newSize > 0)
- GC.RemoveMemoryPressure(this.Size);
-
- this.Memory = _privateHeap.Reallocate(this.Memory, newSize);
+ this.Memory = _privateHeap.Reallocate(0, this.Memory, newSize);
this.Size = newSize;
#if ENABLE_STATISTICS
System.Threading.Interlocked.Increment(ref _reallocatedCount);
#endif
- if (this.Size > 0)
- GC.AddMemoryPressure(this.Size);
}
///
@@ -143,16 +137,9 @@ public virtual void Resize(int newSize)
/// The new size of the allocation.
public virtual void ResizeNew(int newSize)
{
- if (newSize > 0)
- GC.RemoveMemoryPressure(this.Size);
-
- _privateHeap.Free(this.Memory);
-
- this.Memory = _privateHeap.Allocate(newSize);
+ _privateHeap.Free(0, this.Memory);
+ this.Memory = _privateHeap.Allocate(0, newSize);
this.Size = newSize;
-
- if (this.Size > 0)
- GC.AddMemoryPressure(this.Size);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegion.cs b/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegion.cs
index c04ca3efc..cd1d7b596 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegion.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegion.cs
@@ -20,15 +20,68 @@
* along with Process Hacker. If not, see .
*/
+#define SIZE_CACHE_USE_RESOURCE_LOCK
+
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Text;
using ProcessHacker.Common.Objects;
-using ProcessHacker.Native.Api;
+using ProcessHacker.Common.Threading;
namespace ProcessHacker.Native
{
public class MemoryRegion : BaseObject
{
+ private static Dictionary _sizeCache = new Dictionary();
+#if SIZE_CACHE_USE_RESOURCE_LOCK
+ private static FastResourceLock _sizeCacheLock = new FastResourceLock();
+#endif
+
+ private static int GetStructSize(Type structType)
+ {
+ int size;
+
+#if SIZE_CACHE_USE_RESOURCE_LOCK
+ _sizeCacheLock.AcquireShared();
+
+ if (_sizeCache.ContainsKey(structType))
+ {
+ size = _sizeCache[structType];
+ _sizeCacheLock.ReleaseShared();
+ }
+ else
+ {
+ _sizeCacheLock.ReleaseShared();
+
+ size = Marshal.SizeOf(structType);
+ _sizeCacheLock.AcquireExclusive();
+
+ try
+ {
+ if (!_sizeCache.ContainsKey(structType))
+ _sizeCache.Add(structType, size);
+ }
+ finally
+ {
+ _sizeCacheLock.ReleaseExclusive();
+ }
+ }
+
+ return size;
+#else
+ lock (_sizeCache)
+ {
+ if (_sizeCache.ContainsKey(structType))
+ size = _sizeCache[structType];
+ else
+ _sizeCache.Add(structType, size = Marshal.SizeOf(structType));
+
+ return size;
+ }
+#endif
+ }
+
public static T ReadStruct(IntPtr ptr)
{
return (T)Marshal.PtrToStructure(ptr, typeof(T));
@@ -44,7 +97,7 @@ public static implicit operator IntPtr(MemoryRegion memory)
return memory.Memory.ToPointer();
}
- private readonly MemoryRegion _parent;
+ private MemoryRegion _parent;
private IntPtr _memory;
private int _size;
@@ -121,15 +174,15 @@ public virtual int Size
public void DestroyStruct()
{
- Marshal.DestroyStructure(_memory, typeof(T));
+ this.DestroyStruct(0);
}
- public void DestroyStruct(int index, int size)
+ public void DestroyStruct(int index)
{
- this.DestroyStruct(0, index, size);
+ this.DestroyStruct(0, index);
}
- public void DestroyStruct(int offset, int index, int size)
+ public void DestroyStruct(int offset, int index)
{
if (index == 0)
{
@@ -138,7 +191,7 @@ public void DestroyStruct(int offset, int index, int size)
else
{
Marshal.DestroyStructure(
- _memory.Increment(offset + size * index),
+ _memory.Increment(offset + GetStructSize(typeof(T)) * index),
typeof(T)
);
}
@@ -146,7 +199,7 @@ public void DestroyStruct(int offset, int index, int size)
public void Fill(int offset, int length, byte value)
{
- Win32.RtlFillMemory(
+ ProcessHacker.Native.Api.Win32.RtlFillMemory(
_memory.Increment(offset),
length.ToIntPtr(),
value
@@ -213,9 +266,12 @@ public int ReadInt32(int offset)
/// The offset at which to begin reading.
/// The index at which to begin reading, after the offset is added.
/// The integer.
- public unsafe int ReadInt32(int offset, int index)
+ public int ReadInt32(int offset, int index)
{
- return ((int*)((byte*)this._memory + offset))[index];
+ unsafe
+ {
+ return ((int*)((byte*)_memory + offset))[index];
+ }
}
public int[] ReadInt32Array(int offset, int count)
@@ -232,14 +288,17 @@ public IntPtr ReadIntPtr(int offset)
return this.ReadIntPtr(offset, 0);
}
- public unsafe IntPtr ReadIntPtr(int offset, int index)
+ public IntPtr ReadIntPtr(int offset, int index)
{
- return ((IntPtr*)((byte*)this._memory + offset))[index];
+ unsafe
+ {
+ return ((IntPtr*)((byte*)_memory + offset))[index];
+ }
}
public void ReadMemory(IntPtr buffer, int destOffset, int srcOffset, int length)
{
- Win32.RtlMoveMemory(
+ ProcessHacker.Native.Api.Win32.RtlMoveMemory(
buffer.Increment(destOffset),
_memory.Increment(srcOffset),
length.ToIntPtr()
@@ -262,14 +321,36 @@ public uint ReadUInt32(int offset)
/// The offset at which to begin reading.
/// The index at which to begin reading, after the offset is added.
/// The integer.
- public unsafe uint ReadUInt32(int offset, int index)
+ public uint ReadUInt32(int offset, int index)
{
- return ((uint*)((byte*)this._memory + offset))[index];
+ unsafe
+ {
+ return ((uint*)((byte*)_memory + offset))[index];
+ }
}
- public T ReadStruct() where T : struct
+ ///
+ /// Creates a struct from the memory allocation.
+ ///
+ /// The type of the struct.
+ /// The new struct.
+ public T ReadStruct()
+ where T : struct
{
- return (T)Marshal.PtrToStructure(_memory, typeof(T));
+ return this.ReadStruct(0);
+ }
+
+ ///
+ /// Creates a struct from the memory allocation.
+ ///
+ /// The type of the struct.
+ /// The index at which to begin reading to the struct. This is multiplied by
+ /// the size of the struct.
+ /// The new struct.
+ public T ReadStruct(int index)
+ where T : struct
+ {
+ return this.ReadStruct(0, index);
}
///
@@ -277,18 +358,23 @@ public T ReadStruct() where T : struct
///
/// The type of the struct.
/// The offset to add before reading.
- ///
/// The index at which to begin reading to the struct. This is multiplied by
/// the size of the struct.
/// The new struct.
- public T ReadStruct(int offset, int size, int index) where T : struct
+ public T ReadStruct(int offset, int index)
+ where T : struct
{
if (index == 0)
{
return (T)Marshal.PtrToStructure(_memory.Increment(offset), typeof(T));
}
-
- return (T)Marshal.PtrToStructure(this._memory.Increment(offset + size * index), typeof(T));
+ else
+ {
+ return (T)Marshal.PtrToStructure(
+ _memory.Increment(offset + GetStructSize(typeof(T)) * index),
+ typeof(T)
+ );
+ }
}
public string ReadUnicodeString(int offset)
@@ -306,9 +392,12 @@ public string ReadUnicodeString(int offset, int length)
///
/// The offset at which to write.
/// The value of the byte.
- public unsafe void WriteByte(int offset, byte b)
+ public void WriteByte(int offset, byte b)
{
- *((byte*)this._memory + offset) = b;
+ unsafe
+ {
+ *((byte*)_memory + offset) = b;
+ }
}
public void WriteBytes(int offset, byte[] b)
@@ -316,41 +405,53 @@ public void WriteBytes(int offset, byte[] b)
Marshal.Copy(b, 0, _memory.Increment(offset), b.Length);
}
- public unsafe void WriteInt16(int offset, short i)
+ public void WriteInt16(int offset, short i)
{
- *(short*)((byte*)this._memory + offset) = i;
+ unsafe
+ {
+ *(short*)((byte*)_memory + offset) = i;
+ }
}
- public unsafe void WriteInt32(int offset, int i)
+ public void WriteInt32(int offset, int i)
{
- *(int*)((byte*)this._memory + offset) = i;
+ unsafe
+ {
+ *(int*)((byte*)_memory + offset) = i;
+ }
}
- public unsafe void WriteIntPtr(int offset, IntPtr i)
+ public void WriteIntPtr(int offset, IntPtr i)
{
- *(IntPtr*)((byte*)this._memory + offset) = i;
+ unsafe
+ {
+ *(IntPtr*)((byte*)_memory + offset) = i;
+ }
}
public void WriteMemory(int offset, IntPtr buffer, int length)
{
- Win32.RtlMoveMemory(
+ ProcessHacker.Native.Api.Win32.RtlMoveMemory(
_memory.Increment(offset),
buffer,
length.ToIntPtr()
);
}
- public void WriteStruct(T s) where T : struct
+ public void WriteStruct(T s)
+ where T : struct
{
- Marshal.StructureToPtr(s, _memory, false);
+ this.WriteStruct(0, s);
}
- public void WriteStruct(int index, int size, T s) where T : struct
+ public void WriteStruct(int index, T s)
+ where T : struct
{
- this.WriteStruct(0, size, index, s);
+ this.WriteStruct(0, index, s);
}
- public void WriteStruct(int offset, int size, int index, T s) where T : struct
+ public void WriteStruct(int offset, int index, T s)
+ where T : struct
{
if (index == 0)
{
@@ -360,7 +461,7 @@ public void WriteStruct(int offset, int size, int index, T s) where T : struc
{
Marshal.StructureToPtr(
s,
- _memory.Increment(offset + size * index),
+ _memory.Increment(offset + GetStructSize(typeof(T)) * index),
false
);
}
@@ -371,17 +472,20 @@ public void WriteStruct(int offset, int size, int index, T s) where T : struc
///
/// The offset to add.
/// The string to write.
- public unsafe void WriteUnicodeString(int offset, string s)
+ public void WriteUnicodeString(int offset, string s)
{
- fixed (char* ptr = s)
+ unsafe
{
- this.WriteMemory(offset, (IntPtr)ptr, s.Length * 2);
+ fixed (char* ptr = s)
+ {
+ this.WriteMemory(offset, (IntPtr)ptr, s.Length * 2);
+ }
}
}
public void Zero(int offset, int length)
{
- Win32.RtlZeroMemory(
+ ProcessHacker.Native.Api.Win32.RtlZeroMemory(
_memory.Increment(offset),
length.ToIntPtr()
);
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegionStream.cs b/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegionStream.cs
index e4674ecbc..103fc20fe 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegionStream.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/MemoryRegionStream.cs
@@ -28,8 +28,8 @@ namespace ProcessHacker.Native
{
public class MemoryRegionStream : Stream
{
- private readonly MemoryRegion _memory;
- private long _position;
+ private MemoryRegion _memory;
+ private long _position = 0;
public MemoryRegionStream(MemoryRegion memory)
{
@@ -86,18 +86,12 @@ public override int ReadByte()
public override long Seek(long offset, SeekOrigin origin)
{
- switch (origin)
- {
- case SeekOrigin.Begin:
- this._position = offset;
- break;
- case SeekOrigin.Current:
- this._position += offset;
- break;
- case SeekOrigin.End:
- this._position = this._memory.Size + offset;
- break;
- }
+ if (origin == SeekOrigin.Begin)
+ _position = offset;
+ else if (origin == SeekOrigin.Current)
+ _position += offset;
+ else if (origin == SeekOrigin.End)
+ _position = _memory.Size + offset;
return _position;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs b/1.x/trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs
index aeb6f5439..73d2eb040 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/PebMemoryAlloc.cs
@@ -33,9 +33,11 @@ public sealed class PebMemoryAlloc : MemoryAlloc
{
public PebMemoryAlloc(int size)
{
+ NtStatus status;
IntPtr block;
- Win32.RtlAllocateFromPeb(size, out block).ThrowIf();
+ if ((status = Win32.RtlAllocateFromPeb(size, out block)) >= NtStatus.Error)
+ Win32.Throw(status);
this.Memory = block;
this.Size = size;
@@ -43,7 +45,10 @@ public PebMemoryAlloc(int size)
protected override void Free()
{
- Win32.RtlFreeToPeb(this, this.Size).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.RtlFreeToPeb(this, this.Size)) >= NtStatus.Error)
+ Win32.Throw(status);
}
[EditorBrowsable(EditorBrowsableState.Never)]
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPages.cs b/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPages.cs
index 5090620f1..1da7fbca6 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPages.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPages.cs
@@ -10,9 +10,9 @@ namespace ProcessHacker.Native.Memory
///
public sealed class PhysicalPages : BaseObject
{
- private readonly ProcessHandle _processHandle;
- private readonly int _count;
- private readonly IntPtr[] _pfnArray;
+ private ProcessHandle _processHandle;
+ private int _count;
+ private IntPtr[] _pfnArray;
///
/// Allocates physical pages.
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPagesMapping.cs b/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPagesMapping.cs
index 78e7f5962..ee1d5c134 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPagesMapping.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/PhysicalPagesMapping.cs
@@ -1,10 +1,11 @@
using System;
+using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Memory
{
public sealed class PhysicalPagesMapping : MemoryAlloc
{
- private readonly PhysicalPages _physicalPages;
+ private PhysicalPages _physicalPages;
internal PhysicalPagesMapping(PhysicalPages physicalPages, IntPtr baseAddress)
{
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/PinnedObject.cs b/1.x/trunk/ProcessHacker.Native/Memory/PinnedObject.cs
index f3c1f96dd..c1c675c22 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/PinnedObject.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/PinnedObject.cs
@@ -1,11 +1,14 @@
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Text;
+using ProcessHacker.Common.Objects;
namespace ProcessHacker.Native
{
- public sealed class PinnedObject : MemoryRegion
+ public sealed class PinnedObject : BaseObject
{
- private readonly T _object;
+ private T _object;
private GCHandle _handle;
public PinnedObject(T obj)
@@ -14,7 +17,7 @@ public PinnedObject(T obj)
_handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
}
- protected override void Free()
+ protected override void DisposeObject(bool disposing)
{
_handle.Free();
}
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/Section.cs b/1.x/trunk/ProcessHacker.Native/Memory/Section.cs
index 9c68d63ff..7710ce9ce 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/Section.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/Section.cs
@@ -9,7 +9,7 @@ namespace ProcessHacker.Native
///
public sealed class Section : NativeObject
{
- private readonly MemoryProtection _originalProtection = MemoryProtection.ReadWrite;
+ private MemoryProtection _originalProtection = MemoryProtection.ReadWrite;
///
/// Opens an existing section.
@@ -64,7 +64,7 @@ public Section(string name, FileHandle fileHandle, bool image, MemoryProtection
name,
ObjectFlags.OpenIf,
null,
- fileHandle.FileSize,
+ fileHandle.GetSize(),
image ? SectionAttributes.Image : SectionAttributes.Commit,
protection,
fileHandle
diff --git a/1.x/trunk/ProcessHacker.Native/Memory/SectionView.cs b/1.x/trunk/ProcessHacker.Native/Memory/SectionView.cs
index 1e67595e9..232feba5d 100644
--- a/1.x/trunk/ProcessHacker.Native/Memory/SectionView.cs
+++ b/1.x/trunk/ProcessHacker.Native/Memory/SectionView.cs
@@ -40,7 +40,10 @@ internal SectionView(IntPtr baseAddress, IntPtr commitSize)
protected override void Free()
{
- Win32.NtUnmapViewOfSection(ProcessHandle.Current, this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtUnmapViewOfSection(ProcessHandle.Current, this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -62,8 +65,8 @@ public bool IsSameFile(SectionView mappedAsFile)
{
if ((uint)Win32.NtAreMappedFilesTheSame(this, mappedAsFile) == this.Memory.ToUInt32())
return true;
-
- return false;
+ else
+ return false;
}
[EditorBrowsable(EditorBrowsableState.Never)]
diff --git a/1.x/trunk/ProcessHacker.Native/Mfs/Exceptions.cs b/1.x/trunk/ProcessHacker.Native/Mfs/Exceptions.cs
index efd54e387..cc14a02b7 100644
--- a/1.x/trunk/ProcessHacker.Native/Mfs/Exceptions.cs
+++ b/1.x/trunk/ProcessHacker.Native/Mfs/Exceptions.cs
@@ -1,11 +1,13 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Native.Mfs
{
- [Serializable]
public class MfsException : Exception
{
public MfsException()
+ : base()
{ }
public MfsException(string message)
@@ -17,7 +19,6 @@ public MfsException(string message, Exception innerException)
{ }
}
- [Serializable]
public class MfsInvalidFileSystemException : MfsException
{
public MfsInvalidFileSystemException()
@@ -32,8 +33,7 @@ public MfsInvalidFileSystemException(string message, Exception innerException)
: base(message, innerException)
{ }
}
-
- [Serializable]
+
public class MfsInvalidOperationException : MfsException
{
public MfsInvalidOperationException()
diff --git a/1.x/trunk/ProcessHacker.Native/Mfs/Internal.cs b/1.x/trunk/ProcessHacker.Native/Mfs/Internal.cs
index 00e6c865b..0ce96a5aa 100644
--- a/1.x/trunk/ProcessHacker.Native/Mfs/Internal.cs
+++ b/1.x/trunk/ProcessHacker.Native/Mfs/Internal.cs
@@ -98,13 +98,6 @@ internal struct MfsBlockHeader
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal unsafe struct MfsObjectHeader
{
- public static readonly int SizeOf;
-
- static MfsObjectHeader()
- {
- SizeOf = Marshal.SizeOf(typeof(MfsObjectHeader));
- }
-
public MfsCellId Flink;
public MfsCellId Blink;
public MfsCellId Parent;
@@ -118,11 +111,11 @@ static MfsObjectHeader()
public MfsCellId LastData;
public int NameLength;
- public fixed char Name [32];
+ public fixed char Name[32];
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
- internal struct MfsDataCell
+ internal unsafe struct MfsDataCell
{
public static readonly int DataOffset = Marshal.OffsetOf(typeof(MfsDataCell), "Data").ToInt32();
diff --git a/1.x/trunk/ProcessHacker.Native/Mfs/MemoryDataWriteStream.cs b/1.x/trunk/ProcessHacker.Native/Mfs/MemoryDataWriteStream.cs
index 6569cd7f9..da9e844ff 100644
--- a/1.x/trunk/ProcessHacker.Native/Mfs/MemoryDataWriteStream.cs
+++ b/1.x/trunk/ProcessHacker.Native/Mfs/MemoryDataWriteStream.cs
@@ -21,15 +21,17 @@
*/
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Text;
using ProcessHacker.Common;
namespace ProcessHacker.Native.Mfs
{
public class MemoryDataWriteStream : Stream
{
- private readonly MemoryObject _obj;
- private readonly byte[] _buffer;
+ private MemoryObject _obj;
+ private byte[] _buffer;
private int _bufferLength;
internal MemoryDataWriteStream(MemoryObject obj, int bufferSize)
diff --git a/1.x/trunk/ProcessHacker.Native/Mfs/MemoryFileSystem.cs b/1.x/trunk/ProcessHacker.Native/Mfs/MemoryFileSystem.cs
index fd352806e..477ff087b 100644
--- a/1.x/trunk/ProcessHacker.Native/Mfs/MemoryFileSystem.cs
+++ b/1.x/trunk/ProcessHacker.Native/Mfs/MemoryFileSystem.cs
@@ -53,23 +53,26 @@ public void ResetObject()
}
}
- private readonly bool _readOnly;
- private readonly MemoryProtection _protection;
- private readonly Section _section;
+ private bool _readOnly;
+ private MemoryProtection _protection;
+ private Section _section;
private MfsFsHeader* _header;
- private readonly int _blockSize;
- private readonly int _blockMask;
- private readonly int _cellSize;
- private readonly int _cellCount;
- private readonly int _dataCellDataMaxLength;
-
- private readonly MfsCellId _rootObjectCellId = new MfsCellId(0, 1);
- private readonly MemoryObject _rootObjectMo;
-
- private readonly FreeList _vdFreeList = new FreeList(16);
- private readonly Dictionary _views = new Dictionary();
- private readonly Dictionary _views2 = new Dictionary();
+ private int _blockSize;
+ private int _blockMask;
+ private int _cellSize;
+ private int _cellCount;
+ private int _dataCellDataMaxLength;
+
+ private MfsCellId _rootObjectCellId = new MfsCellId(0, 1);
+ private MfsObjectHeader* _rootObject;
+ private MemoryObject _rootObjectMo;
+
+ private FreeList _vdFreeList = new FreeList(16);
+ private Dictionary _views =
+ new Dictionary();
+ private Dictionary _views2 =
+ new Dictionary();
private ViewDescriptor _cachedLastBlockView;
@@ -106,7 +109,7 @@ public MemoryFileSystem(string fileName, MfsOpenMode mode, bool readOnly, MfsPar
break;
}
- using (FileHandle fhandle = FileHandle.CreateWin32(
+ using (var fhandle = FileHandle.CreateWin32(
fileName,
FileAccess.GenericRead | (!readOnly ? FileAccess.GenericWrite : 0),
FileShareMode.Read,
@@ -118,42 +121,46 @@ public MemoryFileSystem(string fileName, MfsOpenMode mode, bool readOnly, MfsPar
_readOnly = readOnly;
_protection = !readOnly ? MemoryProtection.ReadWrite : MemoryProtection.ReadOnly;
- if (fhandle.FileSize == 0)
+ if (fhandle.GetSize() == 0)
{
if (readOnly)
{
throw new MfsInvalidFileSystemException();
}
-
- // File is too small. Make it 1 byte large and we'll deal with it soon.
- fhandle.SetEnd(1);
+ else
+ {
+ // File is too small. Make it 1 byte large and we'll deal with it
+ // soon.
+ fhandle.SetEnd(1);
+ }
}
_section = new Section(fhandle, _protection);
_blockSize = MfsBlockSizeBase; // fake block size to begin with; we'll fix it up later.
- if (fhandle.FileSize < _blockSize)
+ if (fhandle.GetSize() < _blockSize)
{
if (readOnly)
{
throw new MfsInvalidFileSystemException();
}
-
- // We're creating a new file system. We need the correct block size now.
- if (createParams != null)
- this._blockSize = createParams.BlockSize;
else
- this._blockSize = MfsDefaultBlockSize;
+ {
+ // We're creating a new file system. We need the correct block size
+ // now.
+ if (createParams != null)
+ _blockSize = createParams.BlockSize;
+ else
+ _blockSize = MfsDefaultBlockSize;
- this._section.Extend(this._blockSize);
+ _section.Extend(_blockSize);
- using (SectionView view = this._section.MapView(0, this._blockSize, this._protection))
- {
- this.InitializeFs((MfsFsHeader*)view.Memory, createParams);
- }
+ using (var view = _section.MapView(0, _blockSize, _protection))
+ this.InitializeFs((MfsFsHeader*)view.Memory, createParams);
- justCreated = true;
+ justCreated = true;
+ }
}
_header = (MfsFsHeader*)this.ReferenceBlock(0);
@@ -189,6 +196,7 @@ public MemoryFileSystem(string fileName, MfsOpenMode mode, bool readOnly, MfsPar
_header = (MfsFsHeader*)this.ReferenceBlock(0);
// Set up the root object.
+ _rootObject = (MfsObjectHeader*)((byte*)_header + _cellSize);
_rootObjectMo = new MemoryObject(this, _rootObjectCellId, true);
if (_header->NextFreeBlock != 1 && !readOnly)
@@ -203,16 +211,15 @@ public MemoryFileSystem(string fileName, MfsOpenMode mode, bool readOnly, MfsPar
protected override void DisposeObject(bool disposing)
{
- foreach (ViewDescriptor vd in _views.Values)
+ foreach (var vd in _views.Values)
vd.View.Dispose(disposing);
if (_rootObjectMo != null)
_rootObjectMo.Dispose();
-
if (_section != null)
_section.Dispose();
-
_header = null;
+ _rootObject = null;
}
public int BlockSize
@@ -627,7 +634,7 @@ private void ValidateFsParameters(int blockSize, int cellSize)
throw new ArgumentException("The block size must be a multiple of the cell size.");
if ((blockSize / cellSize) < 2)
throw new ArgumentException("There must be a least 2 cells in each block.");
- if (cellSize < MfsObjectHeader.SizeOf)
+ if (cellSize < Marshal.SizeOf(typeof(MfsObjectHeader)))
throw new ArgumentException("The cell size is too small.");
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Mfs/MemoryObject.cs b/1.x/trunk/ProcessHacker.Native/Mfs/MemoryObject.cs
index f3918503b..a057f4511 100644
--- a/1.x/trunk/ProcessHacker.Native/Mfs/MemoryObject.cs
+++ b/1.x/trunk/ProcessHacker.Native/Mfs/MemoryObject.cs
@@ -30,9 +30,9 @@ public unsafe sealed class MemoryObject : BaseObject
{
public delegate bool EnumChildrenDelegate(MemoryObject mo);
- private readonly bool _fsInternal;
- private readonly MemoryFileSystem _fs;
- private readonly MfsCellId _cellId;
+ private bool _fsInternal;
+ private MemoryFileSystem _fs;
+ private MfsCellId _cellId;
private MfsObjectHeader* _obj;
private string _name;
@@ -80,7 +80,7 @@ public string Name
{
get
{
- if (string.IsNullOrEmpty(_name))
+ if (_name == null)
_name = _fs.GetObjectName(_obj);
return _name;
@@ -184,26 +184,23 @@ public MemoryObject GetChild(string name)
return null;
}
- public string[] ChildNames
+ public string[] GetChildNames()
{
- get
- {
- List names = new List();
+ List names = new List();
- this.EnumChildren(mo =>
+ this.EnumChildren((mo) =>
{
names.Add(mo.Name);
mo.Dispose();
return true;
});
- return names.ToArray();
- }
+ return names.ToArray();
}
- public MemoryObject Parent
+ public MemoryObject GetParent()
{
- get { return new MemoryObject(_fs, _obj->Parent); }
+ return new MemoryObject(_fs, _obj->Parent);
}
public MemoryDataWriteStream GetWriteStream()
diff --git a/1.x/trunk/ProcessHacker.Native/NativeBitmap.cs b/1.x/trunk/ProcessHacker.Native/NativeBitmap.cs
index 7bcdf6a0d..f0b5f4bff 100644
--- a/1.x/trunk/ProcessHacker.Native/NativeBitmap.cs
+++ b/1.x/trunk/ProcessHacker.Native/NativeBitmap.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Common;
using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
@@ -54,7 +56,7 @@ public int Length
}
private RtlBitmap _bitmap;
- private readonly MemoryAlloc _buffer;
+ private MemoryAlloc _buffer;
public NativeBitmap(int bits)
{
@@ -129,8 +131,9 @@ public BitmapRun[] FindClearRuns(int count)
public BitmapRun[] FindClearRuns(int count, bool locateLongest)
{
RtlBitmapRun[] runs = new RtlBitmapRun[count];
+ int numberOfRuns;
- int numberOfRuns = Win32.RtlFindClearRuns(ref this._bitmap, runs, count, locateLongest);
+ numberOfRuns = Win32.RtlFindClearRuns(ref _bitmap, runs, count, locateLongest);
BitmapRun[] returnRuns = new BitmapRun[numberOfRuns];
@@ -143,8 +146,9 @@ public BitmapRun[] FindClearRuns(int count, bool locateLongest)
public BitmapRun FindBackwardClearRun(int index)
{
int startingIndex;
+ int numberOfBits;
- int numberOfBits = Win32.RtlFindLastBackwardRunClear(ref this._bitmap, index, out startingIndex);
+ numberOfBits = Win32.RtlFindLastBackwardRunClear(ref _bitmap, index, out startingIndex);
return new BitmapRun(startingIndex, numberOfBits);
}
@@ -152,8 +156,9 @@ public BitmapRun FindBackwardClearRun(int index)
public BitmapRun FindFirstClearRun()
{
int startingIndex;
+ int numberOfBits;
- int numberOfBits = Win32.RtlFindFirstRunClear(ref this._bitmap, out startingIndex);
+ numberOfBits = Win32.RtlFindFirstRunClear(ref _bitmap, out startingIndex);
return new BitmapRun(startingIndex, numberOfBits);
}
@@ -161,8 +166,9 @@ public BitmapRun FindFirstClearRun()
public BitmapRun FindForwardClearRun(int index)
{
int startingIndex;
+ int numberOfBits;
- int numberOfBits = Win32.RtlFindNextForwardRunClear(ref this._bitmap, index, out startingIndex);
+ numberOfBits = Win32.RtlFindNextForwardRunClear(ref _bitmap, index, out startingIndex);
return new BitmapRun(startingIndex, numberOfBits);
}
@@ -170,8 +176,9 @@ public BitmapRun FindForwardClearRun(int index)
public BitmapRun FindLongestClearRun()
{
int startingIndex;
+ int numberOfBits;
- int numberOfBits = Win32.RtlFindLongestRunClear(ref this._bitmap, out startingIndex);
+ numberOfBits = Win32.RtlFindLongestRunClear(ref _bitmap, out startingIndex);
return new BitmapRun(startingIndex, numberOfBits);
}
@@ -196,14 +203,14 @@ public int FindSetAndClear(int length, int hintIndex)
return Win32.RtlFindSetBitsAndClear(ref _bitmap, length, hintIndex);
}
- public int ClearCount
+ public int GetClearCount()
{
- get { return Win32.RtlNumberOfClearBits(ref _bitmap); }
+ return Win32.RtlNumberOfClearBits(ref _bitmap);
}
- public int SetCount
+ public int GetSetCount()
{
- get { return Win32.RtlNumberOfSetBits(ref _bitmap); }
+ return Win32.RtlNumberOfSetBits(ref _bitmap);
}
public void Set()
diff --git a/1.x/trunk/ProcessHacker.Native/NativeLibrary.cs b/1.x/trunk/ProcessHacker.Native/NativeLibrary.cs
deleted file mode 100644
index 1610003fc..000000000
--- a/1.x/trunk/ProcessHacker.Native/NativeLibrary.cs
+++ /dev/null
@@ -1,184 +0,0 @@
-namespace System
-{
- using Runtime.InteropServices;
- using ProcessHacker.Native;
- using ProcessHacker.Native.Api;
- using ProcessHacker.Native.Objects;
-
- ///
- /// Utility class to wrap an unmanaged DLL and be responsible for freeing it.
- ///
- /// This is a managed wrapper over the native LoadLibrary, GetProcAddress, and FreeLibrary calls.
- public sealed class NativeLibrary : NativeHandle
- {
- ///
- /// LoadLibraryEx constructor to load a dll and be responsible for freeing it.
- ///
- /// full path name of dll to load
- ///
- /// Throws exceptions on failure. Most common failure would be file-not-found, or that the file is not a loadable image.
- public NativeLibrary(string dllName, LoadLibraryFlags flags)
- {
- UnicodeString str = new UnicodeString(dllName);
-
- IntPtr ptr;
-
- NtStatus result = Win32.LdrLoadDll(null, (int)flags, ref str, out ptr);
-
- if (result.IsError())
- {
- this.MarkAsInvalid();
- }
-
- str.Dispose();
- }
-
- ///
- /// Dynamically lookup a function in the dll via kernel32!GetProcAddress.
- ///
- /// raw name of the function in the export table.
- /// null if function is not found. Else a delegate to the unmanaged function.
- /// GetProcAddress results are valid as long as the dll is not yet unloaded. This
- /// is very very dangerous to use since you need to ensure that the dll is not unloaded
- /// until after you're done with any objects implemented by the dll. For example, if you
- /// get a delegate that then gets an IUnknown implemented by this dll,
- /// you can not dispose this library until that IUnknown is collected. Else, you may free
- /// the library and then the CLR may call release on that IUnknown and it will crash.
- public TDelegate GetUnmanagedFunction(string functionName) where TDelegate : class
- {
- using (AnsiString str = new AnsiString(functionName))
- {
- IntPtr functionPtr;
-
- NtStatus result = Win32.LdrGetProcedureAddress(this, str.Buffer, 0, out functionPtr);
-
- // Failure is a common case, especially for adaptive code.
- if (result.IsError())
- {
- //result.ReturnException().Log();
-
- return null;
- }
-
- Delegate function = Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(TDelegate));
-
- // Ideally, we'd just make the constraint on TDelegate be
- // System.Delegate, but compiler error CS0702 (constrained can't be System.Delegate)
- // prevents that. So we make the constraint system.object and do the cast from object-->TDelegate.
- object o = function;
-
- return (TDelegate)o;
- }
- }
-
- #region Disposable Members
-
- ///
- /// Call FreeLibrary on the unmanaged dll. All function pointers handed out from this class become invalid after this.
- ///
- /// This is very dangerous because it suddenly invalidate
- /// everything retrieved from this dll. This includes any functions
- /// handed out via GetProcAddress, and potentially any objects returned
- /// from those functions (which may have an implementation in the dll).
- ///
- protected override void Close()
- {
- Win32.LdrUnloadDll(this).ThrowIf();
- }
-
- #endregion
-
- public IntPtr GetProcedure(string procedureName)
- {
- AnsiString str = new AnsiString(procedureName);
- {
- IntPtr functionPtr = IntPtr.Zero;
-
- NtStatus result = Win32.LdrGetProcedureAddress(this, functionPtr, 0, out functionPtr);
-
- return functionPtr;
- }
- }
-
- public IntPtr GetProcedure(int procedureNumber)
- {
- IntPtr functionPtr;
-
- NtStatus result = Win32.LdrGetProcedureAddress(this, IntPtr.Zero, procedureNumber, out functionPtr);
-
- return functionPtr;
- }
-
- #region Static Methods
-
- public static IntPtr GetProcedure(string dllName, string procedureName)
- {
- return GetProcedure(GetModuleHandle(dllName), procedureName);
- }
-
- public static IntPtr GetProcedure(IntPtr dllHandle, string procedureName)
- {
- IntPtr handle;
-
- using (AnsiString str = new AnsiString(procedureName))
- {
- Win32.LdrGetProcedureAddress(dllHandle, str.Buffer, 0, out handle).ThrowIf();
- }
-
- return handle;
- }
-
- public static IntPtr GetModuleHandle(string dllName)
- {
- IntPtr handle;
-
- UnicodeString str = new UnicodeString(dllName);
- {
- Win32.LdrGetDllHandle(null, 0, ref str, out handle).ThrowIf();
- }
-
- return handle;
- }
-
- #endregion
- }
-
- [Flags] //TODO: move to enum file
- public enum LoadLibraryFlags
- {
- None = 0,
-
- ///
- /// If this value is used, and the executable module is a DLL, the system does not call DllMain for process and thread initialization and termination. Also, the system does not load additional executable modules that are referenced by the specified module. Do not use this value; it is provided only for backwards compatibility. If you are planning to access only data or resources in the DLL, use LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE or LOAD_LIBRARY_AS_IMAGE_RESOURCE or both. Otherwise, load the library as a DLL or executable module using the LoadLibrary function.
- ///
- DontResolveDllReferences = 0x00000001,
-
- ///
- /// If this value is used, the system maps the file into the calling process's virtual address space as if it were a data file. Nothing is done to execute or prepare to execute the mapped file. Therefore, you cannot call functions like GetModuleFileName, GetModuleHandle or GetProcAddress with this DLL. Using this value causes writes to read-only memory to raise an access violation. Use this flag when you want to load a DLL only to extract messages or resources from it. This value can be used with LOAD_LIBRARY_AS_IMAGE_RESOURCE.
- ///
- LOAD_LIBRARY_AS_DATAFILE = 0x00000002,
-
- ///
- /// If this value is used and lpFileName specifies an absolute path, the system uses the alternate file search strategy discussed in the Remarks section to find associated executable modules that the specified module causes to be loaded. If this value is used and lpFileName specifies a relative path, the behavior is undefined. If this value is not used, or if lpFileName does not specify a path, the system uses the standard search strategy discussed in the Remarks section to find associated executable modules that the specified module causes to be loaded.
- ///
- LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008,
-
- ///
- /// If this value is used, the system does not check AppLocker rules or apply Software Restriction Policies for the DLL. This action applies only to the DLL being loaded and not to its dependents. This value is recommended for use in setup programs that must run extracted DLLs during installation.
- ///
- LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010,
-
- ///
- /// If this value is used, the system maps the file into the process's virtual address space as an image file. However, the loader does not load the static imports or perform the other usual initialization steps. Use this flag when you want to load a DLL only to extract messages or resources from it. Unless the application depends on the image layout, this value should be used with either LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE or LOAD_LIBRARY_AS_DATAFILE. For more information, see the Remarks section.
- ///
- LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020,
-
- ///
- /// Similar to LOAD_LIBRARY_AS_DATAFILE, except that the DLL file on the disk is opened for exclusive write access. Therefore, other processes cannot open the DLL file for write access while it is in use. However, the DLL can still be opened by other processes. This value can be used with LOAD_LIBRARY_AS_IMAGE_RESOURCE. For more information, see Remarks.
- ///
- LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040,
-
-
- LOAD_LIBRARY_REQUIRE_SIGNED_TARGET = 0x00000080
- }
-}
diff --git a/1.x/trunk/ProcessHacker.Native/NativeUtils.cs b/1.x/trunk/ProcessHacker.Native/NativeUtils.cs
index bd67e9ed0..76f75c478 100644
--- a/1.x/trunk/ProcessHacker.Native/NativeUtils.cs
+++ b/1.x/trunk/ProcessHacker.Native/NativeUtils.cs
@@ -1,6 +1,7 @@
using System;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Security;
namespace ProcessHacker.Native
@@ -41,23 +42,34 @@ public unsafe static void CopyProcessParameters(
ref StartupInfo startupInfo
)
{
+ UnicodeString imagePathNameStr;
+ UnicodeString dllPathStr;
+ UnicodeString currentDirectoryStr;
+ UnicodeString commandLineStr;
+ UnicodeString windowTitleStr;
+ UnicodeString desktopInfoStr;
+ UnicodeString shellInfoStr;
+ UnicodeString runtimeInfoStr;
+
// Create the unicode strings.
- UnicodeString imagePathNameStr = new UnicodeString(imagePathName);
- UnicodeString dllPathStr = new UnicodeString(dllPath);
- UnicodeString currentDirectoryStr = new UnicodeString(currentDirectory);
- UnicodeString commandLineStr = new UnicodeString(commandLine);
- UnicodeString windowTitleStr = new UnicodeString(windowTitle);
- UnicodeString desktopInfoStr = new UnicodeString(desktopInfo);
- UnicodeString shellInfoStr = new UnicodeString(shellInfo);
- UnicodeString runtimeInfoStr = new UnicodeString(runtimeInfo);
+ imagePathNameStr = new UnicodeString(imagePathName);
+ dllPathStr = new UnicodeString(dllPath);
+ currentDirectoryStr = new UnicodeString(currentDirectory);
+ commandLineStr = new UnicodeString(commandLine);
+ windowTitleStr = new UnicodeString(windowTitle);
+ desktopInfoStr = new UnicodeString(desktopInfo);
+ shellInfoStr = new UnicodeString(shellInfo);
+ runtimeInfoStr = new UnicodeString(runtimeInfo);
try
{
+ NtStatus status;
IntPtr processParameters;
// Create the process parameter block.
- Win32.RtlCreateProcessParameters(
+
+ status = Win32.RtlCreateProcessParameters(
out processParameters,
ref imagePathNameStr,
ref dllPathStr,
@@ -68,15 +80,21 @@ ref StartupInfo startupInfo
ref desktopInfoStr,
ref shellInfoStr,
ref runtimeInfoStr
- ).ThrowIf();
+ );
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
try
{
// Allocate a new memory region in the remote process for
// the environment block and copy it over.
- int environmentLength = environment.Length;
- IntPtr newEnvironment = processHandle.AllocateMemory(
+ int environmentLength;
+ IntPtr newEnvironment;
+
+ environmentLength = environment.GetLength();
+ newEnvironment = processHandle.AllocateMemory(
environmentLength,
MemoryProtection.ReadWrite
);
@@ -113,9 +131,10 @@ ref runtimeInfoStr
// Allocate a new memory region in the remote process for
// the process parameters.
+ IntPtr newProcessParameters;
IntPtr regionSize = paramsStruct->Length.ToIntPtr();
- IntPtr newProcessParameters = processHandle.AllocateMemory(
+ newProcessParameters = processHandle.AllocateMemory(
IntPtr.Zero,
ref regionSize,
MemoryFlags.Commit,
@@ -161,23 +180,25 @@ public static string FormatNativeKeyName(string nativeKeyName)
if (nativeKeyName.StartsWith(hkcrString, StringComparison.OrdinalIgnoreCase))
return "HKCR" + nativeKeyName.Substring(hkcrString.Length);
- if (nativeKeyName.StartsWith(hklmString, StringComparison.OrdinalIgnoreCase))
+ else if (nativeKeyName.StartsWith(hklmString, StringComparison.OrdinalIgnoreCase))
return "HKLM" + nativeKeyName.Substring(hklmString.Length);
- if (nativeKeyName.StartsWith(hkcucrString, StringComparison.OrdinalIgnoreCase))
+ else if (nativeKeyName.StartsWith(hkcucrString, StringComparison.OrdinalIgnoreCase))
return @"HKCU\Software\Classes" + nativeKeyName.Substring(hkcucrString.Length);
- if (nativeKeyName.StartsWith(hkcuString, StringComparison.OrdinalIgnoreCase))
+ else if (nativeKeyName.StartsWith(hkcuString, StringComparison.OrdinalIgnoreCase))
return "HKCU" + nativeKeyName.Substring(hkcuString.Length);
- if (nativeKeyName.StartsWith(hkuString, StringComparison.OrdinalIgnoreCase))
+ else if (nativeKeyName.StartsWith(hkuString, StringComparison.OrdinalIgnoreCase))
return "HKU" + nativeKeyName.Substring(hkuString.Length);
- return nativeKeyName;
+ else
+ return nativeKeyName;
}
public static string GetMessage(IntPtr dllHandle, int messageTableId, int messageLanguageId, int messageId)
{
+ NtStatus status;
IntPtr messageEntry;
string message;
- NtStatus status = Win32.RtlFindMessage(
+ status = Win32.RtlFindMessage(
dllHandle,
messageTableId,
messageLanguageId,
@@ -188,8 +209,8 @@ out messageEntry
if (status.IsError())
return null;
- MemoryRegion region = new MemoryRegion(messageEntry);
- MessageResourceEntry entry = region.ReadStruct();
+ var region = new MemoryRegion(messageEntry);
+ var entry = region.ReadStruct();
// Read the message, depending on format.
if ((entry.Flags & MessageResourceFlags.Unicode) == MessageResourceFlags.Unicode)
@@ -217,7 +238,7 @@ public static bool ObjectExists(string name)
try
{
- using (var dhandle = new DirectoryHandle(dirPart, DirectoryAccess.Query))
+ using (var dhandle = new DirectoryHandle(dirPart, ProcessHacker.Native.Security.DirectoryAccess.Query))
{
var objects = dhandle.GetObjects();
@@ -242,7 +263,7 @@ public static NativeHandle OpenObject(int access, string name, ObjectFlags objec
try
{
- return null;// new NativeHandle(KProcessHacker.Instance.KphOpenNamedObject(access, oa).ToIntPtr(), true);
+ return new NativeHandle(KProcessHacker.Instance.KphOpenNamedObject(access, oa).ToIntPtr(), true);
}
finally
{
diff --git a/1.x/trunk/ProcessHacker.Native/OSVersion.cs b/1.x/trunk/ProcessHacker.Native/OSVersion.cs
index 83e4fcc7d..a07d5728f 100644
--- a/1.x/trunk/ProcessHacker.Native/OSVersion.cs
+++ b/1.x/trunk/ProcessHacker.Native/OSVersion.cs
@@ -25,7 +25,7 @@
namespace ProcessHacker.Native
{
- public enum OSArch
+ public enum OSArch : int
{
Unknown,
I386,
@@ -59,11 +59,6 @@ public enum WindowsVersion
///
Seven = 61,
- ///
- /// Windows 8.
- ///
- Eight = 62,
-
///
/// An unknown version of Windows.
///
@@ -72,31 +67,31 @@ public enum WindowsVersion
public static class OSVersion
{
- private static readonly int _bits = IntPtr.Size * 8;
- private static readonly OSArch _arch = IntPtr.Size == 4 ? OSArch.I386 : OSArch.Amd64;
- private static readonly string _versionString;
- private static readonly WindowsVersion _windowsVersion;
-
- private static readonly ProcessAccess _minProcessQueryInfoAccess = ProcessAccess.QueryInformation;
- private static readonly ThreadAccess _minThreadQueryInfoAccess = ThreadAccess.QueryInformation;
- private static readonly ThreadAccess _minThreadSetInfoAccess = ThreadAccess.SetInformation;
-
- private static readonly bool _hasCycleTime;
- private static readonly bool _hasExtendedTaskbar;
- private static readonly bool _hasIoPriority;
- private static readonly bool _hasPagePriority;
- private static readonly bool _hasProtectedProcesses;
- private static readonly bool _hasPsSuspendResumeProcess;
- private static readonly bool _hasQueryLimitedInformation;
- private static readonly bool _hasSetAccessToken;
- private static readonly bool _hasTaskDialogs;
- private static readonly bool _hasThemes;
- private static readonly bool _hasUac;
- private static readonly bool _hasWin32ImageFileName;
+ private static int _bits = IntPtr.Size * 8;
+ private static OSArch _arch = IntPtr.Size == 4 ? OSArch.I386 : OSArch.Amd64;
+ private static string _versionString;
+ private static WindowsVersion _windowsVersion;
+
+ private static ProcessAccess _minProcessQueryInfoAccess = ProcessAccess.QueryInformation;
+ private static ThreadAccess _minThreadQueryInfoAccess = ThreadAccess.QueryInformation;
+ private static ThreadAccess _minThreadSetInfoAccess = ThreadAccess.SetInformation;
+
+ private static bool _hasCycleTime = false;
+ private static bool _hasExtendedTaskbar = false;
+ private static bool _hasIoPriority = false;
+ private static bool _hasPagePriority = false;
+ private static bool _hasProtectedProcesses = false;
+ private static bool _hasPsSuspendResumeProcess = false;
+ private static bool _hasQueryLimitedInformation = false;
+ private static bool _hasSetAccessToken = false;
+ private static bool _hasTaskDialogs = false;
+ private static bool _hasThemes = false;
+ private static bool _hasUac = false;
+ private static bool _hasWin32ImageFileName = false;
static OSVersion()
{
- Version version = Environment.OSVersion.Version;
+ System.Version version = Environment.OSVersion.Version;
if (version.Major == 5 && version.Minor == 0)
_windowsVersion = WindowsVersion.TwoThousand;
@@ -107,9 +102,7 @@ static OSVersion()
else if (version.Major == 6 && version.Minor == 0)
_windowsVersion = WindowsVersion.Vista;
else if (version.Major == 6 && version.Minor == 1)
- _windowsVersion = WindowsVersion.Seven;
- else if (version.Major == 6 && version.Minor == 2)
- _windowsVersion = WindowsVersion.Eight;
+ _windowsVersion = WindowsVersion.Seven;
else
_windowsVersion = WindowsVersion.Unknown;
@@ -263,22 +256,22 @@ public static bool IsI386()
public static bool IsAbove(WindowsVersion version)
{
- return _windowsVersion > version;
+ return (int)_windowsVersion > (int)version;
}
public static bool IsAboveOrEqual(WindowsVersion version)
{
- return _windowsVersion >= version;
+ return (int)_windowsVersion >= (int)version;
}
public static bool IsBelowOrEqual(WindowsVersion version)
{
- return _windowsVersion <= version;
+ return (int)_windowsVersion <= (int)version;
}
public static bool IsBelow(WindowsVersion version)
{
- return _windowsVersion < version;
+ return (int)_windowsVersion < (int)version;
}
public static bool IsEqualTo(WindowsVersion version)
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs
index 2416e0e13..879022ff9 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/DebugObjectHandle.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -40,17 +42,19 @@ public static DebugObjectHandle Create(DebugObjectAccess access, string name, De
public static DebugObjectHandle Create(DebugObjectAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, DebugObjectFlags flags)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateDebugObject(
+ if ((status = Win32.NtCreateDebugObject(
out handle,
access,
ref oa,
flags
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -80,26 +84,31 @@ public DebugObjectHandle(ProcessHandle processHandle)
public void Continue(ClientId cid, NtStatus continueStatus)
{
- Win32.NtDebugContinue(
+ NtStatus status;
+
+ if ((status = Win32.NtDebugContinue(
this,
ref cid,
continueStatus
- ).ThrowIf();
+ )) > NtStatus.Error)
+ Win32.Throw(status);
}
public void SetFlags(DebugObjectFlags flags)
{
unsafe
{
+ NtStatus status;
int retLength;
- Win32.NtSetInformationDebugObject(
+ if ((status = Win32.NtSetInformationDebugObject(
this,
DebugObjectInformationClass.DebugObjectFlags,
new IntPtr(&flags),
sizeof(DebugObjectFlags),
out retLength
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
@@ -111,12 +120,13 @@ public IntPtr WaitForDebugEvent(bool alertable, long timeout, bool timeoutRelati
//NtStatus status;
//long realTimeout = timeoutRelative ? -timeout : timeout;
- //Win32.NtWaitForDebugEvent(
+ //if ((status = Win32.NtWaitForDebugEvent(
// this,
// alertable,
// ref realTimeout,
// IntPtr.Zero
- // ).ThrowIf();
+ // )) >= NtStatus.Error)
+ // Win32.ThrowLastError(status);
//return IntPtr.Zero;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/DesktopHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/DesktopHandle.cs
index 25a22dd99..9c95d819c 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/DesktopHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/DesktopHandle.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs
index 0bb2a5f87..b6ed60e0b 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/DirectoryHandle.cs
@@ -36,8 +36,8 @@ public class DirectoryHandle : NativeHandle
public struct ObjectEntry
{
- private readonly string _name;
- private readonly string _typeName;
+ private string _name;
+ private string _typeName;
public ObjectEntry(string name, string typeName)
{
@@ -56,12 +56,14 @@ public static DirectoryHandle Create(DirectoryAccess access, string name)
public static DirectoryHandle Create(DirectoryAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateDirectoryObject(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtCreateDirectoryObject(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -84,12 +86,21 @@ public DirectoryHandle(string name, DirectoryAccess access)
public DirectoryHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, DirectoryAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenDirectoryObject(out handle, access, ref oa).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ handle = KProcessHacker.Instance.KphOpenDirectoryObject(access, oa).ToIntPtr();
+ }
+ else
+ {
+ if ((status = Win32.NtOpenDirectoryObject(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
}
finally
{
@@ -122,7 +133,7 @@ out retLength
{
// Check if we have at least one entry. If not,
// we need to double the buffer size and try again.
- if (data.ReadStruct(0, ObjectDirectoryInformation.SizeOf, 0).Name.Buffer != IntPtr.Zero)
+ if (data.ReadStruct(0).Name.Buffer != IntPtr.Zero)
break;
if (data.Size > 16 * 1024 * 1024)
@@ -131,18 +142,19 @@ out retLength
data.ResizeNew(data.Size * 2);
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
int i = 0;
while (true)
{
- ObjectDirectoryInformation info = data.ReadStruct(0, ObjectDirectoryInformation.SizeOf, i);
+ ObjectDirectoryInformation info = data.ReadStruct(i);
if (info.Name.Buffer == IntPtr.Zero)
break;
- if (!callback(new ObjectEntry(info.Name.Text, info.TypeName.Text)))
+ if (!callback(new ObjectEntry(info.Name.Read(), info.TypeName.Read())))
return;
i++;
@@ -164,7 +176,7 @@ public ObjectEntry[] GetObjects()
{
var objects = new List();
- this.EnumObjects(obj =>
+ this.EnumObjects((obj) =>
{
objects.Add(obj);
return true;
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/DriverHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/DriverHandle.cs
index 2e63b5571..ffff7d53d 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/DriverHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/DriverHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Objects
@@ -37,7 +38,7 @@ public DriverHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDi
try
{
- this.Handle = IntPtr.Zero;// KProcessHacker.Instance.KphOpenDriver(oa).ToIntPtr();
+ this.Handle = KProcessHacker.Instance.KphOpenDriver(oa).ToIntPtr();
}
finally
{
@@ -45,63 +46,66 @@ public DriverHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDi
}
}
- public string DriverName
+ public DriverBasicInformation GetBasicInformation()
{
- get { return this.GetInformationUnicodeString(DriverInformationClass.DriverNameInformation); }
- }
-
- public string ServiceKeyName
- {
- get { return this.GetInformationUnicodeString(DriverInformationClass.DriverServiceKeyNameInformation); }
- }
-
- public unsafe DriverBasicInformation BasicInformation
- {
- get
+ unsafe
{
- DriverBasicInformation basicInfo = new DriverBasicInformation();
+ DriverBasicInformation basicInfo;
+ int retLength;
- //KProcessHacker.Instance.KphQueryInformationDriver(
- // this,
- // DriverInformationClass.DriverBasicInformation,
- // new IntPtr(&basicInfo),
- // DriverBasicInformation.SizeOf,
- // out retLength
- // );
+ KProcessHacker.Instance.KphQueryInformationDriver(
+ this,
+ DriverInformationClass.DriverBasicInformation,
+ new IntPtr(&basicInfo),
+ Marshal.SizeOf(typeof(DriverBasicInformation)),
+ out retLength
+ );
return basicInfo;
}
}
+ public string GetDriverName()
+ {
+ return this.GetInformationUnicodeString(DriverInformationClass.DriverNameInformation);
+ }
+
private string GetInformationUnicodeString(DriverInformationClass infoClass)
{
using (MemoryAlloc data = new MemoryAlloc(0x1000))
{
- //try
- //{
- // KProcessHacker.Instance.KphQueryInformationDriver(
- // this,
- // infoClass,
- // data,
- // data.Size,
- // out retLength
- // );
- //}
- //catch (WindowsException)
- //{
- // data.ResizeNew(retLength);
+ int retLength = 0;
+
+ try
+ {
+ KProcessHacker.Instance.KphQueryInformationDriver(
+ this,
+ infoClass,
+ data,
+ data.Size,
+ out retLength
+ );
+ }
+ catch (WindowsException)
+ {
+ data.ResizeNew(retLength);
- // KProcessHacker.Instance.KphQueryInformationDriver(
- // this,
- // infoClass,
- // data,
- // data.Size,
- // out retLength
- // );
- //}
+ KProcessHacker.Instance.KphQueryInformationDriver(
+ this,
+ infoClass,
+ data,
+ data.Size,
+ out retLength
+ );
+ }
- return data.ReadStruct().Text;
+ return data.ReadStruct().Read();
}
}
+
+ public string GetServiceKeyName()
+ {
+ return this.GetInformationUnicodeString(DriverInformationClass.DriverServiceKeyNameInformation);
+ }
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/EnlistmentHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/EnlistmentHandle.cs
index 6a95d8c23..69eb2042f 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/EnlistmentHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/EnlistmentHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -40,12 +41,13 @@ public static EnlistmentHandle Create(
IntPtr enlistmentKey
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateEnlistment(
+ if ((status = Win32.NtCreateEnlistment(
out handle,
access,
resourceManagerHandle,
@@ -54,7 +56,8 @@ IntPtr enlistmentKey
createOptions,
notificationMask,
enlistmentKey
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -82,18 +85,20 @@ public EnlistmentHandle(
EnlistmentAccess access
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenEnlistment(
+ if ((status = Win32.NtOpenEnlistment(
out handle,
access,
resourceManagerHandle,
ref guid,
ref oa
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -105,76 +110,108 @@ ref oa
public void Commit(long virtualClock)
{
- Win32.NtCommitEnlistment(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtCommitEnlistment(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void CommitComplete(long virtualClock)
{
- Win32.NtCommitComplete(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtCommitComplete(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
- public EnlistmentBasicInformation BasicInformation
+ public EnlistmentBasicInformation GetBasicInformation()
{
- get
- {
- EnlistmentBasicInformation basicInfo;
- int retLength;
-
- Win32.NtQueryInformationEnlistment(
- this,
- EnlistmentInformationClass.EnlistmentBasicInformation,
- out basicInfo,
- EnlistmentBasicInformation.SizeOf,
- out retLength
- ).ThrowIf();
-
- return basicInfo;
- }
+ NtStatus status;
+ EnlistmentBasicInformation basicInfo;
+ int retLength;
+
+ if ((status = Win32.NtQueryInformationEnlistment(
+ this,
+ EnlistmentInformationClass.EnlistmentBasicInformation,
+ out basicInfo,
+ Marshal.SizeOf(typeof(EnlistmentBasicInformation)),
+ out retLength
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return basicInfo;
}
public void Prepare(long virtualClock)
{
- Win32.NtPrepareEnlistment(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtPrepareEnlistment(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void PrepareComplete(long virtualClock)
{
- Win32.NtPrepareComplete(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtPrepareComplete(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void PrePrepare(long virtualClock)
{
- Win32.NtPrePrepareEnlistment(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtPrePrepareEnlistment(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void PrePrepareComplete(long virtualClock)
{
- Win32.NtPrePrepareComplete(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtPrePrepareComplete(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void ReadOnly(long virtualClock)
{
- Win32.NtReadOnlyEnlistment(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtReadOnlyEnlistment(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void Recover(IntPtr enlistmentKey)
{
- Win32.NtRecoverEnlistment(this, enlistmentKey).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRecoverEnlistment(this, enlistmentKey)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void RejectSinglePhase(long virtualClock)
{
- Win32.NtSinglePhaseReject(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtSinglePhaseReject(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void Rollback(long virtualClock)
{
- Win32.NtRollbackEnlistment(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRollbackEnlistment(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void RollbackComplete(long virtualClock)
{
- Win32.NtRollbackComplete(this, ref virtualClock).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRollbackComplete(this, ref virtualClock)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/EnvironmentBlock.cs b/1.x/trunk/ProcessHacker.Native/Objects/EnvironmentBlock.cs
index 68dc0a107..6c5434bfe 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/EnvironmentBlock.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/EnvironmentBlock.cs
@@ -1,5 +1,9 @@
using System;
+using System.Collections.Generic;
+using System.Text;
+using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
+using System.Runtime.InteropServices;
namespace ProcessHacker.Native.Objects
{
@@ -12,9 +16,12 @@ public static EnvironmentBlock Zero
get { return _zero; }
}
- public unsafe static EnvironmentBlock GetCurrent()
+ public static EnvironmentBlock GetCurrent()
{
- return new EnvironmentBlock(ProcessHandle.GetCurrentProcessParameters()->Environment);
+ unsafe
+ {
+ return new EnvironmentBlock(ProcessHandle.GetCurrentProcessParameters()->Environment);
+ }
}
public static string GetCurrentVariable(string name)
@@ -24,32 +31,46 @@ public static string GetCurrentVariable(string name)
public static EnvironmentBlock SetCurrent(EnvironmentBlock environmentBlock)
{
+ NtStatus status;
IntPtr previousEnvironment;
- Win32.RtlSetCurrentEnvironment(
+ if ((status = Win32.RtlSetCurrentEnvironment(
environmentBlock,
out previousEnvironment
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new EnvironmentBlock(previousEnvironment);
}
public static void SetCurrentVariable(string name, string value)
{
- UnicodeString nameStr = new UnicodeString(name);
- UnicodeString valueStr = new UnicodeString(value);
+ NtStatus status;
+ UnicodeString nameStr;
+ UnicodeString valueStr;
+
+ nameStr = new UnicodeString(name);
try
{
- Win32.RtlSetEnvironmentVariable(
- IntPtr.Zero,
- ref nameStr,
- ref valueStr
- ).ThrowIf();
+ valueStr = new UnicodeString(value);
+
+ try
+ {
+ if ((status = Win32.RtlSetEnvironmentVariable(
+ IntPtr.Zero,
+ ref nameStr,
+ ref valueStr
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
+ finally
+ {
+ valueStr.Dispose();
+ }
}
finally
{
- valueStr.Dispose();
nameStr.Dispose();
}
}
@@ -63,10 +84,13 @@ public static implicit operator IntPtr(EnvironmentBlock environmentBlock)
public EnvironmentBlock(bool cloneCurrent)
{
- Win32.RtlCreateEnvironment(
+ NtStatus status;
+
+ if ((status = Win32.RtlCreateEnvironment(
cloneCurrent,
out _environment
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public EnvironmentBlock(TokenHandle tokenHandle)
@@ -90,41 +114,36 @@ public void Destroy()
Win32.RtlDestroyEnvironment(this);
}
- public unsafe int Length
+ public unsafe int GetLength()
{
- get
- {
- short* ptr = (short*)_environment;
+ short* ptr = (short*)_environment;
- while (*ptr != 0)
- {
- while (*ptr++ != 0)
- {
+ while (*ptr != 0)
+ while (*ptr++ != 0)
+ ;
- }
- }
+ ptr++;
- ptr++;
-
- return (new IntPtr(ptr)).Decrement(_environment).ToInt32();
- }
+ return (new IntPtr(ptr)).Decrement(_environment).ToInt32();
}
public string GetVariable(string name)
{
- UnicodeString nameStr = new UnicodeString(name);
+ NtStatus status;
+ UnicodeString nameStr;
+ UnicodeString valueStr;
+
+ nameStr = new UnicodeString(name);
try
{
- using (MemoryAlloc data = new MemoryAlloc(100))
+ using (var data = new MemoryAlloc(100))
{
- UnicodeString valueStr = new UnicodeString
- {
- Buffer = data,
- MaximumLength = (ushort)data.Size
- };
+ valueStr = new UnicodeString();
+ valueStr.Buffer = data;
+ valueStr.MaximumLength = (ushort)data.Size;
- NtStatus status = Win32.RtlQueryEnvironmentVariable_U(
+ status = Win32.RtlQueryEnvironmentVariable_U(
this,
ref nameStr,
ref valueStr
@@ -144,9 +163,10 @@ ref valueStr
);
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
- return valueStr.Text;
+ return valueStr.Read();
}
}
finally
@@ -157,22 +177,33 @@ ref valueStr
public void SetVariable(string name, string value)
{
+ NtStatus status;
IntPtr environment = _environment;
+ UnicodeString nameStr;
+ UnicodeString valueStr;
- UnicodeString nameStr = new UnicodeString(name);
- UnicodeString valueStr = new UnicodeString(value);
+ nameStr = new UnicodeString(name);
try
{
- Win32.RtlSetEnvironmentVariable(
- ref environment,
- ref nameStr,
- ref valueStr
- ).ThrowIf();
+ valueStr = new UnicodeString(value);
+
+ try
+ {
+ if ((status = Win32.RtlSetEnvironmentVariable(
+ ref environment,
+ ref nameStr,
+ ref valueStr
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
+ finally
+ {
+ valueStr.Dispose();
+ }
}
finally
{
- valueStr.Dispose();
nameStr.Dispose();
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/EventHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/EventHandle.cs
index c332abfc9..5c6c7c8c4 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/EventHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/EventHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -40,12 +41,14 @@ public static EventHandle Create(EventAccess access, string name, EventType type
public static EventHandle Create(EventAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, EventType type, bool initialState)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateEvent(out handle, access, ref oa, type, initialState).ThrowIf();
+ if ((status = Win32.NtCreateEvent(out handle, access, ref oa, type, initialState)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -70,12 +73,14 @@ public EventHandle(string name, EventAccess access)
public EventHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, EventAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenEvent(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenEvent(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -87,51 +92,54 @@ public EventHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDir
public void Clear()
{
- Win32.NtClearEvent(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtClearEvent(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
- public EventBasicInformation BasicInformation
+ public EventBasicInformation GetBasicInformation()
{
- get
- {
- EventBasicInformation ebi;
- int retLength;
-
- Win32.NtQueryEvent(
- this,
- EventInformationClass.EventBasicInformation,
- out ebi,
- EventBasicInformation.SizeOf,
- out retLength
- ).ThrowIf();
-
- return ebi;
- }
+ NtStatus status;
+ EventBasicInformation ebi;
+ int retLength;
+
+ if ((status = Win32.NtQueryEvent(this, EventInformationClass.EventBasicInformation,
+ out ebi, Marshal.SizeOf(typeof(EventBasicInformation)), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return ebi;
}
public int Pulse()
{
+ NtStatus status;
int previousState;
- Win32.NtPulseEvent(this, out previousState).ThrowIf();
+ if ((status = Win32.NtPulseEvent(this, out previousState)) >= NtStatus.Error)
+ Win32.Throw(status);
return previousState;
}
public int Reset()
{
+ NtStatus status;
int previousState;
- Win32.NtResetEvent(this, out previousState).ThrowIf();
+ if ((status = Win32.NtResetEvent(this, out previousState)) >= NtStatus.Error)
+ Win32.Throw(status);
return previousState;
}
public int Set()
{
+ NtStatus status;
int previousState;
- Win32.NtSetEvent(this, out previousState).ThrowIf();
+ if ((status = Win32.NtSetEvent(this, out previousState)) >= NtStatus.Error)
+ Win32.Throw(status);
return previousState;
}
@@ -142,7 +150,10 @@ public int Set()
///
public void SetBoostPriority()
{
- Win32.NtSetEventBoostPriority(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtSetEventBoostPriority(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs
index 23d923147..f562dc5e4 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/EventPairHandle.cs
@@ -56,12 +56,14 @@ public static EventPairHandle Create(EventPairAccess access)
/// A handle to an event pair.
public static EventPairHandle Create(EventPairAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateEventPair(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtCreateEventPair(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -91,12 +93,14 @@ private EventPairHandle(IntPtr handle, bool owned)
/// The desired access to the event pair.
public EventPairHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, EventPairAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenEventPair(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenEventPair(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -115,7 +119,10 @@ public EventPairHandle(string name, EventPairAccess access)
///
public void SetHigh()
{
- Win32.NtSetHighEventPair(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtSetHighEventPair(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -123,7 +130,12 @@ public void SetHigh()
///
public NtStatus SetHighWaitLow()
{
- return Win32.NtSetHighWaitLowEventPair(this);
+ NtStatus status;
+
+ if ((status = Win32.NtSetHighWaitLowEventPair(this)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
///
@@ -131,7 +143,10 @@ public NtStatus SetHighWaitLow()
///
public void SetLow()
{
- Win32.NtSetLowEventPair(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtSetLowEventPair(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -139,7 +154,12 @@ public void SetLow()
///
public NtStatus SetLowWaitHigh()
{
- return Win32.NtSetLowWaitHighEventPair(this);
+ NtStatus status;
+
+ if ((status = Win32.NtSetLowWaitHighEventPair(this)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
///
@@ -147,7 +167,12 @@ public NtStatus SetLowWaitHigh()
///
public NtStatus WaitHigh()
{
- return Win32.NtWaitHighEventPair(this);
+ NtStatus status;
+
+ if ((status = Win32.NtWaitHighEventPair(this)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
///
@@ -155,7 +180,12 @@ public NtStatus WaitHigh()
///
public NtStatus WaitLow()
{
- return Win32.NtWaitLowEventPair(this);
+ NtStatus status;
+
+ if ((status = Win32.NtWaitLowEventPair(this)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/FileHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/FileHandle.cs
index 460b988aa..43d833d12 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/FileHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/FileHandle.cs
@@ -126,13 +126,14 @@ public static FileHandle Create(
out FileIoStatus ioStatus
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
IoStatusBlock isb;
IntPtr handle;
try
{
- Win32.NtCreateFile(
+ if ((status = Win32.NtCreateFile(
out handle,
access,
ref oa,
@@ -144,7 +145,8 @@ out FileIoStatus ioStatus
createOptions,
IntPtr.Zero,
0
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
ioStatus = (FileIoStatus)isb.Information.ToInt32();
}
@@ -166,11 +168,14 @@ public static FileHandle CreateWin32(string fileName, FileAccess desiredAccess,
return CreateWin32(fileName, desiredAccess, shareMode, FileCreationDispositionWin32.OpenAlways);
}
- public static FileHandle CreateWin32(string fileName, FileAccess desiredAccess, FileShareMode shareMode, FileCreationDispositionWin32 creationDisposition)
+ public static FileHandle CreateWin32(string fileName, FileAccess desiredAccess, FileShareMode shareMode,
+ FileCreationDispositionWin32 creationDisposition)
{
- IntPtr handle = Win32.CreateFile(fileName, desiredAccess, shareMode, 0, creationDisposition, 0, IntPtr.Zero);
+ IntPtr handle;
+
+ handle = Win32.CreateFile(fileName, desiredAccess, shareMode, 0, creationDisposition, 0, IntPtr.Zero);
- if (handle != MinusOne)
+ if (handle == NativeHandle.MinusOne)
Win32.Throw();
return new FileHandle(handle, true);
@@ -178,11 +183,13 @@ public static FileHandle CreateWin32(string fileName, FileAccess desiredAccess,
public static void Delete(string fileName, ObjectFlags objectFlags)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, null);
try
{
- Win32.NtDeleteFile(ref oa).ThrowIf();
+ if ((status = Win32.NtDeleteFile(ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -257,20 +264,22 @@ public FileHandle(
FileAccess access
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
IoStatusBlock isb;
IntPtr handle;
try
{
- Win32.NtOpenFile(
+ if ((status = Win32.NtOpenFile(
out handle,
access,
ref oa,
out isb,
shareMode,
openOptions
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -474,9 +483,11 @@ public void BeginLock(AsyncIoContext asyncContext, long offset, long length, boo
public void BeginLock(AsyncIoContext asyncContext, long offset, long length, bool wait, bool exclusive)
{
+ NtStatus status;
+
asyncContext.NotifyPreBegin();
- NtStatus status = Win32.NtLockFile(
+ status = Win32.NtLockFile(
this,
asyncContext.EventHandle ?? IntPtr.Zero,
null,
@@ -506,13 +517,14 @@ public void BeginRead(AsyncIoContext asyncContext, long fileOffset, byte[] buffe
public void BeginRead(AsyncIoContext asyncContext, long fileOffset, byte[] buffer, int offset, int length)
{
- Utils.ValidateBuffer(buffer, offset, length);
+ PinnedObject pinnedBuffer;
+ Utils.ValidateBuffer(buffer, offset, length);
asyncContext.NotifyPreBegin();
// Pin the buffer because the I/O system may be writing to it after
// this call returns.
- PinnedObject pinnedBuffer = new PinnedObject(buffer);
+ pinnedBuffer = new PinnedObject(buffer);
asyncContext.KeepAlive(pinnedBuffer);
this.BeginRead(asyncContext, fileOffset, pinnedBuffer.Address.Increment(offset), length);
}
@@ -560,13 +572,13 @@ public void BeginWrite(AsyncIoContext asyncContext, long fileOffset, byte[] buff
public void BeginWrite(AsyncIoContext asyncContext, long fileOffset, byte[] buffer, int offset, int length)
{
- Utils.ValidateBuffer(buffer, offset, length);
+ PinnedObject pinnedBuffer;
+ Utils.ValidateBuffer(buffer, offset, length);
asyncContext.NotifyPreBegin();
- PinnedObject pinnedBuffer = new PinnedObject(buffer);
+ pinnedBuffer = new PinnedObject(buffer);
asyncContext.KeepAlive(pinnedBuffer);
-
this.BeginWrite(asyncContext, fileOffset, pinnedBuffer.Address.Increment(offset), length);
}
@@ -612,9 +624,11 @@ protected void BeginWrite(AsyncIoContext asyncContext, long fileOffset, IntPtr b
/// An I/O status block.
public IoStatusBlock CancelIo()
{
+ NtStatus status;
IoStatusBlock isb;
- Win32.NtCancelIoFile(this, out isb).ThrowIf();
+ if ((status = Win32.NtCancelIoFile(this, out isb)) >= NtStatus.Error)
+ Win32.Throw(status);
return isb;
}
@@ -624,10 +638,10 @@ public IoStatusBlock CancelIo()
///
public void Delete()
{
- this.SetStruct(FileInformationClass.FileDispositionInformation, FileDispositionInformation.SizeOf, new FileDispositionInformation
- {
- DeleteFile = true
- });
+ this.SetStruct(
+ FileInformationClass.FileDispositionInformation,
+ new FileDispositionInformation() { DeleteFile = true }
+ );
}
///
@@ -640,7 +654,8 @@ protected int EndCommonIo(AsyncIoContext asyncContext)
asyncContext.Wait();
asyncContext.NotifyEnd();
- asyncContext.Status.ThrowIf();
+ if (asyncContext.Status >= NtStatus.Error)
+ Win32.Throw(asyncContext.Status);
return asyncContext.StatusBlock.Information.ToInt32();
}
@@ -678,7 +693,8 @@ public bool EndLock(AsyncIoContext asyncContext)
if (asyncContext.Status == NtStatus.LockNotGranted)
return false;
- asyncContext.Status.ThrowIf();
+ if (asyncContext.Status >= NtStatus.Error)
+ Win32.Throw(asyncContext.Status);
return true;
}
@@ -780,7 +796,8 @@ public void EnumFiles(EnumFilesDelegate callback, string searchPattern)
break;
// Handle any errors.
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
// Read the list of files we got in this batch.
@@ -788,8 +805,7 @@ public void EnumFiles(EnumFilesDelegate callback, string searchPattern)
while (true)
{
- FileDirectoryInformation info = data.ReadStruct(i, FileDirectoryInformation.SizeOf, 0);
-
+ FileDirectoryInformation info = data.ReadStruct(i, 0);
string name = data.ReadUnicodeString(
i + FileDirectoryInformation.FileNameOffset,
info.FileNameLength / 2
@@ -810,8 +826,8 @@ public void EnumFiles(EnumFilesDelegate callback, string searchPattern)
if (info.NextEntryOffset == 0)
break;
-
- i += info.NextEntryOffset;
+ else
+ i += info.NextEntryOffset;
}
firstTime = false;
@@ -833,13 +849,13 @@ public void EnumFiles(EnumFilesDelegate callback, string searchPattern)
/// The callback function to use.
public void EnumStreams(EnumStreamsDelegate callback)
{
- using (MemoryAlloc data = this.QueryVariableSize(FileInformationClass.FileStreamInformation))
+ using (var data = this.QueryVariableSize(FileInformationClass.FileStreamInformation))
{
int i = 0;
while (true)
{
- FileStreamInformation info = data.ReadStruct(i, FileStreamInformation.SizeOf, 0);
+ FileStreamInformation info = data.ReadStruct(i, 0);
string name = data.ReadUnicodeString(
i + FileStreamInformation.StreamNameOffset,
info.StreamNameLength / 2
@@ -850,8 +866,8 @@ public void EnumStreams(EnumStreamsDelegate callback)
if (info.NextEntryOffset == 0)
break;
-
- i += info.NextEntryOffset;
+ else
+ i += info.NextEntryOffset;
}
}
}
@@ -861,9 +877,10 @@ public void EnumStreams(EnumStreamsDelegate callback)
///
public void Flush()
{
+ NtStatus status;
IoStatusBlock isb;
- NtStatus status = Win32.NtFlushBuffersFile(
+ status = Win32.NtFlushBuffersFile(
this,
out isb
);
@@ -874,7 +891,8 @@ out isb
status = isb.Status;
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -945,9 +963,13 @@ public int FsControl(
int outBufferLength
)
{
+ NtStatus status;
int returnLength;
- this.FsControl(controlCode, inBuffer, inBufferLength, outBuffer, outBufferLength, out returnLength).ThrowIf();
+ status = this.FsControl(controlCode, inBuffer, inBufferLength, outBuffer, outBufferLength, out returnLength);
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return returnLength;
}
@@ -961,9 +983,10 @@ public NtStatus FsControl(
out int returnLength
)
{
+ NtStatus status;
IoStatusBlock isb;
- NtStatus status = Win32.NtFsControlFile(
+ status = Win32.NtFsControlFile(
this,
IntPtr.Zero,
null,
@@ -992,37 +1015,34 @@ out int returnLength
/// Gets the attributes of the file.
///
/// The attributes of the file.
- public FileAttributes Attributes
+ public FileAttributes GetAttributes()
{
- get { return this.BasicInformation.FileAttributes; }
+ return this.GetBasicInformation().FileAttributes;
}
///
/// Gets basic information about the file.
///
/// Basic information about the file.
- public FileBasicInformation BasicInformation
+ public FileBasicInformation GetBasicInformation()
{
- get { return this.QueryStruct(FileInformationClass.FileBasicInformation, FileBasicInformation.SizeOf); }
+ return this.QueryStruct(FileInformationClass.FileBasicInformation);
}
///
/// Gets the partial name of the file.
///
/// The name of the file, relative to its volume.
- public string FileName
+ public string GetFileName()
{
- get
+ using (var data = this.QueryVariableSize(FileInformationClass.FileNameInformation))
{
- using (MemoryAlloc data = this.QueryVariableSize(FileInformationClass.FileNameInformation))
- {
- FileNameInformation info = data.ReadStruct(0, FileNameInformation.SizeOf, 0);
+ FileNameInformation info = data.ReadStruct();
- return data.ReadUnicodeString(
- FileNameInformation.FileNameOffset,
- info.FileNameLength/2
- );
- }
+ return data.ReadUnicodeString(
+ FileNameInformation.FileNameOffset,
+ info.FileNameLength / 2
+ );
}
}
@@ -1030,9 +1050,9 @@ public string FileName
/// Gets a list of the files contained in the directory.
///
/// An array of file information structures.
- public FileEntry[] Files
+ public FileEntry[] GetFiles()
{
- get { return this.GetFiles(null); }
+ return this.GetFiles(null);
}
///
@@ -1049,7 +1069,7 @@ public FileEntry[] GetFiles(string searchPattern)
{
List files = new List();
- this.EnumFiles(file =>
+ this.EnumFiles((file) =>
{
files.Add(file);
return true;
@@ -1062,15 +1082,9 @@ public FileEntry[] GetFiles(string searchPattern)
/// Gets the current position.
///
/// A byte offset from the beginning of the file.
- public long Position
+ public long GetPosition()
{
- get
- {
- return this.QueryStruct(
- FileInformationClass.FilePositionInformation,
- FilePositionInformation.SizeOf
- ).CurrentByteOffset;
- }
+ return this.QueryStruct(FileInformationClass.FilePositionInformation).CurrentByteOffset;
}
///
@@ -1081,7 +1095,7 @@ public FileStreamEntry[] GetStreams()
{
List streams = new List();
- this.EnumStreams(file =>
+ this.EnumStreams((file) =>
{
streams.Add(file);
return true;
@@ -1094,53 +1108,46 @@ public FileStreamEntry[] GetStreams()
/// Gets the size of the file.
///
/// The size of the file.
- public long FileSize
+ public long GetSize()
{
- get { return this.StandardInformation.EndOfFile; }
+ return this.GetStandardInformation().EndOfFile;
}
///
/// Gets standard information about the file.
///
/// Standard information about the file.
- public FileStandardInformation StandardInformation
- {
- get
- {
- return this.QueryStruct(
- FileInformationClass.FileStandardInformation,
- FileStandardInformation.SizeOf
- );
- }
+ public FileStandardInformation GetStandardInformation()
+ {
+ return this.QueryStruct(FileInformationClass.FileStandardInformation);
}
///
/// Gets the file system name of the file's associated volume.
///
/// The volume's file system name.
- public string VolumeFsName
+ public string GetVolumeFsName()
{
- get
+ NtStatus status;
+ IoStatusBlock isb;
+
+ using (var data = new MemoryAlloc(0x200))
{
- IoStatusBlock isb;
+ if ((status = Win32.NtQueryVolumeInformationFile(
+ this,
+ out isb,
+ data,
+ data.Size,
+ FsInformationClass.FileFsAttributeInformation
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (MemoryAlloc data = new MemoryAlloc(0x200))
- {
- Win32.NtQueryVolumeInformationFile(
- this,
- out isb,
- data,
- data.Size,
- FsInformationClass.FileFsAttributeInformation
- ).ThrowIf();
-
- FileFsAttributeInformation info = data.ReadStruct(0, FileFsAttributeInformation.SizeOf, 0);
-
- return Marshal.PtrToStringUni(
- data.Memory.Increment(FileFsAttributeInformation.FileSystemNameOffset),
- info.FileSystemNameLength/2
- );
- }
+ FileFsAttributeInformation info = data.ReadStruct();
+
+ return Marshal.PtrToStringUni(
+ data.Memory.Increment(Marshal.OffsetOf(typeof(FileFsAttributeInformation), "FileSystemName")),
+ info.FileSystemNameLength / 2
+ );
}
}
@@ -1148,29 +1155,28 @@ public string VolumeFsName
/// Gets the label of the file's associated volume.
///
/// The volume label.
- public string VolumeLabel
+ public string GetVolumeLabel()
{
- get
- {
- using (MemoryAlloc data = new MemoryAlloc(0x200))
- {
- IoStatusBlock isb;
+ NtStatus status;
+ IoStatusBlock isb;
- Win32.NtQueryVolumeInformationFile(
- this,
- out isb,
- data,
- data.Size,
- FsInformationClass.FileFsVolumeInformation
- ).ThrowIf();
+ using (var data = new MemoryAlloc(0x200))
+ {
+ if ((status = Win32.NtQueryVolumeInformationFile(
+ this,
+ out isb,
+ data,
+ data.Size,
+ FsInformationClass.FileFsVolumeInformation
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- FileFsVolumeInformation info = data.ReadStruct();
+ FileFsVolumeInformation info = data.ReadStruct();
- return Marshal.PtrToStringUni(
- data.Memory.Increment(FileFsVolumeInformation.VolumeLabelOffset),
- info.VolumeLabelLength/2
- );
- }
+ return Marshal.PtrToStringUni(
+ data.Memory.Increment(Marshal.OffsetOf(typeof(FileFsVolumeInformation), "VolumeLabel")),
+ info.VolumeLabelLength / 2
+ );
}
}
@@ -1261,9 +1267,13 @@ public int IoControl(
int outBufferLength
)
{
+ NtStatus status;
int returnLength;
- this.IoControl(controlCode, inBuffer, inBufferLength, outBuffer, outBufferLength, out returnLength).ThrowIf();
+ status = this.IoControl(controlCode, inBuffer, inBufferLength, outBuffer, outBufferLength, out returnLength);
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return returnLength;
}
@@ -1277,9 +1287,10 @@ public NtStatus IoControl(
out int returnLength
)
{
+ NtStatus status;
IoStatusBlock isb;
- NtStatus status = Win32.NtDeviceIoControlFile(
+ status = Win32.NtDeviceIoControlFile(
this,
IntPtr.Zero,
null,
@@ -1345,9 +1356,10 @@ public bool Lock(long offset, long length, bool wait)
/// True if the lock was acquired, otherwise false.
public bool Lock(long offset, long length, bool wait, bool exclusive)
{
+ NtStatus status;
IoStatusBlock isb;
- NtStatus status = Win32.NtLockFile(
+ status = Win32.NtLockFile(
this,
IntPtr.Zero,
null,
@@ -1369,26 +1381,30 @@ public bool Lock(long offset, long length, bool wait, bool exclusive)
if (status == NtStatus.LockNotGranted)
return false;
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return true;
}
- protected T QueryStruct(FileInformationClass infoClass, int size) where T : struct
+ protected T QueryStruct(FileInformationClass infoClass)
+ where T : struct
{
- using (MemoryAlloc data = new MemoryAlloc(size))
+ NtStatus status;
+ IoStatusBlock isb;
+
+ using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(T))))
{
- IoStatusBlock isb;
-
- Win32.NtQueryInformationFile(
+ if ((status = Win32.NtQueryInformationFile(
this,
out isb,
data,
data.Size,
infoClass
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- return data.ReadStruct(0, size, 0);
+ return data.ReadStruct();
}
}
@@ -1396,7 +1412,7 @@ protected MemoryAlloc QueryVariableSize(FileInformationClass infoClass)
{
NtStatus status;
IoStatusBlock isb;
- MemoryAlloc data = new MemoryAlloc(0x200);
+ var data = new MemoryAlloc(0x200);
while (true)
{
@@ -1418,7 +1434,7 @@ protected MemoryAlloc QueryVariableSize(FileInformationClass infoClass)
break;
}
- if (status.IsError())
+ if (status >= NtStatus.Error)
{
data.Dispose();
Win32.Throw(status);
@@ -1560,7 +1576,8 @@ public int Read(long fileOffset, IntPtr buffer, int length)
status = isb.Status;
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return isb.Information.ToInt32();
}
@@ -1571,10 +1588,10 @@ public int Read(long fileOffset, IntPtr buffer, int length)
/// A byte offset from the beginning of the file.
public void SetEnd(long offset)
{
- this.SetStruct(FileInformationClass.FileEndOfFileInformation, FileEndOfFileInformation.SizeOf, new FileEndOfFileInformation
- {
- EndOfFile = offset
- });
+ this.SetStruct(
+ FileInformationClass.FileEndOfFileInformation,
+ new FileEndOfFileInformation() { EndOfFile = offset }
+ );
}
///
@@ -1602,13 +1619,11 @@ public void SetIoCompletion(IoCompletionHandle ioCompletionHandle)
/// A key to associate with the file object.
public void SetIoCompletion(IoCompletionHandle ioCompletionHandle, IntPtr keyContext)
{
- FileCompletionInformation info = new FileCompletionInformation
- {
- Port = ioCompletionHandle,
- Key = keyContext
- };
+ FileCompletionInformation info = new FileCompletionInformation();
- this.SetStruct(FileInformationClass.FileCompletionInformation, FileCompletionInformation.SizeOf, info);
+ info.Port = ioCompletionHandle;
+ info.Key = keyContext;
+ this.SetStruct(FileInformationClass.FileCompletionInformation, info);
}
///
@@ -1617,10 +1632,10 @@ public void SetIoCompletion(IoCompletionHandle ioCompletionHandle, IntPtr keyCon
/// A byte offset from the beginning of the file.
public void SetPosition(long offset)
{
- this.SetStruct(FileInformationClass.FilePositionInformation, FilePositionInformation.SizeOf, new FilePositionInformation
- {
- CurrentByteOffset = offset
- });
+ this.SetStruct(
+ FileInformationClass.FilePositionInformation,
+ new FilePositionInformation() { CurrentByteOffset = offset }
+ );
}
///
@@ -1632,7 +1647,7 @@ public long SetPosition(long offset, PositionOrigin origin)
{
long currentPosition;
- currentPosition = this.Position;
+ currentPosition = this.GetPosition();
switch (origin)
{
@@ -1643,7 +1658,7 @@ public long SetPosition(long offset, PositionOrigin origin)
currentPosition = offset;
break;
case PositionOrigin.End:
- currentPosition = this.FileSize + offset;
+ currentPosition = this.GetSize() + offset;
break;
}
@@ -1652,21 +1667,24 @@ public long SetPosition(long offset, PositionOrigin origin)
return currentPosition;
}
- protected void SetStruct(FileInformationClass infoClass, int size, T info) where T : struct
+ protected void SetStruct(FileInformationClass infoClass, T info)
+ where T : struct
{
- using (MemoryAlloc data = new MemoryAlloc(size))
- {
- data.WriteStruct(info);
+ NtStatus status;
+ IoStatusBlock isb;
- IoStatusBlock isb;
+ using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(T))))
+ {
+ data.WriteStruct(info);
- Win32.NtSetInformationFile(
+ if ((status = Win32.NtSetInformationFile(
this,
out isb,
data,
data.Size,
infoClass
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
@@ -1677,15 +1695,19 @@ protected void SetStruct(FileInformationClass infoClass, int size, T info) wh
/// The length of the byte range.
public void Unlock(long offset, long length)
{
+ NtStatus status;
IoStatusBlock isb;
- Win32.NtUnlockFile(
+ status = Win32.NtUnlockFile(
this,
out isb,
ref offset,
ref length,
0
- ).ThrowIf();
+ );
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -1807,7 +1829,8 @@ public int Write(long fileOffset, IntPtr buffer, int length)
status = isb.Status;
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return isb.Information.ToInt32();
}
@@ -1828,7 +1851,7 @@ public enum PositionOrigin
public sealed class AsyncIoCompletionPort : IDisposable
{
- private readonly IoCompletionHandle _ioCompletionHandle;
+ private IoCompletionHandle _ioCompletionHandle;
public AsyncIoCompletionPort()
: this(0)
@@ -1856,17 +1879,19 @@ public AsyncIoContext Remove()
public AsyncIoContext Remove(long timeout, bool relative)
{
+ bool result;
+ AsyncIoContext asyncContext;
IoStatusBlock isb;
IntPtr keyContext;
IntPtr apcContext;
- bool result = this._ioCompletionHandle.Remove(out isb, out keyContext, out apcContext, relative ? -timeout : timeout, false);
+ result = _ioCompletionHandle.Remove(out isb, out keyContext, out apcContext, relative ? -timeout : timeout, false);
// Fail?
if (!result)
return null;
- AsyncIoContext asyncContext = AsyncIoContext.GetAsyncIoContext(apcContext);
+ asyncContext = AsyncIoContext.GetAsyncIoContext(apcContext);
asyncContext.NotifyEnd();
return asyncContext;
@@ -1885,17 +1910,19 @@ public sealed class AsyncIoContext : BaseObject, ISynchronizable
{
private unsafe sealed class UnmanagedIsb : BaseObject
{
+ private static readonly int _isbSize = Marshal.SizeOf(typeof(IoStatusBlock));
+
public static implicit operator IntPtr(UnmanagedIsb isb)
{
return isb.Memory;
}
- private readonly IoStatusBlock* _ioStatusBlock;
+ private IoStatusBlock* _ioStatusBlock;
public UnmanagedIsb()
{
// Allocate an ISB.
- _ioStatusBlock = (IoStatusBlock*)MemoryAlloc.PrivateHeap.Allocate(IoStatusBlock.SizeOf);
+ _ioStatusBlock = (IoStatusBlock*)MemoryAlloc.PrivateHeap.Allocate(0, _isbSize);
// Zero the ISB.
_ioStatusBlock->Pointer = IntPtr.Zero;
_ioStatusBlock->Information = IntPtr.Zero;
@@ -1905,7 +1932,7 @@ public UnmanagedIsb()
protected override void DisposeObject(bool disposing)
{
if (_ioStatusBlock != null)
- MemoryAlloc.PrivateHeap.Free(new IntPtr(_ioStatusBlock));
+ MemoryAlloc.PrivateHeap.Free(0, new IntPtr(_ioStatusBlock));
}
public IntPtr Information
@@ -1944,12 +1971,12 @@ public static AsyncIoContext GetAsyncIoContext(IntPtr context)
}
private IntPtr _context = IntPtr.Zero;
- private readonly EventHandle _eventHandle;
- private readonly UnmanagedIsb _isb;
- private bool _completedSynchronously;
- private bool _started;
+ private EventHandle _eventHandle = null;
+ private UnmanagedIsb _isb;
+ private bool _completedSynchronously = false;
+ private bool _started = false;
- private List _keepAliveList;
+ private List _keepAliveList = null;
private object _tag;
public AsyncIoContext()
@@ -1958,10 +1985,8 @@ public AsyncIoContext()
public AsyncIoContext(AsyncIoMethod method)
{
- _isb = new UnmanagedIsb
- {
- Status = NtStatus.Pending
- };
+ _isb = new UnmanagedIsb();
+ _isb.Status = NtStatus.Pending;
if (method == AsyncIoMethod.Event)
{
@@ -1990,16 +2015,6 @@ protected override void DisposeObject(bool disposing)
_eventHandle.Dispose();
if (_isb != null)
_isb.Dispose();
-
- if (_context != IntPtr.Zero)
- {
- GCHandle handle = GCHandle.FromIntPtr(_context);
-
- if (handle.IsAllocated)
- handle.Free();
-
- _context = IntPtr.Zero;
- }
}
public bool Cancelled
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/IoCompletionHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/IoCompletionHandle.cs
index 943b5a341..e71db55b9 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/IoCompletionHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/IoCompletionHandle.cs
@@ -21,7 +21,10 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
+using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
namespace ProcessHacker.Native.Objects
@@ -45,12 +48,14 @@ public static IoCompletionHandle Create(IoCompletionAccess access, string name,
public static IoCompletionHandle Create(IoCompletionAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, int count)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateIoCompletion(out handle, access, ref oa, count).ThrowIf();
+ if ((status = Win32.NtCreateIoCompletion(out handle, access, ref oa, count)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -66,12 +71,14 @@ private IoCompletionHandle(IntPtr handle, bool owned)
public IoCompletionHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, IoCompletionAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenIoCompletion(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenIoCompletion(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -92,20 +99,23 @@ public bool Remove(out IoStatusBlock isb, out IntPtr keyContext, out IntPtr apcC
public bool Remove(out IoStatusBlock isb, out IntPtr keyContext, out IntPtr apcContext, long timeout, bool relative)
{
+ NtStatus status;
long realTimeout = relative ? -timeout : timeout;
- return Win32.NtRemoveIoCompletion(this, out keyContext, out apcContext, out isb, ref realTimeout) != NtStatus.Timeout;
+ if ((status = Win32.NtRemoveIoCompletion(
+ this, out keyContext, out apcContext, out isb, ref realTimeout)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status != NtStatus.Timeout;
}
public void Set(IntPtr keyContext, IntPtr apcContext, NtStatus ioStatus, IntPtr ioInformation)
{
- Win32.NtSetIoCompletion(
- this,
- keyContext,
- apcContext,
- ioStatus,
- ioInformation
- ).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtSetIoCompletion(
+ this, keyContext, apcContext, ioStatus, ioInformation)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs
index 43f2d1df3..9d4f242ee 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/JobObjectHandle.cs
@@ -22,6 +22,7 @@
using System;
using System.Collections.Generic;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -44,16 +45,18 @@ public static JobObjectHandle Create(JobObjectAccess access, string name)
public static JobObjectHandle Create(JobObjectAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateJobObject(
+ if ((status = Win32.NtCreateJobObject(
out handle,
access,
ref oa
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -67,15 +70,17 @@ internal static IntPtr Open(ProcessHandle processHandle, JobObjectAccess access)
{
try
{
- return KProcessHacker2.Instance.KphOpenProcessJob(processHandle, (TokenAccess)access);
+ return new IntPtr(KProcessHacker.Instance.KphOpenProcessJob(processHandle, access));
}
catch (WindowsException)
{
+ IntPtr handle;
+
// Use KPH to set the handle's granted access.
- IntPtr handle = KProcessHacker2.Instance.KphOpenProcessJob(processHandle, (TokenAccess)StandardRights.Synchronize);
-
- //if (handle != IntPtr.Zero)
- //KProcessHacker2.Instance.KphSetHandleGrantedAccess(handle, (int)access);
+ handle = new IntPtr(KProcessHacker.Instance.KphOpenProcessJob(processHandle,
+ (JobObjectAccess)StandardRights.Synchronize));
+ if (handle != IntPtr.Zero)
+ KProcessHacker.Instance.KphSetHandleGrantedAccess(handle, (int)access);
return handle;
}
@@ -102,16 +107,18 @@ public JobObjectHandle(string name, JobObjectAccess access)
public JobObjectHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, JobObjectAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenJobObject(
+ if ((status = Win32.NtOpenJobObject(
out handle,
access,
ref oa
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -138,80 +145,80 @@ public JobObjectHandle(ProcessHandle processHandle, JobObjectAccess access)
}
}
+ private T QueryStruct(JobObjectInformationClass informationClass)
+ where T : struct
+ {
+ int retLength;
+
+ using (MemoryAlloc data = new MemoryAlloc(Marshal.SizeOf(typeof(T))))
+ {
+ if (!Win32.QueryInformationJobObject(this, informationClass, data, data.Size, out retLength))
+ {
+ data.ResizeNew(retLength);
+
+ if (!Win32.QueryInformationJobObject(this, informationClass, data, data.Size, out retLength))
+ Win32.Throw();
+ }
+
+ return data.ReadStruct();
+ }
+ }
+
public JobObjectBasicAccountingInformation GetBasicAccountingInformation()
{
return this.QueryStruct(
- JobObjectInformationClass.JobObjectBasicAccountingInformation,
- JobObjectBasicAccountingInformation.SizeOf
- );
+ JobObjectInformationClass.JobObjectBasicAccountingInformation);
}
public JobObjectBasicAndIoAccountingInformation GetBasicAndIoAccountingInformation()
{
return this.QueryStruct(
- JobObjectInformationClass.JobObjectBasicAndIoAccountingInformation,
- JobObjectBasicAndIoAccountingInformation.SizeOf
- );
+ JobObjectInformationClass.JobObjectBasicAndIoAccountingInformation);
}
- public JobObjectBasicLimitInformation BasicLimitInformation
+ public JobObjectBasicLimitInformation GetBasicLimitInformation()
{
- get { return this.QueryStruct(
- JobObjectInformationClass.JobObjectBasicLimitInformation,
- JobObjectBasicLimitInformation.SizeOf
- );
- }
+ return this.QueryStruct(JobObjectInformationClass.JobObjectBasicLimitInformation);
}
- public JobObjectBasicUiRestrictions BasicUiRestrictions
+ public int[] GetProcessIdList()
{
- get
- {
- JobObjectBasicUiRestrictions uiRestrictions;
- int retLength;
+ List processIds = new List();
+ int retLength;
- if (!Win32.QueryInformationJobObject(this, JobObjectInformationClass.JobObjectBasicUIRestrictions, out uiRestrictions, 4, out retLength))
+ // FIXME: Fixed buffer
+ using (MemoryAlloc data = new MemoryAlloc(0x1000))
+ {
+ if (!Win32.QueryInformationJobObject(this, JobObjectInformationClass.JobObjectBasicProcessIdList,
+ data, data.Size, out retLength))
Win32.Throw();
- return uiRestrictions;
- }
- }
+ JobObjectBasicProcessIdList listInfo = data.ReadStruct();
- public JobObjectExtendedLimitInformation ExtendedLimitInformation
- {
- get
- {
- return this.QueryStruct(
- JobObjectInformationClass.JobObjectExtendedLimitInformation,
- JobObjectExtendedLimitInformation.SizeOf
- );
+ for (int i = 0; i < listInfo.NumberOfProcessIdsInList; i++)
+ {
+ processIds.Add(data.ReadInt32(8, i));
+ }
}
+
+ return processIds.ToArray();
}
- public int[] ProcessIdList
+ public JobObjectBasicUiRestrictions GetBasicUiRestrictions()
{
- get
- {
- List processIds = new List();
- int retLength;
-
- // FIXME: Fixed buffer
- using (MemoryAlloc data = new MemoryAlloc(0x1000))
- {
- if (!Win32.QueryInformationJobObject(this, JobObjectInformationClass.JobObjectBasicProcessIdList,
- data, data.Size, out retLength))
- Win32.Throw();
+ JobObjectBasicUiRestrictions uiRestrictions;
+ int retLength;
- JobObjectBasicProcessIdList listInfo = data.ReadStruct();
+ if (!Win32.QueryInformationJobObject(this, JobObjectInformationClass.JobObjectBasicUIRestrictions,
+ out uiRestrictions, 4, out retLength))
+ Win32.Throw();
- for (int i = 0; i < listInfo.NumberOfProcessIdsInList; i++)
- {
- processIds.Add(data.ReadInt32(8, i));
- }
- }
+ return uiRestrictions;
+ }
- return processIds.ToArray();
- }
+ public JobObjectExtendedLimitInformation GetExtendedLimitInformation()
+ {
+ return this.QueryStruct(JobObjectInformationClass.JobObjectExtendedLimitInformation);
}
public void Terminate()
@@ -224,26 +231,5 @@ public void Terminate(int exitCode)
if (!Win32.TerminateJobObject(this, exitCode))
Win32.Throw();
}
-
- private T QueryStruct(JobObjectInformationClass informationClass, int size) where T : struct
- {
- int retLength;
-
- using (MemoryAlloc data = new MemoryAlloc(size))
- {
- bool ret = Win32.QueryInformationJobObject(this, informationClass, data, data.Size, out retLength);
- int res = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
-
- if (!Win32.QueryInformationJobObject(this, informationClass, data, data.Size, out retLength))
- {
- data.ResizeNew(retLength);
-
- if (!Win32.QueryInformationJobObject(this, informationClass, data, data.Size, out retLength))
- Win32.Throw();
- }
-
- return data.ReadStruct();
- }
- }
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/KeyHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/KeyHandle.cs
index 5e8603325..1c075c886 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/KeyHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/KeyHandle.cs
@@ -21,6 +21,9 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
+using ProcessHacker.Native;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -59,12 +62,13 @@ public static KeyHandle Create(
out KeyCreationDisposition creationDisposition
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateKey(
+ if ((status = Win32.NtCreateKey(
out handle,
access,
ref oa,
@@ -72,7 +76,8 @@ out KeyCreationDisposition creationDisposition
IntPtr.Zero,
createOptions,
out creationDisposition
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -92,16 +97,18 @@ public KeyHandle(string name, KeyAccess access)
public KeyHandle(string name, ObjectFlags objectFlags, KeyHandle rootDirectory, KeyAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenKey(
+ if ((status = Win32.NtOpenKey(
out handle,
access,
ref oa
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -113,16 +120,21 @@ ref oa
public void Delete()
{
- Win32.NtDeleteKey(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtDeleteKey(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void DeleteValue(string name)
{
+ NtStatus status;
UnicodeString nameStr = new UnicodeString(name);
try
{
- Win32.NtDeleteValueKey(this, ref nameStr).ThrowIf();
+ if ((status = Win32.NtDeleteValueKey(this, ref nameStr)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs
index af0e11d82..0cd6de4bb 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/KeyedEventHandle.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -40,12 +42,14 @@ public static KeyedEventHandle Create(KeyedEventAccess access, string name)
public static KeyedEventHandle Create(KeyedEventAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateKeyedEvent(out handle, access, ref oa, 0).ThrowIf();
+ if ((status = Win32.NtCreateKeyedEvent(out handle, access, ref oa, 0)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -65,12 +69,14 @@ public KeyedEventHandle(string name, KeyedEventAccess access)
public KeyedEventHandle(string name, DirectoryHandle rootDirectory, ObjectFlags objectFlags, KeyedEventAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenKeyedEvent(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenKeyedEvent(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -102,17 +108,21 @@ public NtStatus ReleaseKey(int key, bool alertable, long timeout)
public NtStatus ReleaseKey(IntPtr key, bool alertable, long timeout, bool relative)
{
+ NtStatus status;
long realTimeout = relative ? -timeout : timeout;
if (key.ToInt64() % 2 != 0)
throw new ArgumentException("Key must be divisible by 2.");
- return Win32.NtReleaseKeyedEvent(
+ if ((status = Win32.NtReleaseKeyedEvent(
this,
key,
alertable,
ref realTimeout
- );
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
public NtStatus WaitKey(int key)
@@ -137,17 +147,21 @@ public NtStatus WaitKey(int key, bool alertable, long timeout)
public NtStatus WaitKey(IntPtr key, bool alertable, long timeout, bool relative)
{
+ NtStatus status;
long realTimeout = relative ? -timeout : timeout;
if (key.ToInt64() % 2 != 0)
throw new ArgumentException("Key must be divisible by 2.");
- return Win32.NtWaitForKeyedEvent(
+ if ((status = Win32.NtWaitForKeyedEvent(
this,
key,
alertable,
ref realTimeout
- );
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/LsaAccountHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/LsaAccountHandle.cs
index 3785068a0..305b6e51d 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/LsaAccountHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/LsaAccountHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -33,14 +34,16 @@ public sealed class LsaAccountHandle : LsaHandle
{
public static LsaAccountHandle Create(LsaAccountAccess access, LsaPolicyHandle policyHandle, Sid sid)
{
+ NtStatus status;
IntPtr handle;
- Win32.LsaCreateAccount(
+ if ((status = Win32.LsaCreateAccount(
policyHandle,
sid,
access,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new LsaAccountHandle(handle, true);
}
@@ -57,14 +60,16 @@ private LsaAccountHandle(IntPtr handle, bool owned)
/// The desired access to the account.
public LsaAccountHandle(LsaPolicyHandle policyHandle, Sid sid, LsaAccountAccess access)
{
+ NtStatus status;
IntPtr handle;
- Win32.LsaOpenAccount(
+ if ((status = Win32.LsaOpenAccount(
policyHandle,
sid,
access,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.Handle = handle;
}
@@ -76,62 +81,61 @@ public void AddPrivilege(Privilege privilege)
public void AddPrivileges(PrivilegeSet privileges)
{
- using (MemoryAlloc privilegeSetMemory = privileges.ToMemory())
+ NtStatus status;
+
+ using (var privilegeSetMemory = privileges.ToMemory())
{
- Win32.LsaAddPrivilegesToAccount(
+ if ((status = Win32.LsaAddPrivilegesToAccount(
this,
privilegeSetMemory
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
- public PrivilegeSet Privileges
+ public PrivilegeSet GetPrivileges()
{
- get
- {
- IntPtr privileges;
+ NtStatus status;
+ IntPtr privileges;
- Win32.LsaEnumeratePrivilegesOfAccount(
- this,
- out privileges
- ).ThrowIf();
+ if ((status = Win32.LsaEnumeratePrivilegesOfAccount(
+ this,
+ out privileges
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (LsaMemoryAlloc privilegesAlloc = new LsaMemoryAlloc(privileges))
- {
- return new PrivilegeSet(privilegesAlloc);
- }
+ using (var privilegesAlloc = new LsaMemoryAlloc(privileges))
+ {
+ return new PrivilegeSet(privilegesAlloc);
}
}
- public QuotaLimits Quotas
+ public QuotaLimits GetQuotas()
{
- get
- {
- QuotaLimits quotas;
+ NtStatus status;
+ QuotaLimits quotas;
- Win32.LsaGetQuotasForAccount(
- this,
- out quotas
- ).ThrowIf();
+ if ((status = Win32.LsaGetQuotasForAccount(
+ this,
+ out quotas
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- return quotas;
- }
+ return quotas;
}
-
- public SecuritySystemAccess SystemAccess
+ public SecuritySystemAccess GetSystemAccess()
{
- get
- {
- SecuritySystemAccess access;
+ NtStatus status;
+ SecuritySystemAccess access;
- Win32.LsaGetSystemAccessAccount(
- this,
- out access
- ).ThrowIf();
+ if ((status = Win32.LsaGetSystemAccessAccount(
+ this,
+ out access
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- return access;
- }
+ return access;
}
public void RemovePrivilege(Privilege privilege)
@@ -141,39 +145,51 @@ public void RemovePrivilege(Privilege privilege)
public void RemovePrivileges()
{
- Win32.LsaRemovePrivilegesFromAccount(
+ NtStatus status;
+
+ if ((status = Win32.LsaRemovePrivilegesFromAccount(
this,
true,
IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void RemovePrivileges(PrivilegeSet privileges)
{
- using (MemoryAlloc privilegeSetMemory = privileges.ToMemory())
+ NtStatus status;
+
+ using (var privilegeSetMemory = privileges.ToMemory())
{
- Win32.LsaRemovePrivilegesFromAccount(
+ if ((status = Win32.LsaRemovePrivilegesFromAccount(
this,
false,
privilegeSetMemory
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
public void SetQuotas(QuotaLimits quotas)
{
- Win32.LsaSetQuotasForAccount(
+ NtStatus status;
+
+ if ((status = Win32.LsaSetQuotasForAccount(
this,
ref quotas
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void SetSystemAccess(SecuritySystemAccess access)
{
- Win32.LsaSetSystemAccessAccount(
+ NtStatus status;
+
+ if ((status = Win32.LsaSetSystemAccessAccount(
this,
access
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/LsaAuthHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/LsaAuthHandle.cs
index 6820913d7..bcb9dfaf2 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/LsaAuthHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/LsaAuthHandle.cs
@@ -21,7 +21,10 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
+using ProcessHacker.Native.Security;
using ProcessHacker.Native.Security.Authentication;
namespace ProcessHacker.Native.Objects
@@ -30,18 +33,21 @@ public sealed class LsaAuthHandle : NativeHandle
{
public static LsaAuthHandle Connect(string name)
{
+ NtStatus status;
+ AnsiString nameStr;
IntPtr handle;
LsaOperationalMode mode;
- AnsiString nameStr = new AnsiString(name);
+ nameStr = new AnsiString(name);
try
{
- Win32.LsaRegisterLogonProcess(
+ if ((status = Win32.LsaRegisterLogonProcess(
ref nameStr,
out handle,
out mode
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -53,9 +59,11 @@ out mode
public static LsaAuthHandle ConnectUntrusted()
{
+ NtStatus status;
IntPtr handle;
- Win32.LsaConnectUntrusted(out handle).ThrowIf();
+ if ((status = Win32.LsaConnectUntrusted(out handle)) >= NtStatus.Error)
+ Win32.Throw(status);
return new LsaAuthHandle(handle, true);
}
@@ -101,18 +109,20 @@ public TokenHandle LogonUser(
out NtStatus subStatus
)
{
+ NtStatus status;
+ AnsiString originNameStr;
IntPtr profileBuffer;
int profileBufferLength;
IntPtr token;
QuotaLimits quotas;
- AnsiString originNameStr = new AnsiString(originName);
+ originNameStr = new AnsiString(originName);
try
{
- using (MemoryRegion logonData = package.GetAuthData())
+ using (var logonData = package.GetAuthData())
{
- Win32.LsaLogonUser(
+ if ((status = Win32.LsaLogonUser(
this,
ref originNameStr,
logonType,
@@ -127,12 +137,11 @@ out NtStatus subStatus
out token,
out quotas,
out subStatus
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (new LsaMemoryAlloc(profileBuffer, true))
- {
+ using (var profileBufferAlloc = new LsaMemoryAlloc(profileBuffer, true))
profileData = package.GetProfileData(new MemoryRegion(profileBuffer, 0, profileBufferLength));
- }
return new TokenHandle(token, true);
}
@@ -145,17 +154,20 @@ out subStatus
public int LookupAuthenticationPackage(string packageName)
{
+ NtStatus status;
+ AnsiString packageNameStr;
int authenticationPackage;
- AnsiString packageNameStr = new AnsiString(packageName);
+ packageNameStr = new AnsiString(packageName);
try
{
- Win32.LsaLookupAuthenticationPackage(
+ if ((status = Win32.LsaLookupAuthenticationPackage(
this,
ref packageNameStr,
out authenticationPackage
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/LsaHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/LsaHandle.cs
index bea581c38..b34e33b2a 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/LsaHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/LsaHandle.cs
@@ -46,29 +46,37 @@ protected override void Close()
public void Delete()
{
- Win32.LsaDelete(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.LsaDelete(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public override SecurityDescriptor GetSecurity(SecurityInformation securityInformation)
{
+ NtStatus status;
IntPtr securityDescriptor;
- Win32.LsaQuerySecurityObject(
+ if ((status = Win32.LsaQuerySecurityObject(
this,
securityInformation,
out securityDescriptor
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new SecurityDescriptor(new LsaMemoryAlloc(securityDescriptor));
}
public override void SetSecurity(SecurityInformation securityInformation, SecurityDescriptor securityDescriptor)
{
- Win32.LsaSetSecurityObject(
+ NtStatus status;
+
+ if ((status = Win32.LsaSetSecurityObject(
this,
securityInformation,
securityDescriptor
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs
index 1b3290066..c2038f685 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/LsaPolicyHandle.cs
@@ -45,7 +45,7 @@ public static LsaPolicyHandle LookupPolicyHandle
if (weakRef != null)
{
- weakRef.TryGetTarget(out policyHandle);
+ policyHandle = weakRef.Target;
}
if (policyHandle == null)
@@ -53,10 +53,9 @@ public static LsaPolicyHandle LookupPolicyHandle
System.Threading.Interlocked.Increment(ref _lookupPolicyHandleMisses);
policyHandle = new LsaPolicyHandle(LsaPolicyAccess.LookupNames);
+
if (policyHandle != null)
- {
_lookupPolicyHandle = new WeakReference(policyHandle);
- }
}
return policyHandle;
@@ -86,19 +85,22 @@ public LsaPolicyHandle(LsaPolicyAccess access)
/// The desired access to the policy.
public LsaPolicyHandle(string systemName, LsaPolicyAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes();
+ UnicodeString systemNameStr;
IntPtr handle;
- UnicodeString systemNameStr = new UnicodeString(systemName);
+ systemNameStr = new UnicodeString(systemName);
try
{
- Win32.LsaOpenPolicy(
+ if ((status = Win32.LsaOpenPolicy(
ref systemNameStr,
ref oa,
access,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -115,6 +117,7 @@ public void AddPrivilege(Sid accountSid, string privilege)
public void AddPrivileges(Sid accountSid, string[] privileges)
{
+ NtStatus status;
UnicodeString[] privilegeStrArray = new UnicodeString[privileges.Length];
for (int i = 0; i < privileges.Length; i++)
@@ -122,12 +125,13 @@ public void AddPrivileges(Sid accountSid, string[] privileges)
try
{
- Win32.LsaAddAccountRights(
+ if ((status = Win32.LsaAddAccountRights(
this,
accountSid,
privilegeStrArray,
privilegeStrArray.Length
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -138,15 +142,19 @@ public void AddPrivileges(Sid accountSid, string[] privileges)
public void DeletePrivateData(string name)
{
- UnicodeString nameStr = new UnicodeString(name);
+ NtStatus status;
+ UnicodeString nameStr;
+
+ nameStr = new UnicodeString(name);
try
{
- Win32.LsaStorePrivateData(
+ if ((status = Win32.LsaStorePrivateData(
this,
ref nameStr,
IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -161,13 +169,14 @@ public void DeletePrivateData(string name)
/// The callback for the enumeration.
public void EnumAccounts(EnumAccountsDelegate callback)
{
+ NtStatus status;
int enumerationContext = 0;
IntPtr buffer;
int count;
while (true)
{
- NtStatus status = Win32.LsaEnumerateAccounts(
+ status = Win32.LsaEnumerateAccounts(
this,
ref enumerationContext,
out buffer,
@@ -177,10 +186,10 @@ out count
if (status == NtStatus.NoMoreEntries)
break;
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
- status.ThrowIf();
-
- using (LsaMemoryAlloc bufferAlloc = new LsaMemoryAlloc(buffer))
+ using (var bufferAlloc = new LsaMemoryAlloc(buffer))
{
for (int i = 0; i < count; i++)
{
@@ -200,26 +209,31 @@ out count
/// The callback for the enumeration.
public void EnumAccountsWithPrivilege(string privilegeName, EnumAccountsDelegate callback)
{
+ NtStatus status;
+ UnicodeString privilegeNameStr;
IntPtr buffer;
int count;
- UnicodeString privilegeNameStr = new UnicodeString(privilegeName);
+ privilegeNameStr = new UnicodeString(privilegeName);
try
{
- Win32.LsaEnumerateAccountsWithUserRight(
+ if ((status = Win32.LsaEnumerateAccountsWithUserRight(
this,
ref privilegeNameStr,
out buffer,
out count
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
privilegeNameStr.Dispose();
}
- using (LsaMemoryAlloc bufferAlloc = new LsaMemoryAlloc(buffer))
+ Sid[] sids = new Sid[count];
+
+ using (var bufferAlloc = new LsaMemoryAlloc(buffer))
{
for (int i = 0; i < count; i++)
{
@@ -236,13 +250,14 @@ out count
/// The callback for the enumeration.
public void EnumPrivileges(EnumPrivilegesDelegate callback)
{
+ NtStatus status;
int enumerationContext = 0;
IntPtr buffer;
int count;
while (true)
{
- NtStatus status = Win32.LsaEnumeratePrivileges(
+ status = Win32.LsaEnumeratePrivileges(
this,
ref enumerationContext,
out buffer,
@@ -252,14 +267,14 @@ out count
if (status == NtStatus.NoMoreEntries)
break;
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
- status.ThrowIf();
-
- using (LsaMemoryAlloc bufferAlloc = new LsaMemoryAlloc(buffer))
+ using (var bufferAlloc = new LsaMemoryAlloc(buffer))
{
for (int i = 0; i < count; i++)
{
- if (!callback(new Privilege(bufferAlloc.ReadStruct(0, PolicyPrivilegeDefinition.SizeOf, i).Name.Text)))
+ if (!callback(new Privilege(bufferAlloc.ReadStruct(i).Name.Read())))
return;
}
}
@@ -270,20 +285,17 @@ out count
/// Gets the accounts in the policy. This requires
/// ViewLocalInformation access.
///
- public Sid[] Accounts
+ public Sid[] GetAccounts()
{
- get
- {
- List sids = new List();
+ List sids = new List();
- this.EnumAccounts(sid =>
+ this.EnumAccounts((sid) =>
{
sids.Add(sid);
return true;
});
- return sids.ToArray();
- }
+ return sids.ToArray();
}
///
@@ -296,7 +308,7 @@ public Sid[] GetAccountsWithPrivilege(string privilegeName)
{
List sids = new List();
- this.EnumAccountsWithPrivilege(privilegeName, sid =>
+ this.EnumAccountsWithPrivilege(privilegeName, (sid) =>
{
sids.Add(sid);
return true;
@@ -305,20 +317,17 @@ public Sid[] GetAccountsWithPrivilege(string privilegeName)
return sids.ToArray();
}
- public Privilege[] Privileges
+ public Privilege[] GetPrivileges()
{
- get
- {
- List privileges = new List();
+ List privileges = new List();
- this.EnumPrivileges(privilege =>
- {
- privileges.Add(privilege);
- return true;
- });
+ this.EnumPrivileges((privilege) =>
+ {
+ privileges.Add(privilege);
+ return true;
+ });
- return privileges.ToArray();
- }
+ return privileges.ToArray();
}
public string LookupName(Sid sid)
@@ -354,7 +363,7 @@ public string LookupName(Sid sid, out SidNameUse nameUse, out string domainName)
new IntPtr[] { sid },
out referencedDomains,
out names
- )).IsError())
+ )) >= NtStatus.Error)
{
if (status == NtStatus.NoneMapped)
{
@@ -366,8 +375,8 @@ out names
Win32.Throw(status);
}
- using (LsaMemoryAlloc referencedDomainsAlloc = new LsaMemoryAlloc(referencedDomains))
- using (LsaMemoryAlloc namesAlloc = new LsaMemoryAlloc(names))
+ using (var referencedDomainsAlloc = new LsaMemoryAlloc(referencedDomains))
+ using (var namesAlloc = new LsaMemoryAlloc(names))
{
LsaTranslatedName translatedName = namesAlloc.ReadStruct();
@@ -384,16 +393,16 @@ out names
{
LsaReferencedDomainList domains = referencedDomainsAlloc.ReadStruct();
MemoryRegion trustArray = new MemoryRegion(domains.Domains);
- LsaTrustInformation trustInfo = trustArray.ReadStruct(0, LsaTrustInformation.SizeOf, translatedName.DomainIndex);
+ LsaTrustInformation trustInfo = trustArray.ReadStruct(translatedName.DomainIndex);
- domainName = trustInfo.Name.Text;
+ domainName = trustInfo.Name.Read();
}
else
{
domainName = null;
}
- return translatedName.Name.Text;
+ return translatedName.Name.Read();
}
}
@@ -404,60 +413,68 @@ public string LookupPrivilegeDisplayName(Luid value)
public string LookupPrivilegeDisplayName(string name)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr displayName;
short language;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.LsaLookupPrivilegeDisplayName(
+ if ((status = Win32.LsaLookupPrivilegeDisplayName(
this,
ref nameStr,
out displayName,
out language
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
nameStr.Dispose();
}
- using (LsaMemoryAlloc displayNameAlloc = new LsaMemoryAlloc(displayName))
+ using (var displayNameAlloc = new LsaMemoryAlloc(displayName))
{
- return displayNameAlloc.ReadStruct().Text;
+ return displayNameAlloc.ReadStruct().Read();
}
}
public string LookupPrivilegeName(Luid value)
{
+ NtStatus status;
IntPtr name;
- Win32.LsaLookupPrivilegeName(
+ if ((status = Win32.LsaLookupPrivilegeName(
this,
ref value,
out name
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (LsaMemoryAlloc nameAlloc = new LsaMemoryAlloc(name))
+ using (var nameAlloc = new LsaMemoryAlloc(name))
{
- return nameAlloc.ReadStruct().Text;
+ return nameAlloc.ReadStruct().Read();
}
}
public Luid LookupPrivilegeValue(string name)
{
+ NtStatus status;
+ UnicodeString nameStr;
Luid luid;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.LsaLookupPrivilegeValue(
+ if ((status = Win32.LsaLookupPrivilegeValue(
this,
ref nameStr,
out luid
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -491,10 +508,11 @@ public Sid LookupSid(string name, out string domainName)
public Sid LookupSid(string name, out SidNameUse nameUse, out string domainName)
{
NtStatus status;
+ UnicodeString nameStr;
IntPtr referencedDomains;
IntPtr sids;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
@@ -505,7 +523,7 @@ public Sid LookupSid(string name, out SidNameUse nameUse, out string domainName)
new UnicodeString[] { nameStr },
out referencedDomains,
out sids
- )).IsError())
+ )) >= NtStatus.Error)
{
if (status == NtStatus.NoneMapped)
{
@@ -540,9 +558,9 @@ out sids
{
LsaReferencedDomainList domains = referencedDomainsAlloc.ReadStruct();
MemoryRegion trustArray = new MemoryRegion(domains.Domains);
- LsaTrustInformation trustInfo = trustArray.ReadStruct(0, LsaTrustInformation.SizeOf, translatedSid.DomainIndex);
+ LsaTrustInformation trustInfo = trustArray.ReadStruct(translatedSid.DomainIndex);
- domainName = trustInfo.Name.Text;
+ domainName = trustInfo.Name.Read();
}
else
{
@@ -560,17 +578,21 @@ public void RemovePrivilege(Sid accountSid, string privilege)
public void RemovePrivileges(Sid accountSid)
{
- Win32.LsaRemoveAccountRights(
+ NtStatus status;
+
+ if ((status = Win32.LsaRemoveAccountRights(
this,
accountSid,
true,
null,
0
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void RemovePrivileges(Sid accountSid, string[] privileges)
{
+ NtStatus status;
UnicodeString[] privilegeStrArray = new UnicodeString[privileges.Length];
for (int i = 0; i < privileges.Length; i++)
@@ -578,13 +600,14 @@ public void RemovePrivileges(Sid accountSid, string[] privileges)
try
{
- Win32.LsaRemoveAccountRights(
+ if ((status = Win32.LsaRemoveAccountRights(
this,
accountSid,
false,
privilegeStrArray,
privilegeStrArray.Length
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -595,41 +618,47 @@ public void RemovePrivileges(Sid accountSid, string[] privileges)
public string RetrievePrivateData(string name)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr privateData;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.LsaRetrievePrivateData(
+ if ((status = Win32.LsaRetrievePrivateData(
this,
ref nameStr,
out privateData
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
nameStr.Dispose();
}
- using (LsaMemoryAlloc privateDataAlloc = new LsaMemoryAlloc(privateData))
- {
- return privateDataAlloc.ReadStruct().Text;
- }
+ using (var privateDataAlloc = new LsaMemoryAlloc(privateData))
+ return privateDataAlloc.ReadStruct().Read();
}
public void StorePrivateData(string name, string privateData)
{
- UnicodeString nameStr = new UnicodeString(name);
- UnicodeString privateDataStr = new UnicodeString(privateData);
+ NtStatus status;
+ UnicodeString nameStr;
+ UnicodeString privateDataStr;
+
+ nameStr = new UnicodeString(name);
+ privateDataStr = new UnicodeString(privateData);
try
{
- Win32.LsaStorePrivateData(
+ if ((status = Win32.LsaStorePrivateData(
this,
ref nameStr,
ref privateDataStr
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/LsaSecretHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/LsaSecretHandle.cs
index 77ada9075..7657956bb 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/LsaSecretHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/LsaSecretHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -33,18 +34,21 @@ public sealed class LsaSecretHandle : LsaHandle
{
public static LsaSecretHandle Create(LsaSecretAccess access, LsaPolicyHandle policyHandle, string name)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr handle;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.LsaCreateSecret(
+ if ((status = Win32.LsaCreateSecret(
policyHandle,
ref nameStr,
access,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -60,18 +64,21 @@ private LsaSecretHandle(IntPtr handle, bool owned)
public LsaSecretHandle(LsaPolicyHandle policyHandle, string name, LsaSecretAccess access)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr handle;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.LsaOpenSecret(
+ if ((status = Win32.LsaOpenSecret(
policyHandle,
ref nameStr,
access,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -106,25 +113,27 @@ public void Query(
out DateTime oldValueSetTime
)
{
+ NtStatus status;
IntPtr currentValueStr;
long currentValueSetTimeLong;
IntPtr oldValueStr;
long oldValueSetTimeLong;
- Win32.LsaQuerySecret(
+ if ((status = Win32.LsaQuerySecret(
this,
out currentValueStr,
out currentValueSetTimeLong,
out oldValueStr,
out oldValueSetTimeLong
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (LsaMemoryAlloc currentValueStrAlloc = new LsaMemoryAlloc(currentValueStr))
- using (LsaMemoryAlloc oldValueStrAlloc = new LsaMemoryAlloc(oldValueStr))
+ using (var currentValueStrAlloc = new LsaMemoryAlloc(currentValueStr))
+ using (var oldValueStrAlloc = new LsaMemoryAlloc(oldValueStr))
{
- currentValue = currentValueStrAlloc.ReadStruct().Text;
+ currentValue = currentValueStrAlloc.ReadStruct().Read();
currentValueSetTime = DateTime.FromFileTime(currentValueSetTimeLong);
- oldValue = oldValueStrAlloc.ReadStruct().Text;
+ oldValue = oldValueStrAlloc.ReadStruct().Read();
oldValueSetTime = DateTime.FromFileTime(oldValueSetTimeLong);
}
}
@@ -136,16 +145,21 @@ public void Set(string currentValue)
public void Set(string currentValue, string oldValue)
{
- UnicodeString currentValueStr = new UnicodeString(currentValue);
- UnicodeString oldValueStr = new UnicodeString(oldValue);
+ NtStatus status;
+ UnicodeString currentValueStr;
+ UnicodeString oldValueStr;
+
+ currentValueStr = new UnicodeString(currentValue);
+ oldValueStr = new UnicodeString(oldValue);
try
{
- Win32.LsaSetSecret(
+ if ((status = Win32.LsaSetSecret(
this,
ref currentValueStr,
ref oldValueStr
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/MailslotHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/MailslotHandle.cs
index 45758ae47..f3b62c173 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/MailslotHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/MailslotHandle.cs
@@ -56,13 +56,14 @@ public static MailslotHandle Create(
FileCreateOptions createOptions
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
IoStatusBlock isb;
IntPtr handle;
try
{
- Win32.NtCreateMailslotFile(
+ if ((status = Win32.NtCreateMailslotFile(
out handle,
access,
ref oa,
@@ -71,7 +72,8 @@ FileCreateOptions createOptions
quota,
maxMessageSize,
ref readTimeout
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/MutantHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/MutantHandle.cs
index f10b0362b..9e9fd229b 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/MutantHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/MutantHandle.cs
@@ -21,8 +21,11 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
+using System.Runtime.InteropServices;
namespace ProcessHacker.Native.Objects
{
@@ -40,12 +43,14 @@ public static MutantHandle Create(MutantAccess access, string name, bool initial
public static MutantHandle Create(MutantAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, bool initialOwner)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateMutant(out handle, access, ref oa, initialOwner).ThrowIf();
+ if ((status = Win32.NtCreateMutant(out handle, access, ref oa, initialOwner)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -66,12 +71,14 @@ private MutantHandle(IntPtr handle, bool owned)
public MutantHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, MutantAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenMutant(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenMutant(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -85,49 +92,39 @@ public MutantHandle(string name, MutantAccess access)
: this(name, 0, null, access)
{ }
- public MutantBasicInformation BasicInformation
+ public MutantBasicInformation GetBasicInformation()
{
- get
- {
- MutantBasicInformation mbi;
- int retLength;
-
- Win32.NtQueryMutant(
- this,
- MutantInformationClass.MutantBasicInformation,
- out mbi,
- MutantBasicInformation.SizeOf,
- out retLength
- ).ThrowIf();
-
- return mbi;
- }
+ NtStatus status;
+ MutantBasicInformation mbi;
+ int retLength;
+
+ if ((status = Win32.NtQueryMutant(this, MutantInformationClass.MutantBasicInformation,
+ out mbi, Marshal.SizeOf(typeof(MutantBasicInformation)), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return mbi;
}
- public MutantOwnerInformation OwnerInformation
+ public MutantOwnerInformation GetOwnerInformation()
{
- get
- {
- MutantOwnerInformation moi;
- int retLength;
-
- Win32.NtQueryMutant(
- this,
- MutantInformationClass.MutantOwnerInformation,
- out moi,
- MutantOwnerInformation.SizeOf,
- out retLength
- ).ThrowIf();
-
- return moi;
- }
+ NtStatus status;
+ MutantOwnerInformation moi;
+ int retLength;
+
+ if ((status = Win32.NtQueryMutant(this, MutantInformationClass.MutantOwnerInformation,
+ out moi, Marshal.SizeOf(typeof(MutantOwnerInformation)), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return moi;
}
public int Release()
{
+ NtStatus status;
int previousCount;
- Win32.NtReleaseMutant(this, out previousCount).ThrowIf();
+ if ((status = Win32.NtReleaseMutant(this, out previousCount)) >= NtStatus.Error)
+ Win32.Throw(status);
return previousCount;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/NamedPipeHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/NamedPipeHandle.cs
index 8d7659360..94075162c 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/NamedPipeHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/NamedPipeHandle.cs
@@ -89,6 +89,7 @@ public static NamedPipeHandle Create(
long defaultTimeout
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
IoStatusBlock isb;
IntPtr handle;
@@ -99,7 +100,7 @@ long defaultTimeout
try
{
- Win32.NtCreateNamedPipeFile(
+ if ((status = Win32.NtCreateNamedPipeFile(
out handle,
access,
ref oa,
@@ -114,7 +115,8 @@ long defaultTimeout
inboundQuota,
outboundQuota,
ref defaultTimeout
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -153,33 +155,33 @@ public static bool Wait(string name, long timeout)
public static bool Wait(string name, long timeout, bool relative)
{
- using (FileHandle npfsHandle = new FileHandle(
+ using (var npfsHandle = new FileHandle(
Win32.NamedPipePath + "\\",
FileShareMode.ReadWrite,
FileCreateOptions.SynchronousIoNonAlert,
FileAccess.ReadAttributes | (FileAccess)StandardRights.Synchronize
))
{
- using (MemoryAlloc data = new MemoryAlloc(FilePipeWaitForBuffer.NameOffset + name.Length * 2))
+ using (var data = new MemoryAlloc(FilePipeWaitForBuffer.NameOffset + name.Length * 2))
{
- FilePipeWaitForBuffer info = new FilePipeWaitForBuffer
- {
- Timeout = timeout,
- TimeoutSpecified = true,
- NameLength = name.Length * 2
- };
-
- data.WriteStruct(info);
+ FilePipeWaitForBuffer info = new FilePipeWaitForBuffer();
+
+ info.Timeout = timeout;
+ info.TimeoutSpecified = true;
+ info.NameLength = name.Length * 2;
+ data.WriteStruct(info);
data.WriteUnicodeString(FilePipeWaitForBuffer.NameOffset, name);
+ NtStatus status;
int returnLength;
- NtStatus status = npfsHandle.FsControl(FsCtlWait, data, data.Size, IntPtr.Zero, 0, out returnLength);
+ status = npfsHandle.FsControl(FsCtlWait, data, data.Size, IntPtr.Zero, 0, out returnLength);
if (status == NtStatus.IoTimeout)
return false;
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return true;
}
@@ -253,7 +255,8 @@ public bool EndListen(AsyncIoContext asyncContext)
if (asyncContext.Status == NtStatus.PipeConnected)
return true;
- asyncContext.StatusBlock.Status.ThrowIf();
+ if (asyncContext.StatusBlock.Status >= NtStatus.Error)
+ Win32.Throw(asyncContext.StatusBlock.Status);
return false;
}
@@ -268,31 +271,19 @@ public void Disconnect()
this.FsControl(FsCtlDisconnect, IntPtr.Zero, 0, IntPtr.Zero, 0);
}
- private FilePipeInformation Information
+ private FilePipeInformation GetInformation()
{
- get
- {
- return this.QueryStruct(
- FileInformationClass.FilePipeInformation,
- FilePipeInformation.SizeOf
- );
- }
+ return this.QueryStruct(FileInformationClass.FilePipeInformation);
}
- private FilePipeLocalInformation LocalInformation
+ private FilePipeLocalInformation GetLocalInformation()
{
- get
- {
- return this.QueryStruct(
- FileInformationClass.FilePipeLocalInformation,
- FilePipeLocalInformation.SizeOf
- );
- }
+ return this.QueryStruct(FileInformationClass.FilePipeLocalInformation);
}
- public PipeType PipeType
+ public PipeType GetPipeType()
{
- get { return this.Information.ReadMode; }
+ return this.GetInformation().ReadMode;
}
public void ImpersonateClient()
@@ -302,14 +293,16 @@ public void ImpersonateClient()
public bool Listen()
{
+ NtStatus status;
int returnLength;
- NtStatus status = this.FsControl(FsCtlListen, IntPtr.Zero, 0, IntPtr.Zero, 0, out returnLength);
+ status = this.FsControl(FsCtlListen, IntPtr.Zero, 0, IntPtr.Zero, 0, out returnLength);
if (status == NtStatus.PipeConnected)
return true;
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return false;
}
@@ -374,7 +367,7 @@ public int Peek(byte[] buffer, int offset, int length, out int bytesAvailable, o
public int Peek(IntPtr buffer, int length, out int bytesAvailable, out int bytesLeftInMessage)
{
- using (MemoryAlloc data = new MemoryAlloc(FilePipePeekBuffer.DataOffset + length))
+ using (var data = new MemoryAlloc(FilePipePeekBuffer.DataOffset + length))
{
NtStatus status;
int returnLength;
@@ -386,12 +379,14 @@ public int Peek(IntPtr buffer, int length, out int bytesAvailable, out int bytes
if (status == NtStatus.BufferOverflow)
status = NtStatus.Success;
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
FilePipePeekBuffer info = data.ReadStruct();
+ int bytesRead;
bytesAvailable = info.ReadDataAvailable;
- int bytesRead = returnLength - FilePipePeekBuffer.DataOffset;
+ bytesRead = returnLength - FilePipePeekBuffer.DataOffset;
bytesLeftInMessage = info.MessageLength - bytesRead;
if (buffer != IntPtr.Zero)
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/NativeHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/NativeHandle.cs
index 99031c6d4..2f60fdfb0 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/NativeHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/NativeHandle.cs
@@ -90,19 +90,23 @@ public static NtStatus WaitAny(ISynchronizable[] objects, bool alertable, long t
private static NtStatus WaitForMultipleObjects(ISynchronizable[] objects, WaitType waitType, bool alertable, long timeout, bool relative)
{
+ NtStatus status;
IntPtr[] handles = new IntPtr[objects.Length];
long realTimeout = relative ? -timeout : timeout;
for (int i = 0; i < objects.Length; i++)
handles[i] = objects[i].Handle;
- return Win32.NtWaitForMultipleObjects(
+ if ((status = Win32.NtWaitForMultipleObjects(
handles.Length,
handles,
waitType,
alertable,
ref realTimeout
- );
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
public static implicit operator int(NativeHandle handle)
@@ -220,80 +224,66 @@ public override int GetHashCode()
/// Gets the handle's name.
///
/// A string.
- public virtual string ObjectName
+ public virtual string GetObjectName()
{
- get
- {
- int retLength;
+ NtStatus status;
+ int retLength;
- Win32.NtQueryObject(
- this,
- ObjectInformationClass.ObjectNameInformation,
- IntPtr.Zero,
- 0,
- out retLength
- );
+ status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectNameInformation,
+ IntPtr.Zero, 0, out retLength);
- if (retLength > 0)
+ if (retLength > 0)
+ {
+ using (MemoryAlloc oniMem = new MemoryAlloc(retLength))
{
- using (MemoryAlloc oniMem = new MemoryAlloc(retLength))
- {
- Win32.NtQueryObject(
- this,
- ObjectInformationClass.ObjectNameInformation,
- oniMem,
- oniMem.Size,
- out retLength
- ).ThrowIf();
-
- ObjectNameInformation oni = oniMem.ReadStruct();
-
- return oni.Name.Text;
- }
- }
+ if ((status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectNameInformation,
+ oniMem, oniMem.Size, out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
- return null;
+ var oni = oniMem.ReadStruct();
+
+ return oni.Name.Read();
+ }
+ }
+ else
+ {
+ Win32.Throw(status);
}
+
+ return null;
}
///
/// Gets the handle's type name.
///
/// A string.
- public virtual string ObjectTypeName
+ public virtual string GetObjectTypeName()
{
- get
- {
- int retLength;
+ NtStatus status;
+ int retLength;
- Win32.NtQueryObject(
- this,
- ObjectInformationClass.ObjectTypeInformation,
- IntPtr.Zero,
- 0,
- out retLength
- );
+ status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectTypeInformation,
+ IntPtr.Zero, 0, out retLength);
- if (retLength > 0)
+ if (retLength > 0)
+ {
+ using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
{
- using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
- {
- Win32.NtQueryObject(
- this,
- ObjectInformationClass.ObjectTypeInformation,
- otiMem,
- otiMem.Size,
- out retLength
- ).ThrowIf();
-
- ObjectTypeInformation oni = otiMem.ReadStruct();
-
- return oni.Name.Text;
- }
- }
+ if ((status = Win32.NtQueryObject(this, ObjectInformationClass.ObjectTypeInformation,
+ otiMem, otiMem.Size, out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
- return null;
+ var oni = otiMem.ReadStruct();
+
+ return oni.Name.Read();
+ }
+ }
+ else
+ {
+ Win32.Throw(status);
}
+
+ return null;
}
///
@@ -322,7 +312,10 @@ protected SecurityDescriptor GetSecurity(SeObjectType objectType, SecurityInform
///
public virtual void MakeObjectPermanent()
{
- Win32.NtMakePermanentObject(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtMakePermanentObject(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -332,16 +325,10 @@ public virtual void MakeObjectPermanent()
///
public virtual void MakeObjectTemporary()
{
- Win32.NtMakeTemporaryObject(this).ThrowIf();
- }
+ NtStatus status;
- ///
- /// Marks the handle as invalid. This method must only be called from
- /// within a derived class constructor.
- ///
- protected bool IsValid
- {
- get { return this._handle != IntPtr.Zero; }
+ if ((status = Win32.NtMakeTemporaryObject(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -414,14 +401,18 @@ public virtual NtStatus SignalAndWait(ISynchronizable waitObject, bool alertable
///
public virtual NtStatus SignalAndWait(ISynchronizable waitObject, bool alertable, long timeout, bool relative)
{
+ NtStatus status;
long realTimeout = relative ? -timeout : timeout;
- return Win32.NtSignalAndWaitForSingleObject(
+ if ((status = Win32.NtSignalAndWaitForSingleObject(
this,
waitObject.Handle,
alertable,
- ref realTimeout
- );
+ ref timeout
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
///
@@ -522,20 +513,25 @@ public NtStatus Wait(long timeout, bool relative)
/// Whether the timeout value is relative.
public virtual NtStatus Wait(bool alertable, long timeout, bool relative)
{
+ NtStatus status;
long realTimeout = relative ? -timeout : timeout;
- return Win32.NtWaitForSingleObject(
+ if ((status = Win32.NtWaitForSingleObject(
this,
alertable,
ref realTimeout
- );
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
}
///
/// Represents a generic Windows handle which acts as a kernel handle by default.
///
- public class NativeHandle : NativeHandle where TAccess : struct
+ public class NativeHandle : NativeHandle
+ where TAccess : struct
{
///
/// Creates a new, invalid handle. You must set the handle using the Handle property.
@@ -571,16 +567,8 @@ public NativeHandle(IntPtr handle, TAccess access)
{
IntPtr newHandle;
- Win32.NtDuplicateObject(
- ProcessHandle.Current,
- handle,
- ProcessHandle.Current,
- out newHandle,
- (int)Convert.ChangeType(access, typeof(int)),
- 0,
- 0
- );
-
+ Win32.DuplicateObject(ProcessHandle.Current, handle, ProcessHandle.Current, out newHandle,
+ (int)Convert.ChangeType(access, typeof(int)), 0, 0);
this.Handle = newHandle;
}
@@ -594,16 +582,8 @@ public NativeHandle(ProcessHandle processHandle, IntPtr handle, TAccess access)
{
IntPtr newHandle;
- Win32.NtDuplicateObject(
- processHandle,
- handle,
- ProcessHandle.Current,
- out newHandle,
- (int)Convert.ChangeType(access, typeof(int)),
- 0,
- 0
- );
-
+ Win32.DuplicateObject(processHandle, handle, ProcessHandle.Current, out newHandle,
+ (int)Convert.ChangeType(access, typeof(int)), 0, 0);
this.Handle = newHandle;
}
@@ -615,16 +595,8 @@ public void ChangeAccess(TAccess access)
{
IntPtr newHandle;
- Win32.NtDuplicateObject(
- ProcessHandle.Current,
- this,
- ProcessHandle.Current,
- out newHandle,
- (int)Convert.ChangeType(access, typeof(int)),
- 0,
- 0
- );
-
+ Win32.DuplicateObject(ProcessHandle.Current, this, ProcessHandle.Current, out newHandle,
+ (int)Convert.ChangeType(access, typeof(int)), 0, 0);
this.SwapHandle(newHandle);
}
@@ -648,6 +620,7 @@ public class GenericHandle : NativeHandle
/// Creates a new, invalid handle. You must set the handle using the Handle property.
///
protected GenericHandle()
+ : base()
{ }
///
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/PortComHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/PortComHandle.cs
index c52d814cd..a032c3a45 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/PortComHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/PortComHandle.cs
@@ -31,13 +31,15 @@ public sealed class PortComHandle : NativeHandle
{
public static PortComHandle Connect(string portName)
{
+ NtStatus status;
UnicodeString portNameStr = new UnicodeString(portName);
- SecurityQualityOfService securityQos = new SecurityQualityOfService(SecurityImpersonationLevel.SecurityImpersonation, true, false);
+ SecurityQualityOfService securityQos =
+ new SecurityQualityOfService(SecurityImpersonationLevel.SecurityImpersonation, true, false);
IntPtr handle;
try
{
- Win32.NtConnectPort(
+ if ((status = Win32.NtConnectPort(
out handle,
ref portNameStr,
ref securityQos,
@@ -46,7 +48,8 @@ public static PortComHandle Connect(string portName)
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -62,9 +65,12 @@ internal PortComHandle(IntPtr handle, bool owned)
public void Reply(PortMessage message)
{
- using (MemoryAlloc messageMemory = message.ToMemory())
+ NtStatus status;
+
+ using (var messageMemory = message.ToMemory())
{
- Win32.NtReplyPort(this, messageMemory).ThrowIf();
+ if ((status = Win32.NtReplyPort(this, messageMemory)) >= NtStatus.Error)
+ Win32.Throw(status);
message.SetHeader(messageMemory);
}
@@ -77,7 +83,10 @@ public PortMessage ReplyWaitReceive()
public PortMessage ReplyWaitReceive(PortMessage message)
{
- using (MemoryAlloc buffer = PortMessage.AllocateBuffer())
+ NtStatus status;
+ IntPtr context;
+
+ using (var buffer = PortMessage.AllocateBuffer())
{
MemoryAlloc messageMemory = null;
@@ -86,14 +95,13 @@ public PortMessage ReplyWaitReceive(PortMessage message)
try
{
- IntPtr context;
-
- Win32.NtReplyWaitReceivePort(
+ if ((status = Win32.NtReplyWaitReceivePort(
this,
out context,
messageMemory ?? IntPtr.Zero,
buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (message != null)
message.SetHeader(messageMemory);
@@ -110,12 +118,15 @@ public PortMessage ReplyWaitReceive(PortMessage message)
public PortMessage ReplyWaitReply(PortMessage message)
{
- using (MemoryAlloc messageMemory = message.ToMemory())
+ NtStatus status;
+
+ using (var messageMemory = message.ToMemory())
{
- Win32.NtReplyWaitReplyPort(
+ if ((status = Win32.NtReplyWaitReplyPort(
this,
messageMemory
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new PortMessage(messageMemory);
}
@@ -123,9 +134,12 @@ public PortMessage ReplyWaitReply(PortMessage message)
public void Request(PortMessage message)
{
- using (MemoryAlloc messageMemory = message.ToMemory())
+ NtStatus status;
+
+ using (var messageMemory = message.ToMemory())
{
- Win32.NtRequestPort(this, messageMemory).ThrowIf();
+ if ((status = Win32.NtRequestPort(this, messageMemory)) >= NtStatus.Error)
+ Win32.Throw(status);
message.SetHeader(messageMemory);
}
@@ -133,14 +147,17 @@ public void Request(PortMessage message)
public PortMessage RequestWaitReply(PortMessage message)
{
- using (MemoryAlloc buffer = PortMessage.AllocateBuffer())
- using (MemoryAlloc messageMemory = message.ToMemory())
+ NtStatus status;
+
+ using (var buffer = PortMessage.AllocateBuffer())
+ using (var messageMemory = message.ToMemory())
{
- Win32.NtRequestWaitReplyPort(
+ if ((status = Win32.NtRequestWaitReplyPort(
this,
messageMemory,
buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
message.SetHeader(messageMemory);
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/PortHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/PortHandle.cs
index 5abd9caae..ca8032f92 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/PortHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/PortHandle.cs
@@ -54,18 +54,20 @@ public static PortHandle Create(
int maxPoolUsage
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreatePort(
+ if ((status = Win32.NtCreatePort(
out handle,
ref oa,
maxConnectionInfoLength,
maxMessageLength,
maxPoolUsage
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -100,18 +102,20 @@ public static PortHandle CreateWaitable(
int maxPoolUsage
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateWaitablePort(
+ if ((status = Win32.NtCreateWaitablePort(
out handle,
ref oa,
maxConnectionInfoLength,
maxMessageLength,
maxPoolUsage
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -127,36 +131,44 @@ private PortHandle(IntPtr handle, bool owned)
public PortComHandle AcceptConnect(PortMessage message, bool accept)
{
+ NtStatus status;
IntPtr portHandle;
- using (MemoryAlloc messageMemory = message.ToMemory())
+ using (var messageMemory = message.ToMemory())
{
- Win32.NtAcceptConnectPort(
+ if ((status = Win32.NtAcceptConnectPort(
out portHandle,
IntPtr.Zero,
messageMemory,
accept,
IntPtr.Zero,
IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (!NativeHandle.IsInvalid(portHandle))
return new PortComHandle(portHandle, true);
-
- return null;
+ else
+ return null;
}
}
public void CompleteConnect()
{
- Win32.NtCompleteConnectPort(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtCompleteConnectPort(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public PortMessage Listen()
{
- using (MemoryAlloc buffer = PortMessage.AllocateBuffer())
+ NtStatus status;
+
+ using (var buffer = PortMessage.AllocateBuffer())
{
- Win32.NtListenPort(this, buffer).ThrowIf();
+ if ((status = Win32.NtListenPort(this, buffer)) >= NtStatus.Error)
+ Win32.Throw(status);
return new PortMessage(buffer);
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs
index b9cc3de4a..c3dbd7468 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/ProcessHandle.cs
@@ -23,6 +23,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Runtime.InteropServices;
using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -106,12 +107,13 @@ public static ProcessHandle Create(
DebugObjectHandle debugPort
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateProcess(
+ if ((status = Win32.NtCreateProcess(
out handle,
access,
ref oa,
@@ -120,7 +122,8 @@ DebugObjectHandle debugPort
sectionHandle ?? IntPtr.Zero,
debugPort ?? IntPtr.Zero,
IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -169,24 +172,36 @@ out ThreadHandle threadHandle
)
{
ProcessHandle phandle;
+ ThreadHandle thandle;
SectionImageInformation imageInfo;
// If we don't have a desktop, use the current one.
if (startupInfo.Desktop == null)
- startupInfo.Desktop = Current.GetPebString(PebOffset.DesktopName);
+ startupInfo.Desktop = ProcessHandle.Current.GetPebString(PebOffset.DesktopName);
// Open the file, create a section, and create a process.
- using (FileHandle fhandle = new FileHandle(fileName, FileShareMode.Read | FileShareMode.Delete, FileAccess.Execute | (FileAccess)StandardRights.Synchronize))
- using (SectionHandle shandle = SectionHandle.Create(SectionAccess.All, SectionAttributes.Image, MemoryProtection.Execute, fhandle))
+ using (var fhandle = new FileHandle(
+ fileName,
+ FileShareMode.Read | FileShareMode.Delete,
+ FileAccess.Execute | (FileAccess)StandardRights.Synchronize
+ ))
{
- imageInfo = shandle.GetImageInformation();
+ using (var shandle = SectionHandle.Create(
+ SectionAccess.All,
+ SectionAttributes.Image,
+ MemoryProtection.Execute,
+ fhandle
+ ))
+ {
+ imageInfo = shandle.GetImageInformation();
- phandle = Create(
- ProcessAccess.All,
- parentProcess,
- inheritHandles,
- shandle
- );
+ phandle = Create(
+ ProcessAccess.All,
+ parentProcess,
+ inheritHandles,
+ shandle
+ );
+ }
}
IntPtr peb = phandle.GetBasicInformation().PebBaseAddress;
@@ -197,21 +212,21 @@ out ThreadHandle threadHandle
peb,
creationFlags,
FileUtils.GetFileName(fileName),
- Current.GetPebString(PebOffset.DllPath),
+ ProcessHandle.Current.GetPebString(PebOffset.DllPath),
currentDirectory,
fileName,
environment,
- !string.IsNullOrEmpty(startupInfo.Title) ? startupInfo.Title : fileName,
- !string.IsNullOrEmpty(startupInfo.Desktop) ? startupInfo.Desktop : string.Empty,
- !string.IsNullOrEmpty(startupInfo.Reserved) ? startupInfo.Reserved : string.Empty,
- string.Empty,
+ startupInfo.Title != null ? startupInfo.Title : fileName,
+ startupInfo.Desktop != null ? startupInfo.Desktop : "",
+ startupInfo.Reserved != null ? startupInfo.Reserved : "",
+ "",
ref startupInfo
);
// TODO: Duplicate the console handles (stdin, stdout, stderr).
// Create the initial thread.
- ThreadHandle thandle = ThreadHandle.CreateUserThread(
+ thandle = ThreadHandle.CreateUserThread(
phandle,
true,
imageInfo.StackCommit.Increment(imageInfo.StackReserved).ToInt32(),
@@ -225,23 +240,24 @@ out clientId
if (notifyCsr)
{
- BaseCreateProcessMsg processMsg = new BaseCreateProcessMsg
- {
- ProcessHandle = phandle,
- ThreadHandle = thandle,
- ClientId = clientId,
- CreationFlags = creationFlags
- };
+ BaseCreateProcessMsg processMsg = new BaseCreateProcessMsg();
+
+ processMsg.ProcessHandle = phandle;
+ processMsg.ThreadHandle = thandle;
+ processMsg.ClientId = clientId;
+ processMsg.CreationFlags = creationFlags;
- if ((creationFlags & (ProcessCreationFlags.DebugProcess | ProcessCreationFlags.DebugOnlyThisProcess)) != 0)
+ if ((creationFlags & (ProcessCreationFlags.DebugProcess |
+ ProcessCreationFlags.DebugOnlyThisProcess)) != 0)
{
- NtStatus status = Win32.DbgUiConnectToDbg();
+ NtStatus status;
+
+ status = Win32.DbgUiConnectToDbg();
- if (status.IsError())
+ if (status >= NtStatus.Error)
{
phandle.Terminate(status);
-
- status.Throw();
+ Win32.Throw(status);
}
processMsg.DebuggerClientId = ThreadHandle.GetCurrentCid();
@@ -251,28 +267,30 @@ out clientId
// hourglass cursor on.
if (imageInfo.ImageSubsystem == 2)
processMsg.ProcessHandle = processMsg.ProcessHandle.Or((1 | 2).ToIntPtr());
-
// We still have to honor the startup info settings, though.
- if (startupInfo.Flags.HasFlag(StartupFlags.ForceOnFeedback))
+ if ((startupInfo.Flags & StartupFlags.ForceOnFeedback) ==
+ StartupFlags.ForceOnFeedback)
processMsg.ProcessHandle = processMsg.ProcessHandle.Or((1).ToIntPtr());
-
- if (startupInfo.Flags.HasFlag(StartupFlags.ForceOffFeedback))
+ if ((startupInfo.Flags & StartupFlags.ForceOffFeedback) ==
+ StartupFlags.ForceOffFeedback)
processMsg.ProcessHandle = processMsg.ProcessHandle.And((1).ToIntPtr().Not());
- using (MemoryAlloc data = new MemoryAlloc(CsrApiMsg.ApiMessageDataOffset + BaseCreateProcessMsg.SizeOf))
+ using (var data = new MemoryAlloc(
+ CsrApiMsg.ApiMessageDataOffset + Marshal.SizeOf(typeof(BaseCreateProcessMsg))
+ ))
{
- data.WriteStruct(CsrApiMsg.ApiMessageDataOffset, BaseCreateProcessMsg.SizeOf, 0, processMsg);
+ data.WriteStruct(CsrApiMsg.ApiMessageDataOffset, 0, processMsg);
Win32.CsrClientCallServer(
data,
IntPtr.Zero,
Win32.CsrMakeApiNumber(Win32.BaseSrvServerDllIndex, (int)BaseSrvApiNumber.BasepCreateProcess),
- BaseCreateProcessMsg.SizeOf
+ Marshal.SizeOf(typeof(BaseCreateProcessMsg))
);
NtStatus status = (NtStatus)data.ReadStruct().ReturnValue;
- if (status.IsError())
+ if (status >= NtStatus.Error)
{
phandle.Terminate(status);
Win32.Throw(status);
@@ -290,11 +308,12 @@ out clientId
public static ProcessHandle CreateUserProcess(string fileName, out ClientId clientId, out ThreadHandle threadHandle)
{
+ NtStatus status;
UnicodeString fileNameStr = new UnicodeString(fileName);
RtlUserProcessParameters processParams = new RtlUserProcessParameters();
RtlUserProcessInformation processInfo;
- processParams.Length = RtlUserProcessParameters.SizeOf;
+ processParams.Length = Marshal.SizeOf(processParams);
processParams.MaximumLength = processParams.Length;
processParams.ImagePathName = new UnicodeString(fileName);
processParams.CommandLine = new UnicodeString(fileName);
@@ -303,7 +322,7 @@ public static ProcessHandle CreateUserProcess(string fileName, out ClientId clie
try
{
- Win32.RtlCreateUserProcess(
+ if ((status = Win32.RtlCreateUserProcess(
ref fileNameStr,
0,
ref processParams,
@@ -314,7 +333,8 @@ public static ProcessHandle CreateUserProcess(string fileName, out ClientId clie
IntPtr.Zero,
IntPtr.Zero,
out processInfo
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
clientId = processInfo.ClientId;
threadHandle = new ThreadHandle(processInfo.Thread, true);
@@ -344,7 +364,7 @@ out ThreadHandle threadHandle
{
ProcessInformation processInformation;
- startupInfo.Size = StartupInfo.SizeOf;
+ startupInfo.Size = Marshal.SizeOf(typeof(StartupInfo));
if (!Win32.CreateProcess(
applicationName,
@@ -381,7 +401,7 @@ out ThreadHandle threadHandle
{
ProcessInformation processInformation;
- startupInfo.Size = StartupInfo.SizeOf;
+ startupInfo.Size = Marshal.SizeOf(typeof(StartupInfo));
if (!Win32.CreateProcessAsUser(
tokenHandle,
@@ -428,9 +448,9 @@ public static ProcessHandle GetCurrent()
/// Gets the ID of the current process.
///
/// The ID of the current process.
- public static int CurrentId
+ public static int GetCurrentId()
{
- get { return Win32.GetCurrentProcessId(); }
+ return Win32.GetCurrentProcessId();
}
///
@@ -506,7 +526,40 @@ public static ProcessHandle[] OpenByName(string processName, ProcessAccess acces
/// A handle.
public static ProcessHandle OpenCurrent(ProcessAccess access)
{
- return new ProcessHandle(CurrentId, access);
+ return new ProcessHandle(GetCurrentId(), access);
+ }
+
+ public static ProcessHandle OpenWithAnyAccess(int pid)
+ {
+ try
+ {
+ return new ProcessHandle(pid, OSVersion.MinProcessQueryInfoAccess);
+ }
+ catch
+ {
+ try
+ {
+ return new ProcessHandle(pid, (ProcessAccess)StandardRights.Synchronize);
+ }
+ catch
+ {
+ try
+ {
+ return new ProcessHandle(pid, (ProcessAccess)StandardRights.ReadControl);
+ }
+ catch
+ {
+ try
+ {
+ return new ProcessHandle(pid, (ProcessAccess)StandardRights.WriteDac);
+ }
+ catch
+ {
+ return new ProcessHandle(pid, (ProcessAccess)StandardRights.WriteOwner);
+ }
+ }
+ }
+ }
}
private ProcessHandle(IntPtr handle, bool owned)
@@ -529,11 +582,11 @@ public ProcessHandle(int pid)
public ProcessHandle(int pid, ProcessAccess access)
{
// If we have KPH, use it.
- if (KProcessHacker2.Instance.KphIsConnected)
+ if (KProcessHacker.Instance != null)
{
try
{
- this.Handle = KProcessHacker2.Instance.KphOpenProcess(pid, access);
+ this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenProcess(pid, access));
}
catch (WindowsException)
{
@@ -541,7 +594,9 @@ public ProcessHandle(int pid, ProcessAccess access)
// some part of ObReferenceObjectByHandle is hooked. We can
// open the process with SYNCHRONIZE access and set the granted access
// using KPH.
- this.Handle = KProcessHacker2.Instance.KphOpenProcess(pid, (ProcessAccess)StandardRights.Synchronize);
+ this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenProcess(pid,
+ (ProcessAccess)StandardRights.Synchronize));
+ KProcessHacker.Instance.KphSetHandleGrantedAccess(this.Handle, (int)access);
}
}
else
@@ -556,6 +611,19 @@ public ProcessHandle(int pid, ProcessAccess access)
}
}
+ ///
+ /// Opens a thread's process.
+ ///
+ /// A handle to a thread.
+ /// The desired access to the process.
+ public ProcessHandle(ThreadHandle threadHandle, ProcessAccess access)
+ {
+ if (KProcessHacker.Instance == null)
+ throw new NotSupportedException();
+
+ this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenThreadProcess(threadHandle, access));
+ }
+
///
/// Opens a process.
///
@@ -574,31 +642,34 @@ public ProcessHandle(
ProcessAccess access
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
// NtOpenProcess fails when both a client ID and a name is specified.
- if (!string.IsNullOrEmpty(name))
+ if (name != null)
{
// Name specified, don't specify a CID.
- Win32.NtOpenProcess(
+ if ((status = Win32.NtOpenProcess(
out handle,
access,
ref oa,
IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
else
{
// No name, specify a CID.
- Win32.NtOpenProcess(
+ if ((status = Win32.NtOpenProcess(
out handle,
access,
ref oa,
ref clientId
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
finally
@@ -680,14 +751,17 @@ public IntPtr AllocateMemory(IntPtr baseAddress, int size, MemoryFlags type, Mem
/// The base address of the allocated pages.
public IntPtr AllocateMemory(IntPtr baseAddress, ref IntPtr size, MemoryFlags type, MemoryProtection protection)
{
- Win32.NtAllocateVirtualMemory(
+ NtStatus status;
+
+ if ((status = Win32.NtAllocateVirtualMemory(
this,
ref baseAddress,
IntPtr.Zero,
ref size,
type,
protection
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return baseAddress;
}
@@ -794,7 +868,9 @@ public ThreadHandle CreateThreadWin32(IntPtr startAddress, IntPtr parameter, boo
/// A handle to the new thread.
public ThreadHandle CreateThreadWin32(IntPtr startAddress, IntPtr parameter, bool createSuspended, out int threadId)
{
- IntPtr threadHandle = Win32.CreateRemoteThread(
+ IntPtr threadHandle;
+
+ if ((threadHandle = Win32.CreateRemoteThread(
this,
IntPtr.Zero,
IntPtr.Zero,
@@ -802,9 +878,7 @@ public ThreadHandle CreateThreadWin32(IntPtr startAddress, IntPtr parameter, boo
parameter,
createSuspended ? ProcessCreationFlags.CreateSuspended : 0,
out threadId
- );
-
- if (threadHandle == IntPtr.Zero)
+ )) == IntPtr.Zero)
Win32.Throw();
return new ThreadHandle(threadHandle, true);
@@ -817,7 +891,10 @@ out threadId
/// A handle to a debug object.
public void Debug(DebugObjectHandle debugObjectHandle)
{
- Win32.NtDebugActiveProcess(this, debugObjectHandle).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtDebugActiveProcess(this, debugObjectHandle)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -827,13 +904,16 @@ public void Debug(DebugObjectHandle debugObjectHandle)
///
public void DisableHandleTracing()
{
+ NtStatus status;
+
// Length 0 and NULL disables handle tracing.
- Win32.NtSetInformationProcess(
+ if ((status = Win32.NtSetInformationProcess(
this,
ProcessInformationClass.ProcessHandleTracing,
IntPtr.Zero,
0
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -852,14 +932,16 @@ public void EmptyWorkingSet()
///
public void EnableHandleTracing()
{
+ NtStatus status;
ProcessHandleTracingEnable phte = new ProcessHandleTracingEnable();
- Win32.NtSetInformationProcess(
+ if ((status = Win32.NtSetInformationProcess(
this,
ProcessInformationClass.ProcessHandleTracing,
ref phte,
- ProcessHandleTracingEnable.SizeOf
- ).ThrowIf();
+ Marshal.SizeOf(phte)
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -869,10 +951,10 @@ public void EnableHandleTracing()
public void EnumMemory(EnumMemoryDelegate enumMemoryCallback)
{
IntPtr address = IntPtr.Zero;
+ MemoryBasicInformation mbi = new MemoryBasicInformation();
+ int mbiSize = Marshal.SizeOf(mbi);
- MemoryBasicInformation mbi;
-
- while (Win32.VirtualQueryEx(this, address, out mbi, MemoryBasicInformation.SizeOf) != 0)
+ while (Win32.VirtualQueryEx(this, address, out mbi, mbiSize) != 0)
{
if (!enumMemoryCallback(mbi))
break;
@@ -905,23 +987,23 @@ private void EnumModulesApi(EnumModulesDelegate enumModulesCallback)
if (!Win32.EnumProcessModules(this, moduleHandles, requiredSize, out requiredSize))
Win32.Throw();
- foreach (IntPtr t in moduleHandles)
+ for (int i = 0; i < moduleHandles.Length; i++)
{
ModuleInfo moduleInfo = new ModuleInfo();
StringBuilder baseName = new StringBuilder(0x400);
StringBuilder fileName = new StringBuilder(0x400);
- if (!Win32.GetModuleInformation(this, t, moduleInfo, ModuleInfo.SizeOf))
+ if (!Win32.GetModuleInformation(this, moduleHandles[i], moduleInfo, Marshal.SizeOf(moduleInfo)))
Win32.Throw();
- if (Win32.GetModuleBaseName(this, t, baseName, baseName.Capacity * 2) == 0)
+ if (Win32.GetModuleBaseName(this, moduleHandles[i], baseName, baseName.Capacity * 2) == 0)
Win32.Throw();
- if (Win32.GetModuleFileNameEx(this, t, fileName, fileName.Capacity * 2) == 0)
+ if (Win32.GetModuleFileNameEx(this, moduleHandles[i], fileName, fileName.Capacity * 2) == 0)
Win32.Throw();
if (!enumModulesCallback(new ProcessModule(
- moduleInfo.BaseOfDll, moduleInfo.SizeOfImage, moduleInfo.EntryPoint, 0,
- baseName.ToString(), FileUtils.GetFileName(fileName.ToString())
- )))
+ moduleInfo.BaseOfDll, moduleInfo.SizeOfImage, moduleInfo.EntryPoint, 0,
+ baseName.ToString(), FileUtils.GetFileName(fileName.ToString())
+ )))
break;
}
}
@@ -941,7 +1023,7 @@ private unsafe void EnumModulesNative(EnumModulesDelegate enumModulesCallback)
PebLdrData data;
// Read the loader data table structure.
- this.ReadMemory(loaderData, &data, PebLdrData.SizeOf);
+ this.ReadMemory(loaderData, &data, Marshal.SizeOf(typeof(PebLdrData)));
if (!data.Initialized)
throw new Exception("Loader data is not initialized.");
@@ -961,7 +1043,7 @@ private unsafe void EnumModulesNative(EnumModulesDelegate enumModulesCallback)
break;
// Read the loader data table entry.
- this.ReadMemory(currentLink, ¤tEntry, LdrDataTableEntry.SizeOf);
+ this.ReadMemory(currentLink, ¤tEntry, Marshal.SizeOf(typeof(LdrDataTableEntry)));
// Check if the entry is valid.
if (currentEntry.DllBase != IntPtr.Zero)
@@ -1009,15 +1091,17 @@ private unsafe void EnumModulesNative(EnumModulesDelegate enumModulesCallback)
/// A NT status value.
public NtStatus FlushMemory(IntPtr baseAddress, int size)
{
+ NtStatus status;
IntPtr sizeIntPtr = size.ToIntPtr();
IoStatusBlock isb;
- Win32.NtFlushVirtualMemory(
+ if ((status = Win32.NtFlushVirtualMemory(
this,
ref baseAddress,
ref sizeIntPtr,
out isb
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return isb.Status;
}
@@ -1041,37 +1125,31 @@ public void FreeMemory(IntPtr baseAddress, int size)
/// reserve the memory instead of freeing it.
public void FreeMemory(IntPtr baseAddress, int size, bool reserveOnly)
{
+ NtStatus status;
IntPtr sizeIntPtr = size.ToIntPtr();
// Size needs to be 0 if we're freeing.
if (!reserveOnly)
sizeIntPtr = IntPtr.Zero;
- Win32.NtFreeVirtualMemory(
+ if ((status = Win32.NtFreeVirtualMemory(
this,
ref baseAddress,
ref sizeIntPtr,
reserveOnly ? MemoryFlags.Decommit : MemoryFlags.Release
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
- /// Gets/Sets the processor affinity for the process.
+ /// Gets the processor affinity for the process.
///
/// The processor affinity for the process.
- public long AffinityMask
+ public long GetAffinityMask()
{
- get
- {
- long systemMask;
+ long systemMask;
- return this.GetAffinityMask(out systemMask);
- }
- set
- {
- if (!Win32.SetProcessAffinityMask(this, new IntPtr(value)))
- Win32.Throw();
- }
+ return this.GetAffinityMask(out systemMask);
}
///
@@ -1095,10 +1173,9 @@ public long GetAffinityMask(out long systemMask)
///
/// Gets the base priority of the process.
///
- public int BasePriority
+ public int GetBasePriority()
{
- get { return this.GetInformationInt32(ProcessInformationClass.ProcessBasePriority); }
- set { this.SetInformationInt32(ProcessInformationClass.ProcessBasePriority, value); }
+ return this.GetInformationInt32(ProcessInformationClass.ProcessBasePriority);
}
///
@@ -1108,16 +1185,13 @@ public int BasePriority
/// A PROCESS_BASIC_INFORMATION structure.
public ProcessBasicInformation GetBasicInformation()
{
+ NtStatus status;
ProcessBasicInformation pbi;
int retLen;
- Win32.NtQueryInformationProcess(
- this,
- ProcessInformationClass.ProcessBasicInformation,
- out pbi,
- ProcessBasicInformation.SizeOf,
- out retLen
- ).ThrowIf();
+ if ((status = Win32.NtQueryInformationProcess(this, ProcessInformationClass.ProcessBasicInformation,
+ out pbi, Marshal.SizeOf(typeof(ProcessBasicInformation)), out retLen)) >= NtStatus.Error)
+ Win32.Throw(status);
return pbi;
}
@@ -1127,15 +1201,12 @@ out retLen
/// the PROCESS_QUERY_LIMITED_INFORMATION and PROCESS_VM_READ permissions.
///
/// A string.
- public string CommandLine
+ public string GetCommandLine()
{
- get
- {
- if (!this.IsPosix)
- return this.GetPebString(PebOffset.CommandLine);
-
+ if (!this.IsPosix())
+ return this.GetPebString(PebOffset.CommandLine);
+ else
return this.GetPosixCommandLine();
- }
}
///
@@ -1149,9 +1220,9 @@ public int GetCookie()
///
/// Gets the creation time of the process.
///
- public DateTime CreateTime
+ public DateTime GetCreateTime()
{
- get { return DateTime.FromFileTime(this.GetTimes()[0]); }
+ return DateTime.FromFileTime(this.GetTimes()[0]);
}
///
@@ -1173,7 +1244,9 @@ public ulong GetCycleTime()
/// A debug object handle.
public DebugObjectHandle GetDebugObject()
{
- IntPtr handle = this.GetDebugObjectHandle();
+ IntPtr handle;
+
+ handle = this.GetDebugObjectHandle();
// Check if we got a handle. If we didn't the process is not being debugged.
if (handle == IntPtr.Zero)
@@ -1188,61 +1261,43 @@ internal IntPtr GetDebugObjectHandle()
}
///
- /// Gets/Sets the process' DEP policy.
+ /// Gets the process' DEP policy.
///
/// A DepStatus enum.
- public DepStatus DepStatus
+ public DepStatus GetDepStatus()
{
- get
- {
- // If we're on 64-bit and the process isn't under
- // WOW64, it must be under permanent DEP.
- if (OSVersion.Architecture == OSArch.Amd64)
- {
- if (!this.IsWow64)
- return DepStatus.Enabled | DepStatus.Permanent;
- }
+ MemExecuteOptions options;
- MemExecuteOptions options = (MemExecuteOptions)this.GetInformationInt32(ProcessInformationClass.ProcessExecuteFlags);
-
- DepStatus depStatus = 0;
+ // If we're on 64-bit and the process isn't under
+ // WOW64, it must be under permanent DEP.
+ if (OSVersion.Architecture == OSArch.Amd64)
+ {
+ if (!this.IsWow64())
+ return DepStatus.Enabled | DepStatus.Permanent;
+ }
- // Check if execution of data pages is enabled.
- if ((options & MemExecuteOptions.ExecuteEnable) == MemExecuteOptions.ExecuteEnable)
- return 0;
+ options = (MemExecuteOptions)this.GetInformationInt32(ProcessInformationClass.ProcessExecuteFlags);
- // Check if execution of data pages is disabled.
- if ((options & MemExecuteOptions.ExecuteDisable) == MemExecuteOptions.ExecuteDisable)
- depStatus = DepStatus.Enabled;
- // ExecuteDisable and ExecuteEnable are both disabled in OptOut mode.
- else if ((options & MemExecuteOptions.ExecuteDisable) == 0 &&
- (options & MemExecuteOptions.ExecuteEnable) == 0)
- depStatus = DepStatus.Enabled;
+ DepStatus depStatus = 0;
- if ((options & MemExecuteOptions.DisableThunkEmulation) == MemExecuteOptions.DisableThunkEmulation)
- depStatus |= DepStatus.AtlThunkEmulationDisabled;
- if ((options & MemExecuteOptions.Permanent) == MemExecuteOptions.Permanent)
- depStatus |= DepStatus.Permanent;
+ // Check if execution of data pages is enabled.
+ if ((options & MemExecuteOptions.ExecuteEnable) == MemExecuteOptions.ExecuteEnable)
+ return 0;
- return depStatus;
- }
- set
- {
- MemExecuteOptions executeOptions = 0;
+ // Check if execution of data pages is disabled.
+ if ((options & MemExecuteOptions.ExecuteDisable) == MemExecuteOptions.ExecuteDisable)
+ depStatus = DepStatus.Enabled;
+ // ExecuteDisable and ExecuteEnable are both disabled in OptOut mode.
+ else if ((options & MemExecuteOptions.ExecuteDisable) == 0 &&
+ (options & MemExecuteOptions.ExecuteEnable) == 0)
+ depStatus = DepStatus.Enabled;
- if (value.HasFlag(DepStatus.Enabled))
- executeOptions |= MemExecuteOptions.ExecuteDisable;
- else
- executeOptions |= MemExecuteOptions.ExecuteEnable;
+ if ((options & MemExecuteOptions.DisableThunkEmulation) == MemExecuteOptions.DisableThunkEmulation)
+ depStatus |= DepStatus.AtlThunkEmulationDisabled;
+ if ((options & MemExecuteOptions.Permanent) == MemExecuteOptions.Permanent)
+ depStatus |= DepStatus.Permanent;
- if (value.HasFlag(DepStatus.AtlThunkEmulationDisabled))
- executeOptions |= MemExecuteOptions.DisableThunkEmulation;
-
- if (value.HasFlag(DepStatus.Permanent))
- executeOptions |= MemExecuteOptions.Permanent;
-
- //KProcessHacker.Instance.SetExecuteOptions(this, executeOptions);
- }
+ return depStatus;
}
///
@@ -1262,7 +1317,7 @@ public unsafe IDictionary GetEnvironmentVariables()
// Get a pointer to the environment block.
this.ReadMemory(processParameters.Increment(RtlUserProcessParameters.EnvironmentOffset), buffer, IntPtr.Size);
IntPtr envBase = *(IntPtr*)buffer;
- int length;
+ int length = 0;
{
MemoryBasicInformation mbi = this.QueryMemory(envBase);
@@ -1356,7 +1411,8 @@ public DateTime GetExitTime()
///
/// Gets a GUI handle count.
///
- /// If true, returns the number of USER handles. Otherwise, returns the number of GDI handles.
+ /// If true, returns the number of USER handles. Otherwise, returns
+ /// the number of GDI handles.
/// A handle count.
public int GetGuiResources(bool userObjects)
{
@@ -1375,45 +1431,45 @@ public int GetHandleCount()
/// Gets the handles owned by the process.
///
/// An array of handle information structures.
- //public ProcessHandleInformation[] GetHandles()
- //{
- // int returnLength = 0;
- // int attempts = 0;
-
- // using (MemoryAlloc data = new MemoryAlloc(0x1000))
- // {
- // while (true)
- // {
- // try
- // {
- // //KProcessHacker.Instance.KphQueryProcessHandles(this, data, data.Size, out returnLength);
- // }
- // catch (WindowsException ex)
- // {
- // if (attempts > 3)
- // throw ex;
-
- // if (
- // ex.Status == NtStatus.BufferTooSmall &&
- // returnLength > data.Size
- // )
- // data.ResizeNew(returnLength);
-
- // attempts++;
-
- // continue;
- // }
-
- // int handleCount = data.ReadInt32(0);
- // ProcessHandleInformation[] handles = new ProcessHandleInformation[handleCount];
-
- // for (int i = 0; i < handleCount; i++)
- // handles[i] = data.ReadStruct(sizeof(int), ProcessHandleInformation.SizeOf, i);
-
- // return handles;
- // }
- // }
- //}
+ public ProcessHandleInformation[] GetHandles()
+ {
+ int returnLength = 0;
+ int attempts = 0;
+
+ using (var data = new MemoryAlloc(0x1000))
+ {
+ while (true)
+ {
+ try
+ {
+ KProcessHacker.Instance.KphQueryProcessHandles(this, data, data.Size, out returnLength);
+ }
+ catch (WindowsException ex)
+ {
+ if (attempts > 3)
+ throw ex;
+
+ if (
+ ex.Status == NtStatus.BufferTooSmall &&
+ returnLength > data.Size
+ )
+ data.ResizeNew(returnLength);
+
+ attempts++;
+
+ continue;
+ }
+
+ int handleCount = data.ReadInt32(0);
+ ProcessHandleInformation[] handles = new ProcessHandleInformation[handleCount];
+
+ for (int i = 0; i < handleCount; i++)
+ handles[i] = data.ReadStruct(sizeof(int), i);
+
+ return handles;
+ }
+ }
+ }
///
/// Gets a collection of handle stack traces. This requires
@@ -1439,17 +1495,15 @@ public ProcessHandleTraceCollection GetHandleTraces(IntPtr handle)
NtStatus status = NtStatus.Success;
int retLength;
- using (MemoryAlloc data = new MemoryAlloc(0x10000))
+ using (var data = new MemoryAlloc(0x10000))
{
+ var query = new ProcessHandleTracingQuery();
+
// If Handle is not NULL, NtQueryInformationProcess will
// get a specific stack trace. Otherwise, it will get
// all of the stack traces.
- ProcessHandleTracingQuery query = new ProcessHandleTracingQuery
- {
- Handle = handle
- };
-
- data.WriteStruct(query);
+ query.Handle = handle;
+ data.WriteStruct(query);
for (int i = 0; i < 8; i++)
{
@@ -1467,7 +1521,8 @@ out retLength
continue;
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return new ProcessHandleTraceCollection(data);
}
@@ -1499,9 +1554,9 @@ public unsafe IntPtr GetHeap()
/// QueryLimitedInformation access.
///
/// A file name, in native format.
- public string ImageFileName
+ public string GetImageFileName()
{
- get { return FileUtils.GetFileName(this.GetInformationUnicodeString(ProcessInformationClass.ProcessImageFileName)); }
+ return this.GetInformationUnicodeString(ProcessInformationClass.ProcessImageFileName);
}
///
@@ -1515,36 +1570,106 @@ public string GetImageFileNameWin32()
}
///
- /// Gets/Sets the process' I/O priority, ranging from 0-7.
+ /// Gets information about the process in an Int32.
+ ///
+ /// The class of information to retrieve.
+ /// An int.
+ private int GetInformationInt32(ProcessInformationClass infoClass)
+ {
+ if (
+ KProcessHacker.Instance != null &&
+ infoClass == ProcessInformationClass.ProcessIoPriority
+ )
+ {
+ unsafe
+ {
+ int value;
+ int retLength;
+
+ KProcessHacker.Instance.KphQueryInformationProcess(
+ this, infoClass, new IntPtr(&value), sizeof(int), out retLength
+ );
+
+ return value;
+ }
+ }
+ else
+ {
+ NtStatus status;
+ int value;
+ int retLength;
+
+ if ((status = Win32.NtQueryInformationProcess(
+ this, infoClass, out value, sizeof(int), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return value;
+ }
+ }
+
+ ///
+ /// Gets information about the process in an IntPtr.
+ ///
+ /// The class of information to retrieve.
+ /// An IntPtr.
+ private IntPtr GetInformationIntPtr(ProcessInformationClass infoClass)
+ {
+ NtStatus status;
+ IntPtr value;
+ int retLength;
+
+ if ((status = Win32.NtQueryInformationProcess(
+ this, infoClass, out value, IntPtr.Size, out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return value;
+ }
+
+ private string GetInformationUnicodeString(ProcessInformationClass infoClass)
+ {
+ NtStatus status;
+ int retLen;
+
+ Win32.NtQueryInformationProcess(this, infoClass, IntPtr.Zero, 0, out retLen);
+
+ using (MemoryAlloc data = new MemoryAlloc(retLen))
+ {
+ if ((status = Win32.NtQueryInformationProcess(this, infoClass, data, retLen, out retLen)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return data.ReadStruct().Read();
+ }
+ }
+
+ ///
+ /// Gets the process' I/O priority, ranging from 0-7.
///
///
- public int IoPriority
+ public int GetIoPriority()
{
- get { return this.GetInformationInt32(ProcessInformationClass.ProcessIoPriority); }
- set { this.SetInformationInt32(ProcessInformationClass.ProcessIoPriority, value); }
- }
+ return this.GetInformationInt32(ProcessInformationClass.ProcessIoPriority);
+ }
///
/// Gets I/O statistics for the process.
///
/// A IoCounters structure.
- public IoCounters IoStatistics
+ public IoCounters GetIoStatistics()
{
- get
- {
- IoCounters counters;
- int retLength;
+ NtStatus status;
+ IoCounters counters;
+ int retLength;
- Win32.NtQueryInformationProcess(
- this,
- ProcessInformationClass.ProcessIoCounters,
- out counters,
- IoCounters.SizeOf,
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQueryInformationProcess(
+ this,
+ ProcessInformationClass.ProcessIoCounters,
+ out counters,
+ Marshal.SizeOf(typeof(IoCounters)),
+ out retLength
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- return counters;
- }
+ return counters;
}
///
@@ -1553,50 +1678,51 @@ out retLength
/// A job object handle.
public JobObjectHandle GetJobObject(JobObjectAccess access)
{
- IntPtr handle = JobObjectHandle.Open(this, access);
+ IntPtr handle;
+
+ handle = JobObjectHandle.Open(this, access);
if (handle != IntPtr.Zero)
return new JobObjectHandle(handle, true);
-
- return null;
+ else
+ return null;
}
///
/// Gets the type of well-known process.
///
/// A known process type.
- public KnownProcess KnownProcessType
+ public KnownProcess GetKnownProcessType()
{
- get
- {
- if (this.GetBasicInformation().UniqueProcessId.Equals(4))
- return KnownProcess.System;
+ if (this.GetBasicInformation().UniqueProcessId.Equals(4))
+ return KnownProcess.System;
- string fileName = this.ImageFileName;
+ string fileName = FileUtils.GetFileName(this.GetImageFileName());
- if (fileName.StartsWith(Environment.SystemDirectory, StringComparison.OrdinalIgnoreCase))
- {
- string baseName = fileName.Remove(0, Environment.SystemDirectory.Length).TrimStart('\\').ToLowerInvariant();
+ if (fileName.StartsWith(Environment.SystemDirectory, StringComparison.OrdinalIgnoreCase))
+ {
+ string baseName = fileName.Remove(0, Environment.SystemDirectory.Length).TrimStart('\\').ToLowerInvariant();
- switch (baseName)
- {
- case "smss.exe":
- return KnownProcess.SessionManager;
- case "csrss.exe":
- return KnownProcess.WindowsSubsystem;
- case "wininit.exe":
- return KnownProcess.WindowsStartup;
- case "services.exe":
- return KnownProcess.ServiceControlManager;
- case "lsass.exe":
- return KnownProcess.LocalSecurityAuthority;
- case "lsm.exe":
- return KnownProcess.LocalSessionManager;
- default:
- return KnownProcess.None;
- }
+ switch (baseName)
+ {
+ case "smss.exe":
+ return KnownProcess.SessionManager;
+ case "csrss.exe":
+ return KnownProcess.WindowsSubsystem;
+ case "wininit.exe":
+ return KnownProcess.WindowsStartup;
+ case "services.exe":
+ return KnownProcess.ServiceControlManager;
+ case "lsass.exe":
+ return KnownProcess.LocalSecurityAuthority;
+ case "lsm.exe":
+ return KnownProcess.LocalSessionManager;
+ default:
+ return KnownProcess.None;
}
-
+ }
+ else
+ {
return KnownProcess.None;
}
}
@@ -1606,20 +1732,17 @@ public KnownProcess KnownProcessType
/// PROCESS_QUERY_INFORMATION and PROCESS_VM_READ permissions.
///
/// A ProcessModule.
- public ProcessModule MainModule
+ public ProcessModule GetMainModule()
{
- get
- {
- ProcessModule mainModule = null;
+ ProcessModule mainModule = null;
- this.EnumModules(module =>
- {
- mainModule = module;
- return false;
- });
+ this.EnumModules((module) =>
+ {
+ mainModule = module;
+ return false;
+ });
- return mainModule;
- }
+ return mainModule;
}
///
@@ -1655,10 +1778,10 @@ out retLength
);
}
- if (status.IsError())
+ if (status >= NtStatus.Error)
return null;
- return FileUtils.GetFileName(data.ReadStruct().Text);
+ return FileUtils.GetFileName(data.ReadStruct().Read());
}
}
@@ -1666,23 +1789,22 @@ out retLength
/// Gets memory statistics for the process.
///
/// A VmCounters structure.
- public VmCounters MemoryStatistics
+ public VmCounters GetMemoryStatistics()
{
- get
- {
- VmCounters counters;
- int retLength;
+ NtStatus status;
+ VmCounters counters;
+ int retLength;
- Win32.NtQueryInformationProcess(
- this,
- ProcessInformationClass.ProcessVmCounters,
- out counters,
- VmCounters.SizeOf,
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQueryInformationProcess(
+ this,
+ ProcessInformationClass.ProcessVmCounters,
+ out counters,
+ Marshal.SizeOf(typeof(VmCounters)),
+ out retLength
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- return counters;
- }
+ return counters;
}
///
@@ -1694,7 +1816,7 @@ public ProcessModule[] GetModules()
{
List modules = new List();
- this.EnumModules(module =>
+ this.EnumModules((module) =>
{
modules.Add(module);
return true;
@@ -1710,20 +1832,22 @@ public ProcessModule[] GetModules()
/// A process handle.
public ProcessHandle GetNextProcess(ProcessAccess access)
{
+ NtStatus status;
IntPtr handle;
- Win32.NtGetNextProcess(
+ if ((status = Win32.NtGetNextProcess(
this,
access,
0,
0,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (handle != IntPtr.Zero)
return new ProcessHandle(handle, true);
-
- return null;
+ else
+ return null;
}
///
@@ -1734,30 +1858,31 @@ out handle
/// A thread handle.
public ThreadHandle GetNextThread(ThreadHandle threadHandle, ThreadAccess access)
{
+ NtStatus status;
IntPtr handle;
- Win32.NtGetNextThread(
+ if ((status = Win32.NtGetNextThread(
this,
- threadHandle ?? IntPtr.Zero,
+ threadHandle != null ? threadHandle : IntPtr.Zero,
access,
0,
0,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (handle != IntPtr.Zero)
return new ThreadHandle(handle, true);
-
- return null;
+ else
+ return null;
}
///
/// Gets the process' page priority, ranging from 0-7.
///
- public int PagePriority
+ public int GetPagePriority()
{
- get { return this.GetInformationInt32(ProcessInformationClass.ProcessPagePriority); }
- set { this.SetInformationInt32(ProcessInformationClass.ProcessPagePriority, value); }
+ return this.GetInformationInt32(ProcessInformationClass.ProcessPagePriority);
}
///
@@ -1765,9 +1890,9 @@ public int PagePriority
/// the PROCESS_QUERY_LIMITED_INFORMATION permission.
///
/// The process ID.
- public int ParentPid
+ public int GetParentPid()
{
- get { return this.GetBasicInformation().InheritedFromUniqueProcessId.ToInt32(); }
+ return this.GetBasicInformation().InheritedFromUniqueProcessId.ToInt32();
}
///
@@ -1790,7 +1915,7 @@ public unsafe string GetPebString(PebOffset offset)
// Read the UNICODE_STRING structure.
UnicodeString pebStr;
- this.ReadMemory(processParameters.Increment(realOffset), &pebStr, UnicodeString.SizeOf);
+ this.ReadMemory(processParameters.Increment(realOffset), &pebStr, Marshal.SizeOf(typeof(UnicodeString)));
// read string and decode it
return Encoding.Unicode.GetString(this.ReadMemory(pebStr.Buffer, pebStr.Length), 0, pebStr.Length);
@@ -1815,9 +1940,8 @@ public unsafe string GetPosixCommandLine()
this.ReadMemory(
processParameters.Increment(GetPebOffset(PebOffset.CommandLine)),
&commandLineUs,
- UnicodeString.SizeOf
+ Marshal.SizeOf(typeof(UnicodeString))
);
-
IntPtr stringAddr = commandLineUs.Buffer;
/*
@@ -1852,8 +1976,7 @@ public unsafe string GetPosixCommandLine()
if (zeroReached)
break;
-
- if (value == IntPtr.Zero)
+ else if (value == IntPtr.Zero)
zeroReached = true;
}
@@ -1880,56 +2003,61 @@ public unsafe string GetPosixCommandLine()
}
///
- /// Gets/Sets the process' priority class.
+ /// Gets the process' priority class.
///
/// A ProcessPriorityClass enum.
- public ProcessPriorityClass PriorityClass
- {
- get
- {
- ProcessPriorityClassStruct priorityClass;
- int retLength;
-
- Win32.NtQueryInformationProcess(
- this,
- ProcessInformationClass.ProcessPriorityClass,
- out priorityClass,
- ProcessPriorityClassStruct.SizeOf,
- out retLength
- ).ThrowIf();
+ public ProcessPriorityClass GetPriorityClass()
+ {
+ //switch (Win32.GetPriorityClass(this))
+ //{
+ // case ProcessPriorityClassWin32.AboveNormal:
+ // return ProcessPriorityClass.AboveNormal;
+ // case ProcessPriorityClassWin32.BelowNormal:
+ // return ProcessPriorityClass.BelowNormal;
+ // case ProcessPriorityClassWin32.High:
+ // return ProcessPriorityClass.High;
+ // case ProcessPriorityClassWin32.Idle:
+ // return ProcessPriorityClass.Idle;
+ // case ProcessPriorityClassWin32.Normal:
+ // return ProcessPriorityClass.Normal;
+ // case ProcessPriorityClassWin32.RealTime:
+ // return ProcessPriorityClass.RealTime;
+ // default:
+ // Win32.Throw();
+ // // Stupid compiler
+ // return ProcessPriorityClass.Unknown;
+ //}
- return (ProcessPriorityClass)priorityClass.PriorityClass;
- }
- set
- {
- ProcessPriorityClassStruct processPriority;
+ NtStatus status;
+ ProcessPriorityClassStruct priorityClass;
+ int retLength;
- processPriority.Foreground = '\0';
- processPriority.PriorityClass = Convert.ToChar(value);
+ if ((status = Win32.NtQueryInformationProcess(
+ this,
+ ProcessInformationClass.ProcessPriorityClass,
+ out priorityClass,
+ Marshal.SizeOf(typeof(ProcessPriorityClassStruct)),
+ out retLength
+ )) != NtStatus.Success)
+ Win32.Throw(status);
- Win32.NtSetInformationProcess(
- this,
- ProcessInformationClass.ProcessPriorityClass,
- ref processPriority,
- ProcessPriorityClassStruct.SizeOf
- ).ThrowIf();
- }
+ return (ProcessPriorityClass)priorityClass.PriorityClass;
}
///
/// Gets the process' unique identifier.
///
- public int ProcessId
+ public int GetProcessId()
{
- get { return this.GetBasicInformation().UniqueProcessId.ToInt32(); }
+ return this.GetBasicInformation().UniqueProcessId.ToInt32();
}
///
/// Gets the process' session ID.
///
- public int SessionId
+ public int GetSessionId()
{
- get { return this.GetInformationInt32(ProcessInformationClass.ProcessSessionInformation); }
+ return this.GetInformationInt32(ProcessInformationClass.ProcessSessionInformation);
}
///
@@ -2012,20 +2140,17 @@ public void InjectDll(string path, uint timeout)
/// Gets whether the process is currently being debugged. This requires
/// QueryInformation access.
///
- public bool IsBeingDebugged
+ public bool IsBeingDebugged()
{
- get { return this.GetInformationIntPtr(ProcessInformationClass.ProcessDebugPort) != IntPtr.Zero; }
+ return this.GetInformationIntPtr(ProcessInformationClass.ProcessDebugPort) != IntPtr.Zero;
}
///
- /// Gets/Sets whether the system will crash upon the process being terminated.
- /// This function requires SeTcbPrivilege.
- /// Whether the system will crash upon the process being terminated.
+ /// Gets whether the system will crash upon the process being terminated.
///
- public bool IsCritical
+ public bool IsCritical()
{
- get { return this.GetInformationInt32(ProcessInformationClass.ProcessBreakOnTermination) != 0; }
- set { this.SetInformationInt32(ProcessInformationClass.ProcessBreakOnTermination, value ? 1 : 0); }
+ return this.GetInformationInt32(ProcessInformationClass.ProcessBreakOnTermination) != 0;
}
///
@@ -2060,46 +2185,38 @@ public bool IsInJob(JobObjectHandle jobObjectHandle)
///
/// Gets whether the process is a NTVDM process.
///
- public bool IsNtVdmProcess
+ public bool IsNtVdmProcess()
{
- get { return this.GetInformationInt32(ProcessInformationClass.ProcessWx86Information) != 0; }
+ return this.GetInformationInt32(ProcessInformationClass.ProcessWx86Information) != 0;
}
///
/// Gets whether the process is using the POSIX subsystem.
///
- public unsafe bool IsPosix
+ public unsafe bool IsPosix()
{
- get
- {
- int subsystem;
- IntPtr pebBaseAddress = this.GetBasicInformation().PebBaseAddress;
+ int subsystem;
+ IntPtr pebBaseAddress = this.GetBasicInformation().PebBaseAddress;
- this.ReadMemory(pebBaseAddress.Increment(Peb.ImageSubsystemOffset), &subsystem, sizeof(int));
+ this.ReadMemory(pebBaseAddress.Increment(Peb.ImageSubsystemOffset), &subsystem, sizeof(int));
- return subsystem == 7;
- }
+ return subsystem == 7;
}
///
- /// Gets/Sets whether the process has priority boost enabled.
+ /// Gets whether the process has priority boost enabled.
///
- public bool IsPriorityBoostEnabled
+ public bool IsPriorityBoostEnabled()
{
- get { return this.GetInformationInt32(ProcessInformationClass.ProcessPriorityBoost) == 0; }
- set
- {
- // If priority boost is being enabled, we have to not disable it (hence the value of 0).
- this.SetInformationInt32(ProcessInformationClass.ProcessPriorityBoost, value ? 0 : 1);
- }
+ return this.GetInformationInt32(ProcessInformationClass.ProcessPriorityBoost) == 0;
}
///
/// Gets whether the process is running under WOW64.
///
- public bool IsWow64
+ public bool IsWow64()
{
- get { return this.GetInformationIntPtr(ProcessInformationClass.ProcessWow64Information) != IntPtr.Zero; }
+ return this.GetInformationIntPtr(ProcessInformationClass.ProcessWow64Information) != IntPtr.Zero;
}
///
@@ -2111,16 +2228,18 @@ public bool IsWow64
/// The old memory protection.
public MemoryProtection ProtectMemory(IntPtr baseAddress, int size, MemoryProtection protection)
{
+ NtStatus status;
IntPtr sizeIntPtr = size.ToIntPtr();
MemoryProtection oldProtection;
- Win32.NtProtectVirtualMemory(
+ if ((status = Win32.NtProtectVirtualMemory(
this,
ref baseAddress,
ref sizeIntPtr,
protection,
out oldProtection
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return oldProtection;
}
@@ -2132,17 +2251,19 @@ out oldProtection
/// A MEMORY_BASIC_INFORMATION structure.
public MemoryBasicInformation QueryMemory(IntPtr baseAddress)
{
+ NtStatus status;
MemoryBasicInformation mbi;
IntPtr retLength;
- Win32.NtQueryVirtualMemory(
+ if ((status = Win32.NtQueryVirtualMemory(
this,
baseAddress,
MemoryInformationClass.MemoryBasicInformation,
out mbi,
- MemoryBasicInformation.SizeOf.ToIntPtr(),
+ Marshal.SizeOf(typeof(MemoryBasicInformation)).ToIntPtr(),
out retLength
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return mbi;
}
@@ -2196,23 +2317,34 @@ public unsafe int ReadMemory(IntPtr baseAddress, void* buffer, int length)
/// The number of bytes read.
public int ReadMemory(IntPtr baseAddress, IntPtr buffer, int length)
{
+ int retLength;
+
if (this.Handle == Current)
{
Win32.RtlMoveMemory(buffer, baseAddress, length.ToIntPtr());
return length;
}
- IntPtr retLengthIntPtr;
-
- Win32.NtReadVirtualMemory(
- this,
- baseAddress,
- buffer,
- length.ToIntPtr(),
- out retLengthIntPtr
- ).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ KProcessHacker.Instance.KphReadVirtualMemory(this, baseAddress.ToInt32(), buffer, length, out retLength);
+ }
+ else
+ {
+ NtStatus status;
+ IntPtr retLengthIntPtr;
- int retLength = retLengthIntPtr.ToInt32();
+ if ((status = Win32.NtReadVirtualMemory(
+ this,
+ baseAddress,
+ buffer,
+ length.ToIntPtr(),
+ out retLengthIntPtr
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ retLength = retLengthIntPtr.ToInt32();
+ }
return retLength;
}
@@ -2244,7 +2376,10 @@ public ThreadHandle RemoteCall(IntPtr address, IntPtr[] arguments)
/// The debug object which was used to debug the process.
public void RemoveDebug(DebugObjectHandle debugObjectHandle)
{
- Win32.NtRemoveProcessDebug(this, debugObjectHandle).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRemoveProcessDebug(this, debugObjectHandle)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -2252,7 +2387,101 @@ public void RemoveDebug(DebugObjectHandle debugObjectHandle)
///
public void Resume()
{
- Win32.NtResumeProcess(this).ThrowIf();
+ if (KProcessHacker.Instance != null && OSVersion.HasPsSuspendResumeProcess)
+ {
+ KProcessHacker.Instance.KphResumeProcess(this);
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = Win32.NtResumeProcess(this)) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
+ }
+
+ ///
+ /// Sets the processor affinity for the process.
+ ///
+ /// The processor affinity mask.
+ public void SetAffinityMask(long processMask)
+ {
+ if (!Win32.SetProcessAffinityMask(this, new IntPtr(processMask)))
+ Win32.Throw();
+ }
+
+ ///
+ /// Sets the process' base priority.
+ ///
+ /// The process' base priority.
+ public void SetBasePriority(int basePriority)
+ {
+ this.SetInformationInt32(ProcessInformationClass.ProcessBasePriority, basePriority);
+ }
+
+ ///
+ /// Sets whether the system will crash upon the process being terminated.
+ /// This function requires SeTcbPrivilege.
+ ///
+ /// Whether the system will crash upon the process being terminated.
+ public void SetCritical(bool critical)
+ {
+ this.SetInformationInt32(ProcessInformationClass.ProcessBreakOnTermination, critical ? 1 : 0);
+ }
+
+ ///
+ /// Sets the process' DEP policy.
+ ///
+ /// The DEP options.
+ public void SetDepStatus(DepStatus depStatus)
+ {
+ MemExecuteOptions executeOptions = 0;
+
+ if ((depStatus & DepStatus.Enabled) == DepStatus.Enabled)
+ executeOptions |= MemExecuteOptions.ExecuteDisable;
+ else
+ executeOptions |= MemExecuteOptions.ExecuteEnable;
+
+ if ((depStatus & DepStatus.AtlThunkEmulationDisabled) == DepStatus.AtlThunkEmulationDisabled)
+ executeOptions |= MemExecuteOptions.DisableThunkEmulation;
+ if ((depStatus & DepStatus.Permanent) == DepStatus.Permanent)
+ executeOptions |= MemExecuteOptions.Permanent;
+
+ KProcessHacker.Instance.SetExecuteOptions(this, executeOptions);
+ }
+
+ ///
+ /// Sets information about the process in an Int32.
+ ///
+ /// The class of information to set.
+ /// The value to set.
+ private void SetInformationInt32(ProcessInformationClass infoClass, int value)
+ {
+ if (
+ KProcessHacker.Instance != null &&
+ infoClass == ProcessInformationClass.ProcessIoPriority
+ )
+ {
+ unsafe
+ {
+ KProcessHacker.Instance.KphSetInformationProcess(
+ this, infoClass, new IntPtr(&value), sizeof(int)
+ );
+ }
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = Win32.NtSetInformationProcess(
+ this, infoClass, ref value, sizeof(int))) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
+ }
+
+ public void SetIoPriority(int ioPriority)
+ {
+ this.SetInformationInt32(ProcessInformationClass.ProcessIoPriority, ioPriority);
}
///
@@ -2273,7 +2502,7 @@ public unsafe void SetModuleReferenceCount(IntPtr baseAddress, ushort count)
IntPtr loaderData = *(IntPtr*)buffer;
PebLdrData data;
- this.ReadMemory(loaderData, &data, PebLdrData.SizeOf);
+ this.ReadMemory(loaderData, &data, Marshal.SizeOf(typeof(PebLdrData)));
if (!data.Initialized)
throw new Exception("Loader data is not initialized.");
@@ -2291,7 +2520,7 @@ public unsafe void SetModuleReferenceCount(IntPtr baseAddress, ushort count)
if (i > 0x800)
break;
- this.ReadMemory(currentLink, ¤tEntry, LdrDataTableEntry.SizeOf);
+ this.ReadMemory(currentLink, ¤tEntry, Marshal.SizeOf(typeof(LdrDataTableEntry)));
if (currentEntry.DllBase == baseAddress)
{
@@ -2304,13 +2533,87 @@ public unsafe void SetModuleReferenceCount(IntPtr baseAddress, ushort count)
}
}
+ public void SetPagePriority(int pagePriority)
+ {
+ this.SetInformationInt32(ProcessInformationClass.ProcessPagePriority, pagePriority);
+ }
+
+ ///
+ /// Sets the process' priority boost.
+ ///
+ /// Whether priority boost will be enabled.
+ public void SetPriorityBoost(bool enabled)
+ {
+ // If priority boost is being enabled, we have to not disable it (hence the value of 0).
+ this.SetInformationInt32(ProcessInformationClass.ProcessPriorityBoost, enabled ? 0 : 1);
+ }
+
+ ///
+ /// Sets the process' priority class.
+ ///
+ /// The process' priority class.
+ public void SetPriorityClass(ProcessPriorityClass priorityClass)
+ {
+ //ProcessPriorityClassWin32 pcWin32;
+
+ //switch (priorityClass)
+ //{
+ // case ProcessPriorityClass.AboveNormal:
+ // pcWin32 = ProcessPriorityClassWin32.AboveNormal;
+ // break;
+ // case ProcessPriorityClass.BelowNormal:
+ // pcWin32 = ProcessPriorityClassWin32.BelowNormal;
+ // break;
+ // case ProcessPriorityClass.High:
+ // pcWin32 = ProcessPriorityClassWin32.High;
+ // break;
+ // case ProcessPriorityClass.Idle:
+ // pcWin32 = ProcessPriorityClassWin32.Idle;
+ // break;
+ // case ProcessPriorityClass.Normal:
+ // pcWin32 = ProcessPriorityClassWin32.Normal;
+ // break;
+ // case ProcessPriorityClass.RealTime:
+ // pcWin32 = ProcessPriorityClassWin32.RealTime;
+ // break;
+ // default:
+ // throw new ArgumentException("priorityClass");
+ //}
+
+ //if (!Win32.SetPriorityClass(this, pcWin32))
+ // Win32.Throw();
+
+ NtStatus status;
+ ProcessPriorityClassStruct processPriority;
+
+ processPriority.Foreground = '\0';
+ processPriority.PriorityClass = Convert.ToChar(priorityClass);
+
+ if ((status = Win32.NtSetInformationProcess(
+ this,
+ ProcessInformationClass.ProcessPriorityClass,
+ ref processPriority,
+ Marshal.SizeOf(typeof(ProcessPriorityClassStruct))
+ )) != NtStatus.Success)
+ Win32.Throw(status);
+ }
///
/// Suspends the process. This requires PROCESS_SUSPEND_RESUME access.
///
public void Suspend()
{
- Win32.NtSuspendProcess(this).ThrowIf();
+ if (KProcessHacker.Instance != null && OSVersion.HasPsSuspendResumeProcess)
+ {
+ KProcessHacker.Instance.KphSuspendProcess(this);
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = Win32.NtSuspendProcess(this)) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
}
///
@@ -2327,7 +2630,17 @@ public void Terminate()
/// The exit status.
public void Terminate(NtStatus exitStatus)
{
- Win32.NtTerminateProcess(this, exitStatus).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ KProcessHacker.Instance.KphTerminateProcess(this, exitStatus);
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = Win32.NtTerminateProcess(this, exitStatus)) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
}
///
@@ -2353,10 +2666,8 @@ public void WriteDump(string fileName)
/// The type of minidump to write.
public void WriteDump(string fileName, MinidumpType type)
{
- using (FileHandle fhandle = FileHandle.CreateWin32(fileName, FileAccess.GenericWrite))
- {
+ using (var fhandle = FileHandle.CreateWin32(fileName, FileAccess.GenericWrite))
this.WriteDump(fhandle, type);
- }
}
///
@@ -2368,7 +2679,7 @@ public void WriteDump(FileHandle fileHandle, MinidumpType type)
{
if (!Win32.MiniDumpWriteDump(
this,
- this.ProcessId,
+ this.GetProcessId(),
fileHandle,
type,
IntPtr.Zero,
@@ -2384,11 +2695,14 @@ public void WriteDump(FileHandle fileHandle, MinidumpType type)
/// The offset at which to begin writing.
/// The data to write.
/// The length, in bytes, that was written.
- public unsafe int WriteMemory(IntPtr baseAddress, byte[] buffer)
+ public int WriteMemory(IntPtr baseAddress, byte[] buffer)
{
- fixed (byte* dataPtr = buffer)
+ unsafe
{
- return WriteMemory(baseAddress, dataPtr, buffer.Length);
+ fixed (byte* dataPtr = buffer)
+ {
+ return WriteMemory(baseAddress, dataPtr, buffer.Length);
+ }
}
}
@@ -2413,94 +2727,36 @@ public unsafe int WriteMemory(IntPtr baseAddress, void* buffer, int length)
/// The length, in bytes, that was written.
public int WriteMemory(IntPtr baseAddress, IntPtr buffer, int length)
{
+ int retLength;
+
if (this.Handle == Current)
{
Win32.RtlMoveMemory(baseAddress, buffer, length.ToIntPtr());
return length;
}
- IntPtr retLengthIntPtr;
-
- Win32.NtWriteVirtualMemory(
- this,
- baseAddress,
- buffer,
- length.ToIntPtr(),
- out retLengthIntPtr
- ).ThrowIf();
-
- return retLengthIntPtr.ToInt32();
- }
-
- ///
- /// Gets information about the process in an Int32.
- ///
- /// The class of information to retrieve.
- /// An int.
- private int GetInformationInt32(ProcessInformationClass infoClass)
- {
- int value;
- int retLength;
-
- Win32.NtQueryInformationProcess(
- this,
- infoClass,
- out value,
- sizeof(int),
- out retLength
- ).ThrowIf();
-
- return value;
- }
-
- ///
- /// Gets information about the process in an IntPtr.
- ///
- /// The class of information to retrieve.
- /// An IntPtr.
- private IntPtr GetInformationIntPtr(ProcessInformationClass infoClass)
- {
- IntPtr value;
- int retLength;
-
- Win32.NtQueryInformationProcess(
- this,
- infoClass,
- out value,
- IntPtr.Size,
- out retLength
- ).ThrowIf();
-
- return value;
- }
-
- private string GetInformationUnicodeString(ProcessInformationClass infoClass)
- {
- int retLen;
-
- Win32.NtQueryInformationProcess(this, infoClass, IntPtr.Zero, 0, out retLen);
-
- using (MemoryAlloc data = new MemoryAlloc(retLen))
+ if (KProcessHacker.Instance != null)
{
- Win32.NtQueryInformationProcess(this, infoClass, data, retLen, out retLen).ThrowIf();
+ KProcessHacker.Instance.KphWriteVirtualMemory(this, baseAddress.ToInt32(), buffer, length, out retLength);
+ }
+ else
+ {
+ NtStatus status;
+ IntPtr retLengthIntPtr;
- return data.ReadStruct().Text;
+ if ((status = Win32.NtWriteVirtualMemory(
+ this,
+ baseAddress,
+ buffer,
+ length.ToIntPtr(),
+ out retLengthIntPtr
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ retLength = retLengthIntPtr.ToInt32();
}
- }
- ///
- /// Sets information about the process in an Int32.
- ///
- /// The class of information to set.
- /// The value to set.
- private void SetInformationInt32(ProcessInformationClass infoClass, int value)
- {
- Win32.NtSetInformationProcess(
- this,
- infoClass,
- ref value,
- sizeof(int)
- ).ThrowIf();
+ return retLength;
}
}
@@ -2509,10 +2765,10 @@ private void SetInformationInt32(ProcessInformationClass infoClass, int value)
///
public class ProcessHandleTrace
{
- private readonly ClientId _clientId;
- private readonly IntPtr _handle;
- private readonly IntPtr[] _stack;
- private readonly HandleTraceType _type;
+ private ClientId _clientId;
+ private IntPtr _handle;
+ private IntPtr[] _stack;
+ private HandleTraceType _type;
internal ProcessHandleTrace(ProcessHandleTracingEntry entry)
{
@@ -2521,7 +2777,7 @@ internal ProcessHandleTrace(ProcessHandleTracingEntry entry)
_type = entry.Type;
// Find the first occurrence of a NULL to find where the trace stops.
- int zeroIndex = Array.IndexOf(entry.Stacks, IntPtr.Zero);
+ int zeroIndex = Array.IndexOf(entry.Stacks, IntPtr.Zero);
// If there was no NULL, copy the entire array.
if (zeroIndex == -1)
@@ -2570,16 +2826,16 @@ public HandleTraceType Type
///
public class ProcessHandleTraceCollection : ReadOnlyCollection
{
- private readonly IntPtr _handle;
+ private IntPtr _handle;
internal ProcessHandleTraceCollection(MemoryAlloc data)
: base(new List())
{
- if (data.Size < ProcessHandleTracingEntry.SizeOf)
+ if (data.Size < Marshal.SizeOf(typeof(ProcessHandleTracingQuery)))
throw new ArgumentException("Data memory allocation is too small.");
// Read the structure.
- ProcessHandleTracingQuery query = data.ReadStruct();
+ var query = data.ReadStruct();
_handle = query.Handle;
@@ -2588,9 +2844,8 @@ internal ProcessHandleTraceCollection(MemoryAlloc data)
for (int i = 0; i < query.TotalTraces; i++)
{
- ProcessHandleTracingEntry entry = data.ReadStruct(
- ProcessHandleTracingQuery.HandleTraceOffset,
- ProcessHandleTracingEntry.SizeOf,
+ var entry = data.ReadStruct(
+ ProcessHandleTracingQuery.HandleTraceOffset,
i
);
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/ProfileHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/ProfileHandle.cs
index cad79dca2..73000759d 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/ProfileHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/ProfileHandle.cs
@@ -38,6 +38,7 @@ public static ProfileHandle Create(
IntPtr affinity
)
{
+ NtStatus status;
IntPtr handle;
if (bucketSize < 2 || bucketSize > 30)
@@ -48,7 +49,7 @@ IntPtr affinity
uint realBucketSize = (uint)(2 << (bucketSize - 1));
MemoryAlloc buffer = new MemoryAlloc((int)((rangeSize - 1) / realBucketSize + 1) * sizeof(int)); // divide, round up
- Win32.NtCreateProfile(
+ if ((status = Win32.NtCreateProfile(
out handle,
processHandle ?? IntPtr.Zero,
rangeBase,
@@ -58,7 +59,8 @@ IntPtr affinity
buffer.Size,
profileSource,
affinity
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new ProfileHandle(handle, true, rangeBase, rangeSize, realBucketSize, buffer);
}
@@ -66,19 +68,27 @@ IntPtr affinity
public static int GetInterval(KProfileSource profileSource)
{
+ NtStatus status;
int interval;
- Win32.NtQueryIntervalProfile(profileSource, out interval).ThrowIf();
+ if ((status = Win32.NtQueryIntervalProfile(profileSource, out interval)) >= NtStatus.Error)
+ Win32.Throw(status);
return interval;
}
public static void SetInterval(KProfileSource profileSource, int interval)
{
- Win32.NtSetIntervalProfile(interval, profileSource).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtSetIntervalProfile(interval, profileSource)) >= NtStatus.Error)
+ Win32.Throw(status);
}
- private readonly MemoryAlloc _buffer;
+ private IntPtr _rangeBase;
+ private uint _rangeSize;
+ private uint _bucketSize; // not logarithmic
+ private MemoryAlloc _buffer;
private ProfileHandle(
IntPtr handle,
@@ -90,6 +100,9 @@ MemoryAlloc buffer
)
: base(handle, owned)
{
+ _rangeBase = rangeBase;
+ _rangeSize = rangeSize;
+ _bucketSize = bucketSize;
_buffer = buffer;
}
@@ -111,12 +124,18 @@ public int[] Collect()
public void Start()
{
- Win32.NtStartProfile(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtStartProfile(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void Stop()
{
- Win32.NtStopProfile(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtStopProfile(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/RemoteHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/RemoteHandle.cs
index d33c3ea84..2e2e0f757 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/RemoteHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/RemoteHandle.cs
@@ -29,8 +29,8 @@ namespace ProcessHacker.Native.Objects
///
public class RemoteHandle
{
- private readonly ProcessHandle _phandle;
- private readonly IntPtr _handle;
+ private ProcessHandle _phandle;
+ private IntPtr _handle;
public RemoteHandle(ProcessHandle phandle, IntPtr handle)
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/RemoteTokenHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/RemoteTokenHandle.cs
index 379dbf3e4..6f3b6ae82 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/RemoteTokenHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/RemoteTokenHandle.cs
@@ -42,7 +42,7 @@ public RemoteTokenHandle(ProcessHandle phandle, IntPtr handle)
public new IntPtr GetHandle(int rights)
{
- IntPtr newHandle;
+ IntPtr newHandle = IntPtr.Zero;
// We can use KPH here. RemoteHandle doesn't.
Win32.DuplicateObject(this.ProcessHandle, this.Handle, new IntPtr(-1), out newHandle, rights, 0, 0);
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/ResourceManagerHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/ResourceManagerHandle.cs
index f38161e7c..90dbe9f6b 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/ResourceManagerHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/ResourceManagerHandle.cs
@@ -39,26 +39,34 @@ public static ResourceManagerHandle Create(
string description
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
- UnicodeString descriptionStr = new UnicodeString(description);
try
{
- Win32.NtCreateResourceManager(
- out handle,
- access,
- tmHandle,
- ref guid,
- ref oa,
- createOptions,
- ref descriptionStr
- ).ThrowIf();
+ UnicodeString descriptionStr = new UnicodeString(description);
+
+ try
+ {
+ if ((status = Win32.NtCreateResourceManager(
+ out handle,
+ access,
+ tmHandle,
+ ref guid,
+ ref oa,
+ createOptions,
+ ref descriptionStr
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
+ finally
+ {
+ descriptionStr.Dispose();
+ }
}
finally
{
- descriptionStr.Dispose();
-
oa.Dispose();
}
@@ -83,18 +91,20 @@ public ResourceManagerHandle(
ResourceManagerAccess access
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenResourceManager(
+ if ((status = Win32.NtOpenResourceManager(
out handle,
access,
tmHandle,
ref guid,
ref oa
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -109,7 +119,7 @@ private MemoryAlloc GetBasicInformation()
NtStatus status;
int retLength;
- MemoryAlloc data = new MemoryAlloc(0x1000);
+ var data = new MemoryAlloc(0x1000);
status = Win32.NtQueryInformationResourceManager(
this,
@@ -133,7 +143,7 @@ out retLength
);
}
- if (status.IsError())
+ if (status >= NtStatus.Error)
{
data.Dispose();
Win32.Throw(status);
@@ -142,36 +152,33 @@ out retLength
return data;
}
- public string Description
+ public string GetDescription()
{
- get
+ using (var data = this.GetBasicInformation())
{
- using (MemoryAlloc data = this.GetBasicInformation())
- {
- ResourceManagerBasicInformation basicInfo = data.ReadStruct();
+ var basicInfo = data.ReadStruct();
- return data.ReadUnicodeString(
- ResourceManagerBasicInformation.DescriptionOffset,
- basicInfo.DescriptionLength / 2
- );
- }
+ return data.ReadUnicodeString(
+ ResourceManagerBasicInformation.DescriptionOffset,
+ basicInfo.DescriptionLength / 2
+ );
}
}
- public Guid Guid
+ public Guid GetGuid()
{
- get
+ using (var data = this.GetBasicInformation())
{
- using (MemoryAlloc data = this.GetBasicInformation())
- {
- return data.ReadStruct().ResourceManagerId;
- }
+ return data.ReadStruct().ResourceManagerId;
}
}
public void Recover()
{
- Win32.NtRecoverResourceManager(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRecoverResourceManager(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SamAliasHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SamAliasHandle.cs
index 954f49183..8c328e0a8 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SamAliasHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SamAliasHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -33,19 +34,22 @@ public sealed class SamAliasHandle : SamHandle
{
public static SamAliasHandle Create(SamAliasAccess access, SamDomainHandle domainHandle, string name, out int aliasId)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr handle;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.SamCreateAliasInDomain(
+ if ((status = Win32.SamCreateAliasInDomain(
domainHandle,
ref nameStr,
access,
out handle,
out aliasId
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -62,7 +66,7 @@ public static SamAliasHandle Open(string name, SamAliasAccess access)
public static SamAliasHandle Open(Sid sid, SamAliasAccess access)
{
- using (SamDomainHandle dhandle = new SamDomainHandle(sid.DomainName, SamDomainAccess.Lookup))
+ using (var dhandle = new SamDomainHandle(sid.DomainName, SamDomainAccess.Lookup))
{
return new SamAliasHandle(dhandle, dhandle.LookupName(sid.Name), access);
}
@@ -80,119 +84,129 @@ private SamAliasHandle(IntPtr handle, bool owned)
/// The desired access to the alias.
public SamAliasHandle(SamDomainHandle domainHandle, int aliasId, SamAliasAccess access)
{
+ NtStatus status;
IntPtr handle;
- Win32.SamOpenAlias(
+ if ((status = Win32.SamOpenAlias(
domainHandle,
access,
aliasId,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.Handle = handle;
}
public void AddMember(Sid sid)
{
- Win32.SamAddMemberToAlias(this, sid).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamAddMemberToAlias(this, sid)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddMembers(Sid[] sids)
{
+ NtStatus status;
IntPtr[] sidArray = new IntPtr[sids.Length];
for (int i = 0; i < sids.Length; i++)
sidArray[i] = sids[i];
- Win32.SamAddMultipleMembersToAlias(
+ if ((status = Win32.SamAddMultipleMembersToAlias(
this,
sidArray,
sids.Length
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void Delete()
{
- Win32.SamDeleteAlias(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamDeleteAlias(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
private SamMemoryAlloc GetInformation(AliasInformationClass infoClass)
{
+ NtStatus status;
IntPtr buffer;
- Win32.SamQueryInformationAlias(
+ if ((status = Win32.SamQueryInformationAlias(
this,
infoClass,
out buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new SamMemoryAlloc(buffer);
}
- public string AdminComment
+ public string GetAdminComment()
{
- get
+ using (var data = this.GetInformation(AliasInformationClass.AliasAdminCommentInformation))
{
- using (SamMemoryAlloc data = this.GetInformation(AliasInformationClass.AliasAdminCommentInformation))
- {
- return data.ReadStruct().AdminComment.Text;
- }
+ return data.ReadStruct().AdminComment.Read();
}
}
- public Sid[] Members
+ public Sid[] GetMembers()
{
- get
- {
- IntPtr members;
- int count;
+ NtStatus status;
+ IntPtr members;
+ int count;
- Win32.SamGetMembersInAlias(
- this,
- out members,
- out count
- ).ThrowIf();
+ if ((status = Win32.SamGetMembersInAlias(
+ this,
+ out members,
+ out count
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (SamMemoryAlloc membersAlloc = new SamMemoryAlloc(members))
- {
- Sid[] sids = new Sid[count];
+ using (var membersAlloc = new SamMemoryAlloc(members))
+ {
+ Sid[] sids = new Sid[count];
- for (int i = 0; i < sids.Length; i++)
- sids[i] = new Sid(membersAlloc.ReadIntPtr(0, i));
+ for (int i = 0; i < sids.Length; i++)
+ sids[i] = new Sid(membersAlloc.ReadIntPtr(0, i));
- return sids;
- }
+ return sids;
}
}
- public string Name
+ public string GetName()
{
- get
+ using (var data = this.GetInformation(AliasInformationClass.AliasNameInformation))
{
- using (SamMemoryAlloc data = this.GetInformation(AliasInformationClass.AliasNameInformation))
- {
- return data.ReadStruct().Name.Text;
- }
+ return data.ReadStruct().Name.Read();
}
}
public void RemoveMember(Sid sid)
{
- Win32.SamRemoveMemberFromAlias(this, sid).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamRemoveMemberFromAlias(this, sid)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void RemoveMembers(Sid[] sids)
{
+ NtStatus status;
IntPtr[] sidArray = new IntPtr[sids.Length];
for (int i = 0; i < sids.Length; i++)
sidArray[i] = sids[i];
- Win32.SamRemoveMultipleMembersFromAlias(
+ if ((status = Win32.SamRemoveMultipleMembersFromAlias(
this,
sidArray,
sids.Length
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SamDomainHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SamDomainHandle.cs
index 12df34bac..a9a068a59 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SamDomainHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SamDomainHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -85,44 +86,49 @@ public SamDomainHandle(SamServerHandle serverHandle, string name, SamDomainAcces
/// The desired access to the domain.
public SamDomainHandle(SamServerHandle serverHandle, Sid domainId, SamDomainAccess access)
{
+ NtStatus status;
IntPtr handle;
- Win32.SamOpenDomain(
+ if ((status = Win32.SamOpenDomain(
serverHandle,
access,
domainId,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.Handle = handle;
}
public void EnumAliases(EnumAliasesDelegate callback)
{
+ NtStatus status;
int enumerationContext = 0;
IntPtr buffer;
int count;
while (true)
{
- Win32.SamEnumerateAliasesInDomain(
+ status = Win32.SamEnumerateAliasesInDomain(
this,
ref enumerationContext,
out buffer,
0x100,
out count
- ).ThrowIf();
+ );
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
if (count == 0)
break;
- using (SamMemoryAlloc bufferAlloc = new SamMemoryAlloc(buffer))
+ using (var bufferAlloc = new SamMemoryAlloc(buffer))
{
for (int i = 0; i < count; i++)
{
- SamRidEnumeration data = bufferAlloc.ReadStruct(0, SamRidEnumeration.SizeOf, i);
+ var data = bufferAlloc.ReadStruct(i);
- if (!callback(data.Name.Text, data.RelativeId))
+ if (!callback(data.Name.Read(), data.RelativeId))
return;
}
}
@@ -131,30 +137,33 @@ out count
public void EnumGroups(EnumGroupsDelegate callback)
{
+ NtStatus status;
int enumerationContext = 0;
IntPtr buffer;
int count;
while (true)
{
- Win32.SamEnumerateGroupsInDomain(
+ status = Win32.SamEnumerateGroupsInDomain(
this,
ref enumerationContext,
out buffer,
0x100,
out count
- ).ThrowIf();
+ );
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
if (count == 0)
break;
- using (SamMemoryAlloc bufferAlloc = new SamMemoryAlloc(buffer))
+ using (var bufferAlloc = new SamMemoryAlloc(buffer))
{
for (int i = 0; i < count; i++)
{
- SamRidEnumeration data = bufferAlloc.ReadStruct(0, SamRidEnumeration.SizeOf, i);
+ var data = bufferAlloc.ReadStruct(i);
- if (!callback(data.Name.Text, data.RelativeId))
+ if (!callback(data.Name.Read(), data.RelativeId))
return;
}
}
@@ -168,31 +177,34 @@ public void EnumUsers(EnumUsersDelegate callback)
public void EnumUsers(EnumUsersDelegate callback, UserAccountFlags flags)
{
+ NtStatus status;
int enumerationContext = 0;
IntPtr buffer;
int count;
while (true)
{
- Win32.SamEnumerateUsersInDomain(
+ status = Win32.SamEnumerateUsersInDomain(
this,
ref enumerationContext,
flags,
out buffer,
0x100,
out count
- ).ThrowIf();
+ );
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
if (count == 0)
break;
- using (SamMemoryAlloc bufferAlloc = new SamMemoryAlloc(buffer))
+ using (var bufferAlloc = new SamMemoryAlloc(buffer))
{
for (int i = 0; i < count; i++)
{
- var data = bufferAlloc.ReadStruct(0, SamRidEnumeration.SizeOf, i);
+ var data = bufferAlloc.ReadStruct(i);
- if (!callback(data.Name.Text, data.RelativeId))
+ if (!callback(data.Name.Read(), data.RelativeId))
return;
}
}
@@ -201,44 +213,50 @@ out count
public int[] GetAliasMembership(Sid sid)
{
+ NtStatus status;
IntPtr aliases;
int count;
- Win32.SamGetAliasMembership(
+ if ((status = Win32.SamGetAliasMembership(
this,
1,
new IntPtr[] { sid },
out count,
out aliases
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (aliases != IntPtr.Zero)
{
using (var aliasesAlloc = new SamMemoryAlloc(aliases))
return aliasesAlloc.ReadInt32Array(0, count);
}
-
- return new int[0];
+ else
+ {
+ return new int[0];
+ }
}
private SamMemoryAlloc GetInformation(DomainInformationClass infoClass)
{
+ NtStatus status;
IntPtr buffer;
- Win32.SamQueryInformationDomain(
+ if ((status = Win32.SamQueryInformationDomain(
this,
infoClass,
out buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new SamMemoryAlloc(buffer);
}
public DomainPasswordPolicy GetPasswordPolicy()
{
- using (SamMemoryAlloc data = this.GetInformation(DomainInformationClass.DomainPasswordInformation))
+ using (var data = this.GetInformation(DomainInformationClass.DomainPasswordInformation))
{
- DomainPasswordInformation info = data.ReadStruct();
+ var info = data.ReadStruct();
return new DomainPasswordPolicy(
info.MinPasswordLength,
@@ -252,15 +270,17 @@ public DomainPasswordPolicy GetPasswordPolicy()
public Sid GetSid(int relativeId)
{
+ NtStatus status;
IntPtr sid;
- Win32.SamRidToSid(
+ if ((status = Win32.SamRidToSid(
this,
relativeId,
out sid
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (SamMemoryAlloc sidAlloc = new SamMemoryAlloc(sid))
+ using (var sidAlloc = new SamMemoryAlloc(sid))
return new Sid(sidAlloc);
}
@@ -278,26 +298,28 @@ public string[] LookupIds(int[] relativeIds)
public string[] LookupIds(int[] relativeIds, out SidNameUse[] uses)
{
+ NtStatus status;
IntPtr names;
IntPtr use;
- Win32.SamLookupIdsInDomain(
+ if ((status = Win32.SamLookupIdsInDomain(
this,
relativeIds.Length,
relativeIds,
out names,
out use
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (SamMemoryAlloc namesAlloc = new SamMemoryAlloc(names))
- using (SamMemoryAlloc useAlloc = new SamMemoryAlloc(use))
+ using (var namesAlloc = new SamMemoryAlloc(names))
+ using (var useAlloc = new SamMemoryAlloc(use))
{
string[] nameArray = new string[relativeIds.Length];
SidNameUse[] useArray = new SidNameUse[relativeIds.Length];
for (int i = 0; i < relativeIds.Length; i++)
{
- nameArray[i] = namesAlloc.ReadStruct(0, UnicodeString.SizeOf, i).Text;
+ nameArray[i] = namesAlloc.ReadStruct(i).Read();
useArray[i] = (SidNameUse)useAlloc.ReadInt32(0, i);
}
@@ -321,23 +343,26 @@ public int[] LookupNames(string[] names)
public int[] LookupNames(string[] names, out SidNameUse[] uses)
{
+ NtStatus status;
+ UnicodeString[] nameStr;
IntPtr relativeIds;
IntPtr use;
- UnicodeString[] nameStr = new UnicodeString[names.Length];
+ nameStr = new UnicodeString[names.Length];
for (int i = 0; i < names.Length; i++)
nameStr[i] = new UnicodeString(names[i]);
try
{
- Win32.SamLookupNamesInDomain(
+ if ((status = Win32.SamLookupNamesInDomain(
this,
names.Length,
nameStr,
out relativeIds,
out use
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -345,8 +370,8 @@ out use
nameStr[i].Dispose();
}
- using (SamMemoryAlloc relativeIdsAlloc = new SamMemoryAlloc(relativeIds))
- using (SamMemoryAlloc useAlloc = new SamMemoryAlloc(use))
+ using (var relativeIdsAlloc = new SamMemoryAlloc(relativeIds))
+ using (var useAlloc = new SamMemoryAlloc(use))
{
SidNameUse[] useArray = new SidNameUse[names.Length];
@@ -361,25 +386,30 @@ out use
private void SetInformation(DomainInformationClass infoClass, IntPtr buffer)
{
- Win32.SamSetInformationDomain(
+ NtStatus status;
+
+ if ((status = Win32.SamSetInformationDomain(
this,
infoClass,
buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
- public unsafe void SetPasswordPolicy(DomainPasswordPolicy policy)
+ public void SetPasswordPolicy(DomainPasswordPolicy policy)
{
- DomainPasswordInformation info = new DomainPasswordInformation
+ unsafe
{
- MinPasswordLength = policy.MinPasswordLength,
- PasswordHistoryLength = policy.PasswordHistoryLength,
- PasswordProperties = policy.PasswordProperties,
- MaxPasswordAge = -policy.MaxPasswordAge.Ticks,
- MinPasswordAge = -policy.MinPasswordAge.Ticks
- };
-
- this.SetInformation(DomainInformationClass.DomainPasswordInformation, new IntPtr(&info));
+ DomainPasswordInformation info = new DomainPasswordInformation();
+
+ info.MinPasswordLength = policy.MinPasswordLength;
+ info.PasswordHistoryLength = policy.PasswordHistoryLength;
+ info.PasswordProperties = policy.PasswordProperties;
+ info.MaxPasswordAge = -policy.MaxPasswordAge.Ticks;
+ info.MinPasswordAge = -policy.MinPasswordAge.Ticks;
+
+ this.SetInformation(DomainInformationClass.DomainPasswordInformation, new IntPtr(&info));
+ }
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SamGroupHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SamGroupHandle.cs
index 0bc8d86e1..9b16d394f 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SamGroupHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SamGroupHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -33,19 +34,22 @@ public sealed class SamGroupHandle : SamHandle
{
public static SamGroupHandle Create(SamGroupAccess access, SamDomainHandle domainHandle, string name, out int groupId)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr handle;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.SamCreateGroupInDomain(
+ if ((status = Win32.SamCreateGroupInDomain(
domainHandle,
ref nameStr,
access,
out handle,
out groupId
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -62,7 +66,7 @@ public static SamGroupHandle Open(string name, SamGroupAccess access)
public static SamGroupHandle Open(Sid sid, SamGroupAccess access)
{
- using (SamDomainHandle dhandle = new SamDomainHandle(sid.DomainName, SamDomainAccess.Lookup))
+ using (var dhandle = new SamDomainHandle(sid.DomainName, SamDomainAccess.Lookup))
{
return new SamGroupHandle(dhandle, dhandle.LookupName(sid.Name), access);
}
@@ -80,89 +84,95 @@ private SamGroupHandle(IntPtr handle, bool owned)
/// The desired access to the group.
public SamGroupHandle(SamDomainHandle domainHandle, int groupId, SamGroupAccess access)
{
+ NtStatus status;
IntPtr handle;
- Win32.SamOpenGroup(
+ if ((status = Win32.SamOpenGroup(
domainHandle,
access,
groupId,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.Handle = handle;
}
public void AddMember(int memberId)
{
- Win32.SamAddMemberToGroup(this, memberId, 0).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamAddMemberToGroup(this, memberId, 0)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void Delete()
{
- Win32.SamDeleteGroup(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamDeleteGroup(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
private SamMemoryAlloc GetInformation(GroupInformationClass infoClass)
{
+ NtStatus status;
IntPtr buffer;
- Win32.SamQueryInformationGroup(
+ if ((status = Win32.SamQueryInformationGroup(
this,
infoClass,
out buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new SamMemoryAlloc(buffer);
}
- public string AdminComment
+ public string GetAdminComment()
{
- get
+ using (var data = this.GetInformation(GroupInformationClass.GroupAdminCommentInformation))
{
- using (SamMemoryAlloc data = this.GetInformation(GroupInformationClass.GroupAdminCommentInformation))
- {
- return data.ReadStruct().AdminComment.Text;
- }
+ return data.ReadStruct().AdminComment.Read();
}
}
- public int[] Members
+ public int[] GetMembers()
{
- get
+ NtStatus status;
+ IntPtr memberIds;
+ IntPtr attributes;
+ int count;
+
+ if ((status = Win32.SamGetMembersInGroup(
+ this,
+ out memberIds,
+ out attributes,
+ out count
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ using (var memberIdsAlloc = new SamMemoryAlloc(memberIds))
+ using (var attributesAlloc = new SamMemoryAlloc(attributes))
{
- IntPtr memberIds;
- IntPtr attributes;
- int count;
-
- Win32.SamGetMembersInGroup(
- this,
- out memberIds,
- out attributes,
- out count
- ).ThrowIf();
-
- using (SamMemoryAlloc memberIdsAlloc = new SamMemoryAlloc(memberIds))
- using (new SamMemoryAlloc(attributes))
- {
- return memberIdsAlloc.ReadInt32Array(0, count);
- }
+ return memberIdsAlloc.ReadInt32Array(0, count);
}
}
- public string Name
+ public string GetName()
{
- get
+ using (var data = this.GetInformation(GroupInformationClass.GroupNameInformation))
{
- using (SamMemoryAlloc data = this.GetInformation(GroupInformationClass.GroupNameInformation))
- {
- return data.ReadStruct().Name.Text;
- }
+ return data.ReadStruct().Name.Read();
}
}
public void RemoveMember(int memberId)
{
- Win32.SamRemoveMemberFromGroup(this, memberId).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamRemoveMemberFromGroup(this, memberId)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SamHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SamHandle.cs
index 7810a4cbd..f97e51d7d 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SamHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SamHandle.cs
@@ -46,24 +46,29 @@ protected override void Close()
public override SecurityDescriptor GetSecurity(SecurityInformation securityInformation)
{
+ NtStatus status;
IntPtr securityDescriptor;
- Win32.SamQuerySecurityObject(
+ if ((status = Win32.SamQuerySecurityObject(
this,
securityInformation,
out securityDescriptor
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new SecurityDescriptor(new SamMemoryAlloc(securityDescriptor));
}
public override void SetSecurity(SecurityInformation securityInformation, SecurityDescriptor securityDescriptor)
{
- Win32.SamSetSecurityObject(
+ NtStatus status;
+
+ if ((status = Win32.SamSetSecurityObject(
this,
securityInformation,
securityDescriptor
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SamServerHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SamServerHandle.cs
index df0f676e4..56e527a63 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SamServerHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SamServerHandle.cs
@@ -34,7 +34,7 @@ namespace ProcessHacker.Native.Objects
public sealed class SamServerHandle : SamHandle
{
private static WeakReference _connectServerHandle;
- private static int _connectServerHandleMisses;
+ private static int _connectServerHandleMisses = 0;
public static SamServerHandle ConnectServerHandle
{
@@ -45,7 +45,7 @@ public static SamServerHandle ConnectServerHandle
if (weakRef != null)
{
- weakRef.TryGetTarget(out connectHandle);
+ connectHandle = weakRef.Target;
}
if (connectHandle == null)
@@ -53,10 +53,9 @@ public static SamServerHandle ConnectServerHandle
System.Threading.Interlocked.Increment(ref _connectServerHandleMisses);
connectHandle = new SamServerHandle(SamServerAccess.GenericRead | SamServerAccess.GenericExecute);
+
if (connectHandle != null)
- {
_connectServerHandle = new WeakReference(connectHandle);
- }
}
return connectHandle;
@@ -85,18 +84,22 @@ public SamServerHandle(SamServerAccess access)
/// The desired access to the server.
public SamServerHandle(string serverName, SamServerAccess access)
{
- IntPtr handle;
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes();
- UnicodeString serverNameStr = new UnicodeString(serverName);
+ UnicodeString serverNameStr;
+ IntPtr handle;
+
+ serverNameStr = new UnicodeString(serverName);
try
{
- Win32.SamConnect(
+ if ((status = Win32.SamConnect(
ref serverNameStr,
out handle,
access,
ref oa
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -108,30 +111,33 @@ ref oa
public void EnumDomains(EnumDomainsDelegate callback)
{
+ NtStatus status;
int enumerationContext = 0;
IntPtr buffer;
int count;
while (true)
{
- Win32.SamEnumerateDomainsInSamServer(
+ status = Win32.SamEnumerateDomainsInSamServer(
this,
ref enumerationContext,
out buffer,
0x100,
out count
- ).ThrowIf();
+ );
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
if (count == 0)
break;
- using (SamMemoryAlloc bufferAlloc = new SamMemoryAlloc(buffer))
+ using (var bufferAlloc = new SamMemoryAlloc(buffer))
{
for (int i = 0; i < count; i++)
{
- SamSidEnumeration data = bufferAlloc.ReadStruct(0, SamSidEnumeration.SizeOf, i);
+ var data = bufferAlloc.ReadStruct(i);
- if (!callback(data.Name.Text))
+ if (!callback(data.Name.Read()))
return;
}
}
@@ -142,7 +148,7 @@ public string[] GetDomains()
{
List domains = new List();
- this.EnumDomains(name =>
+ this.EnumDomains((name) =>
{
domains.Add(name);
return true;
@@ -153,17 +159,20 @@ public string[] GetDomains()
public Sid LookupDomain(string name)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr domainId;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.SamLookupDomainInSamServer(
+ if ((status = Win32.SamLookupDomainInSamServer(
this,
ref nameStr,
out domainId
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -176,7 +185,10 @@ out domainId
public void Shutdown()
{
- Win32.SamShutdownSamServer(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamShutdownSamServer(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SamUserHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SamUserHandle.cs
index 0654bc6e5..dcc30fc12 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SamUserHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SamUserHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Collections.Generic;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -33,19 +34,22 @@ public sealed class SamUserHandle : SamHandle
{
public static SamUserHandle Create(SamUserAccess access, SamDomainHandle domainHandle, string name, out int userId)
{
+ NtStatus status;
+ UnicodeString nameStr;
IntPtr handle;
- UnicodeString nameStr = new UnicodeString(name);
+ nameStr = new UnicodeString(name);
try
{
- Win32.SamCreateUserInDomain(
+ if ((status = Win32.SamCreateUserInDomain(
domainHandle,
ref nameStr,
access,
out handle,
out userId
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -84,30 +88,37 @@ public SamUserHandle(SamDomainHandle domainHandle, string name, SamUserAccess ac
/// The desired access to the user.
public SamUserHandle(SamDomainHandle domainHandle, int userId, SamUserAccess access)
{
+ NtStatus status;
IntPtr handle;
- Win32.SamOpenUser(
+ if ((status = Win32.SamOpenUser(
domainHandle,
access,
userId,
out handle
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.Handle = handle;
}
public void ChangePassword(string oldPassword, string newPassword)
{
- UnicodeString oldPasswordStr = new UnicodeString(oldPassword);
- UnicodeString newPasswordStr = new UnicodeString(newPassword);
+ NtStatus status;
+ UnicodeString oldPasswordStr;
+ UnicodeString newPasswordStr;
+
+ oldPasswordStr = new UnicodeString(oldPassword);
+ newPasswordStr = new UnicodeString(newPassword);
try
{
- Win32.SamChangePasswordUser(
+ if ((status = Win32.SamChangePasswordUser(
this,
ref oldPasswordStr,
ref newPasswordStr
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -118,221 +129,220 @@ ref newPasswordStr
public void Delete()
{
- Win32.SamDeleteUser(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.SamDeleteUser(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
- public string AdminComment
+ public string GetAdminComment()
{
- get { return this.Information.AdminComment; }
+ return this.GetInformation().AdminComment;
}
- public UserAccountFlags Flags
+ public UserAccountFlags GetFlags()
{
- get { return this.Information.UserFlags; }
+ return this.GetInformation().UserFlags;
}
- public string FullName
+ public string GetFullName()
{
- get
- {
- using (SamMemoryAlloc data = this.GetInformation(UserInformationClass.UserFullNameInformation))
- {
- return data.ReadStruct().FullName.Text;
- }
- }
+ using (var data = this.GetInformation(UserInformationClass.UserFullNameInformation))
+ return data.ReadStruct().FullName.Read();
}
- public int[] Groups
+ public int[] GetGroups()
{
- get
- {
- IntPtr groups;
- int count;
+ NtStatus status;
+ IntPtr groups;
+ int count;
- Win32.SamGetGroupsForUser(
- this,
- out groups,
- out count
- ).ThrowIf();
+ if ((status = Win32.SamGetGroupsForUser(
+ this,
+ out groups,
+ out count
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- using (SamMemoryAlloc groupsAlloc = new SamMemoryAlloc(groups))
- {
- return groupsAlloc.ReadInt32Array(0, count);
- }
+ using (var groupsAlloc = new SamMemoryAlloc(groups))
+ {
+ return groupsAlloc.ReadInt32Array(0, count);
}
}
- public SamUserInformation Information
+ public SamUserInformation GetInformation()
{
- get
+ using (var data = this.GetInformation(UserInformationClass.UserAllInformation))
{
- using (SamMemoryAlloc data = this.GetInformation(UserInformationClass.UserAllInformation))
- {
- UserAllInformation info = data.ReadStruct();
-
- return new SamUserInformation(
- SamDomainHandle.ToDateTime(info.LastLogon),
- SamDomainHandle.ToDateTime(info.LastLogoff),
- SamDomainHandle.ToDateTime(info.PasswordLastSet),
- SamDomainHandle.ToDateTime(info.AccountExpires),
- SamDomainHandle.ToDateTime(info.PasswordCanChange),
- SamDomainHandle.ToDateTime(info.PasswordMustChange),
- info.UserName.Text,
- info.FullName.Text,
- info.AdminComment.Text,
- info.UserComment.Text,
- info.UserId,
- info.PrimaryGroupId,
- info.UserAccountControl,
- info.PasswordExpired
- );
- }
+ UserAllInformation info = data.ReadStruct();
+
+ return new SamUserInformation(
+ SamDomainHandle.ToDateTime(info.LastLogon),
+ SamDomainHandle.ToDateTime(info.LastLogoff),
+ SamDomainHandle.ToDateTime(info.PasswordLastSet),
+ SamDomainHandle.ToDateTime(info.AccountExpires),
+ SamDomainHandle.ToDateTime(info.PasswordCanChange),
+ SamDomainHandle.ToDateTime(info.PasswordMustChange),
+ info.UserName.Read(),
+ info.FullName.Read(),
+ info.AdminComment.Read(),
+ info.UserComment.Read(),
+ info.UserId,
+ info.PrimaryGroupId,
+ info.UserAccountControl,
+ info.PasswordExpired
+ );
}
}
private SamMemoryAlloc GetInformation(UserInformationClass infoClass)
{
+ NtStatus status;
IntPtr buffer;
- Win32.SamQueryInformationUser(
+ if ((status = Win32.SamQueryInformationUser(
this,
infoClass,
out buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new SamMemoryAlloc(buffer);
}
- public string Name
+ public string GetName()
{
- get
- {
- using (SamMemoryAlloc data = this.GetInformation(UserInformationClass.UserAccountNameInformation))
- {
- return data.ReadStruct().UserName.Text;
- }
- }
+ using (var data = this.GetInformation(UserInformationClass.UserAccountNameInformation))
+ return data.ReadStruct().UserName.Read();
+ }
+
+ public string GetPasswordHint()
+ {
+ using (var data = this.GetInformation(UserInformationClass.UserExtendedInformation))
+ return data.ReadStruct().PasswordHint.Read();
}
- public string PasswordHint
+ public void SetAdminComment(string comment)
{
- get
+ unsafe
{
- using (SamMemoryAlloc data = this.GetInformation(UserInformationClass.UserExtendedInformation))
+ UserAllInformation info = new UserAllInformation();
+
+ info.WhichFields = UserWhichFields.AdminComment;
+ info.AdminComment = new UnicodeString(comment);
+
+ try
+ {
+ this.SetInformation(UserInformationClass.UserAllInformation, new IntPtr(&info));
+ }
+ finally
{
- return data.ReadStruct().PasswordHint.Text;
+ info.AdminComment.Dispose();
}
}
}
- public unsafe void SetAdminComment(string comment)
+ public void SetFlags(UserAccountFlags flags)
{
- UserAllInformation info = new UserAllInformation
+ unsafe
{
- WhichFields = UserWhichFields.AdminComment,
- AdminComment = new UnicodeString(comment)
- };
+ UserAllInformation info = new UserAllInformation();
+
+ info.WhichFields = UserWhichFields.UserAccountControl;
+ info.UserAccountControl = flags;
- try
- {
this.SetInformation(UserInformationClass.UserAllInformation, new IntPtr(&info));
}
- finally
- {
- info.AdminComment.Dispose();
- }
}
- public unsafe void SetFlags(UserAccountFlags flags)
+ public void SetFullName(string fullName)
{
- UserAllInformation info = new UserAllInformation
+ unsafe
{
- WhichFields = UserWhichFields.UserAccountControl,
- UserAccountControl = flags
- };
+ UserFullNameInformation info = new UserFullNameInformation();
- this.SetInformation(UserInformationClass.UserAllInformation, new IntPtr(&info));
- }
+ info.FullName = new UnicodeString(fullName);
- public unsafe void SetFullName(string fullName)
- {
- UserFullNameInformation info = new UserFullNameInformation
- {
- FullName = new UnicodeString(fullName)
- };
-
- try
- {
- this.SetInformation(UserInformationClass.UserFullNameInformation, new IntPtr(&info));
- }
- finally
- {
- info.FullName.Dispose();
+ try
+ {
+ this.SetInformation(UserInformationClass.UserFullNameInformation, new IntPtr(&info));
+ }
+ finally
+ {
+ info.FullName.Dispose();
+ }
}
}
private void SetInformation(UserInformationClass infoClass, IntPtr buffer)
{
- Win32.SamSetInformationUser(
+ NtStatus status;
+
+ if ((status = Win32.SamSetInformationUser(
this,
infoClass,
buffer
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
- public unsafe void SetPassword(string password, bool expired)
+ public void SetPassword(string password, bool expired)
{
- UserSetPasswordInformation info = new UserSetPasswordInformation
+ unsafe
{
- Password = new UnicodeString(password),
- PasswordExpired = expired
- };
+ UserSetPasswordInformation info = new UserSetPasswordInformation();
- try
- {
- this.SetInformation(UserInformationClass.UserSetPasswordInformation, new IntPtr(&info));
- }
- finally
- {
- info.Password.Dispose();
+ info.Password = new UnicodeString(password);
+ info.PasswordExpired = expired;
+
+ try
+ {
+ this.SetInformation(UserInformationClass.UserSetPasswordInformation, new IntPtr(&info));
+ }
+ finally
+ {
+ info.Password.Dispose();
+ }
}
}
- public unsafe void SetPasswordHint(string passwordHint)
+ public void SetPasswordHint(string passwordHint)
{
- UserExtendedInformation info = new UserExtendedInformation
+ unsafe
{
- ExtendedWhichFields = UserExtendedWhichFields.PasswordHint,
- PasswordHint = new UnicodeString(passwordHint)
- };
+ UserExtendedInformation info = new UserExtendedInformation();
- try
- {
- this.SetInformation(UserInformationClass.UserExtendedInformation, new IntPtr(&info));
- }
- finally
- {
- info.PasswordHint.Dispose();
+ info.ExtendedWhichFields = UserExtendedWhichFields.PasswordHint;
+ info.PasswordHint = new UnicodeString(passwordHint);
+
+ try
+ {
+ this.SetInformation(UserInformationClass.UserExtendedInformation, new IntPtr(&info));
+ }
+ finally
+ {
+ info.PasswordHint.Dispose();
+ }
}
}
}
public class SamUserInformation
{
- private readonly DateTime _lastLogon;
- private readonly DateTime _lastLogoff;
- private readonly DateTime _passwordLastSet;
- private readonly DateTime _accountExpires;
- private readonly DateTime _passwordCanChange;
- private readonly DateTime _passwordMustChange;
- private readonly string _userName;
- private readonly string _fullName;
- private readonly string _adminComment;
- private readonly string _userComment;
- private readonly int _userId;
- private readonly int _primaryGroupId;
- private readonly UserAccountFlags _userFlags;
- private readonly bool _passwordExpired;
+ private DateTime _lastLogon;
+ private DateTime _lastLogoff;
+ private DateTime _passwordLastSet;
+ private DateTime _accountExpires;
+ private DateTime _passwordCanChange;
+ private DateTime _passwordMustChange;
+ private string _userName;
+ private string _fullName;
+ private string _adminComment;
+ private string _userComment;
+ private int _userId;
+ private int _primaryGroupId;
+ private UserAccountFlags _userFlags;
+ private bool _passwordExpired;
public SamUserInformation(
DateTime lastLogon,
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SectionHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SectionHandle.cs
index 146ef2d9c..014957f95 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SectionHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SectionHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -82,6 +83,7 @@ public static SectionHandle Create(
FileHandle fileHandle
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
@@ -89,7 +91,7 @@ FileHandle fileHandle
{
if (maximumSize != 0)
{
- Win32.NtCreateSection(
+ if ((status = Win32.NtCreateSection(
out handle,
access,
ref oa,
@@ -97,11 +99,12 @@ FileHandle fileHandle
pageAttributes,
sectionAttributes,
fileHandle ?? IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
else
{
- Win32.NtCreateSection(
+ if ((status = Win32.NtCreateSection(
out handle,
access,
ref oa,
@@ -109,7 +112,8 @@ FileHandle fileHandle
pageAttributes,
sectionAttributes,
fileHandle ?? IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
finally
@@ -131,12 +135,14 @@ private SectionHandle(IntPtr handle, bool owned)
public SectionHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, SectionAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenSection(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenSection(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -152,39 +158,36 @@ public SectionHandle(string name, SectionAccess access)
public long Extend(long newSize)
{
- Win32.NtExtendSection(this, ref newSize).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtExtendSection(this, ref newSize)) >= NtStatus.Error)
+ Win32.Throw(status);
return newSize;
}
public SectionBasicInformation GetBasicInformation()
{
+ NtStatus status;
SectionBasicInformation sbi;
IntPtr retLength;
- Win32.NtQuerySection(
- this,
- SectionInformationClass.SectionBasicInformation,
- out sbi,
- new IntPtr(SectionBasicInformation.SizeOf),
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQuerySection(this, SectionInformationClass.SectionBasicInformation,
+ out sbi, new IntPtr(Marshal.SizeOf(typeof(SectionBasicInformation))), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
return sbi;
}
public SectionImageInformation GetImageInformation()
{
+ NtStatus status;
SectionImageInformation sii;
IntPtr retLength;
- Win32.NtQuerySection(
- this,
- SectionInformationClass.SectionImageInformation,
- out sii,
- new IntPtr(SectionImageInformation.SizeOf),
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQuerySection(this, SectionInformationClass.SectionImageInformation,
+ out sii, new IntPtr(Marshal.SizeOf(typeof(SectionImageInformation))), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
return sii;
}
@@ -230,9 +233,11 @@ public SectionView MapView(
MemoryProtection protection
)
{
+ NtStatus status;
+
// sectionOffset requires 2 << 15 = 0x10000 = 65536 alignment.
// viewSize will be rounded up to the page size.
- Win32.NtMapViewOfSection(
+ if ((status = Win32.NtMapViewOfSection(
this,
processHandle,
ref baseAddress,
@@ -243,7 +248,8 @@ MemoryProtection protection
inheritDisposition,
allocationType,
protection
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new SectionView(baseAddress, viewSize);
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs
index 735767bec..c73cdc2af 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SemaphoreHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -40,18 +41,15 @@ public static SemaphoreHandle Create(SemaphoreAccess access, string name, int in
public static SemaphoreHandle Create(SemaphoreAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, int initialCount, int maximumCount)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateSemaphore(
- out handle,
- access,
- ref oa,
- initialCount,
- maximumCount
- ).ThrowIf();
+ if ((status = Win32.NtCreateSemaphore(out handle, access, ref oa,
+ initialCount, maximumCount)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -72,12 +70,14 @@ private SemaphoreHandle(IntPtr handle, bool owned)
public SemaphoreHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, SemaphoreAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenSemaphore(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenSemaphore(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -93,16 +93,13 @@ public SemaphoreHandle(string name, SemaphoreAccess access)
public SemaphoreBasicInformation GetBasicInformation()
{
+ NtStatus status;
SemaphoreBasicInformation sbi;
int retLength;
- Win32.NtQuerySemaphore(
- this,
- SemaphoreInformationClass.SemaphoreBasicInformation,
- out sbi,
- SemaphoreBasicInformation.SizeOf,
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQuerySemaphore(this, SemaphoreInformationClass.SemaphoreBasicInformation,
+ out sbi, Marshal.SizeOf(typeof(SemaphoreBasicInformation)), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
return sbi;
}
@@ -114,9 +111,11 @@ public int Release()
public int Release(int count)
{
+ NtStatus status;
int previousCount;
- Win32.NtReleaseSemaphore(this, count, out previousCount).ThrowIf();
+ if ((status = Win32.NtReleaseSemaphore(this, count, out previousCount)) >= NtStatus.Error)
+ Win32.Throw(status);
return previousCount;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/ServiceHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/ServiceHandle.cs
index 5aabc23f8..543adb999 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/ServiceHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/ServiceHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
using ProcessHacker.Native.Security.AccessControl;
@@ -95,7 +96,8 @@ public ServiceHandle(string serviceName)
/// The desired access to the service.
public ServiceHandle(string serviceName, ServiceAccess access)
{
- using (ServiceManagerHandle manager = new ServiceManagerHandle(ScManagerAccess.Connect))
+ using (ServiceManagerHandle manager =
+ new ServiceManagerHandle(ScManagerAccess.Connect))
{
this.Handle = Win32.OpenService(manager, serviceName, access);
@@ -113,7 +115,7 @@ public ServiceHandle(string serviceName, ServiceAccess access)
/// The message.
public void Control(ServiceControl control)
{
- ServiceStatus status;
+ ServiceStatus status = new ServiceStatus();
if (!Win32.ControlService(this, control, out status))
Win32.Throw();
@@ -133,7 +135,7 @@ public void Delete()
///
public QueryServiceConfig GetConfig()
{
- int requiredSize;
+ int requiredSize = 0;
Win32.QueryServiceConfig(this, IntPtr.Zero, 0, out requiredSize);
@@ -179,7 +181,7 @@ public ServiceStatusProcess GetStatus()
ServiceStatusProcess status;
int retLen;
- if (!Win32.QueryServiceStatusEx(this, 0, out status, ServiceStatusProcess.SizeOf, out retLen))
+ if (!Win32.QueryServiceStatusEx(this, 0, out status, Marshal.SizeOf(typeof(ServiceStatusProcess)), out retLen))
Win32.Throw();
return status;
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/ServiceManagerHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/ServiceManagerHandle.cs
index 8a5769847..854f838f6 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/ServiceManagerHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/ServiceManagerHandle.cs
@@ -60,25 +60,15 @@ public ServiceHandle CreateService(string name, string displayName,
ServiceErrorControl.Ignore, binaryPath, null, null, null);
}
- public ServiceHandle CreateService(string name, string displayName, ServiceType type, ServiceStartType startType, ServiceErrorControl errorControl, string binaryPath, string group, string accountName, string password)
+ public ServiceHandle CreateService(string name, string displayName,
+ ServiceType type, ServiceStartType startType, ServiceErrorControl errorControl,
+ string binaryPath, string group, string accountName, string password)
{
- IntPtr service = Win32.CreateService(
- this,
- name,
- displayName,
- ServiceAccess.All,
- type,
- startType,
- errorControl,
- binaryPath,
- group,
- IntPtr.Zero,
- IntPtr.Zero,
- accountName,
- password
- );
+ IntPtr service;
- if (service == IntPtr.Zero)
+ if ((service = Win32.CreateService(this, name, displayName, ServiceAccess.All,
+ type, startType, errorControl, binaryPath, group,
+ IntPtr.Zero, IntPtr.Zero, accountName, password)) == IntPtr.Zero)
Win32.Throw();
return new ServiceHandle(service, true);
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs
index d9282db85..fc0e3148f 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/SymbolicLinkHandle.cs
@@ -35,6 +35,7 @@ public static SymbolicLinkHandle Create(SymbolicLinkAccess access, string name,
public static SymbolicLinkHandle Create(SymbolicLinkAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, string linkTarget)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
@@ -44,12 +45,9 @@ public static SymbolicLinkHandle Create(SymbolicLinkAccess access, string name,
try
{
- Win32.NtCreateSymbolicLinkObject(
- out handle,
- access,
- ref oa,
- ref linkTargetString
- ).ThrowIf();
+ if ((status = Win32.NtCreateSymbolicLinkObject(out handle, access,
+ ref oa, ref linkTargetString)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -70,12 +68,14 @@ private SymbolicLinkHandle(IntPtr handle, bool owned)
public SymbolicLinkHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, SymbolicLinkAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenSymbolicLinkObject(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenSymbolicLinkObject(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -89,30 +89,29 @@ public SymbolicLinkHandle(string name, SymbolicLinkAccess access)
: this(name, 0, null, access)
{ }
- public string Target
+ public string GetTarget()
{
- get
+ NtStatus status;
+ int retLength;
+ UnicodeString str = new UnicodeString();
+
+ using (var buffer = new MemoryAlloc(0x200))
{
- int retLength;
- UnicodeString str = new UnicodeString();
+ str.Length = 0;
+ str.MaximumLength = (ushort)buffer.Size;
+ str.Buffer = buffer;
- using (MemoryAlloc buffer = new MemoryAlloc(0x200))
+ if ((status = Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength)) >= NtStatus.Error)
{
- str.Length = 0;
- str.MaximumLength = (ushort)buffer.Size;
+ buffer.ResizeNew(retLength);
+ str.MaximumLength = (ushort)retLength;
str.Buffer = buffer;
+ }
- if (Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength).IsError())
- {
- buffer.ResizeNew(retLength);
- str.MaximumLength = (ushort)retLength;
- str.Buffer = buffer;
- }
-
- Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength).ThrowIf();
+ if ((status = Win32.NtQuerySymbolicLinkObject(this, ref str, out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
- return str.Text;
- }
+ return str.Read();
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/TerminalServerHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/TerminalServerHandle.cs
index 4cbeb52dd..ae7bb2991 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/TerminalServerHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/TerminalServerHandle.cs
@@ -74,7 +74,7 @@ public static void UnregisterNotificationsCurrent(IWin32Window window)
Win32.Throw();
}
- private readonly string _systemName;
+ private string _systemName;
private TerminalServerHandle(IntPtr handle, bool owned)
: base(handle, owned)
@@ -120,13 +120,13 @@ public TerminalServerProcess[] GetProcesses()
if (!Win32.WTSEnumerateProcesses(this, 0, 1, out dataPtr, out count))
Win32.Throw();
- using (WtsMemoryAlloc data = new WtsMemoryAlloc(dataPtr))
+ using (var data = new WtsMemoryAlloc(dataPtr))
{
processes = new TerminalServerProcess[count];
for (int i = 0; i < count; i++)
{
- var process = data.ReadStruct(0, WtsProcessInfo.SizeOf, i);
+ var process = data.ReadStruct(i);
processes[i] = new TerminalServerProcess(
process.ProcessId,
process.SessionId,
@@ -157,18 +157,18 @@ public TerminalServerSession[] GetSessions()
{
IntPtr dataPtr;
int count;
+ TerminalServerSession[] sessions;
if (!Win32.WTSEnumerateSessions(this, 0, 1, out dataPtr, out count))
Win32.Throw();
- using (WtsMemoryAlloc data = new WtsMemoryAlloc(dataPtr))
+ using (var data = new WtsMemoryAlloc(dataPtr))
{
- TerminalServerSession[] sessions = new TerminalServerSession[count];
+ sessions = new TerminalServerSession[count];
for (int i = 0; i < count; i++)
{
- WtsSessionInfo session = data.ReadStruct(0, WtsSessionInfo.SizeOf, i);
-
+ var session = data.ReadStruct(i);
sessions[i] = new TerminalServerSession(
this,
session.SessionID,
@@ -235,8 +235,8 @@ public static int GetActiveConsoleId()
return Win32.WTSGetActiveConsoleSessionId();
}
- private readonly TerminalServerHandle _serverHandle;
- private readonly int _sessionId;
+ private TerminalServerHandle _serverHandle;
+ private int _sessionId;
private string _name;
private WtsConnectStateClass _state = (WtsConnectStateClass)(-1);
private string _initialProgram;
@@ -291,7 +291,8 @@ public WtsConnectStateClass State
IntPtr dataPtr;
int length;
- if (!Win32.WTSQuerySessionInformation(_serverHandle, _sessionId, WtsInformationClass.ConnectState, out dataPtr, out length))
+ if (!Win32.WTSQuerySessionInformation(
+ _serverHandle, _sessionId, WtsInformationClass.ConnectState, out dataPtr, out length))
Win32.Throw();
using (var data = new WtsMemoryAlloc(dataPtr))
@@ -381,17 +382,21 @@ public System.Net.IPAddress ClientAddress
IntPtr dataPtr;
int length;
- if (!Win32.WTSQuerySessionInformation(_serverHandle, _sessionId, WtsInformationClass.ClientAddress, out dataPtr, out length))
+ if (!Win32.WTSQuerySessionInformation(
+ _serverHandle, _sessionId, WtsInformationClass.ClientAddress, out dataPtr, out length))
Win32.Throw();
if (dataPtr != IntPtr.Zero)
{
- using (WtsMemoryAlloc data = new WtsMemoryAlloc(dataPtr))
+ unsafe
{
- WtsClientAddress address = data.ReadStruct();
+ using (var data = new WtsMemoryAlloc(dataPtr))
+ {
+ var address = data.ReadStruct();
- if (address.AddressFamily != 0)
- this._clientAddress = new System.Net.IPAddress(data.ReadBytes(6, 4));
+ if (address.AddressFamily != 0)
+ _clientAddress = new System.Net.IPAddress(data.ReadBytes(6, 4));
+ }
}
}
}
@@ -404,12 +409,13 @@ public WtsClientDisplay ClientDisplay
{
get
{
- if (!_clientDisplay.HasValue)
+ if (_clientDisplay == null)
{
IntPtr dataPtr;
int length;
- if (!Win32.WTSQuerySessionInformation(_serverHandle, _sessionId, WtsInformationClass.ClientDisplay, out dataPtr, out length))
+ if (!Win32.WTSQuerySessionInformation(
+ _serverHandle, _sessionId, WtsInformationClass.ClientDisplay, out dataPtr, out length))
Win32.Throw();
if (dataPtr != IntPtr.Zero)
@@ -508,10 +514,10 @@ bool synchronous
public class TerminalServerProcess
{
- private readonly int _processId;
- private readonly int _sessionId;
- private readonly string _name;
- private readonly Sid _sid;
+ private int _processId;
+ private int _sessionId;
+ private string _name;
+ private Sid _sid;
internal TerminalServerProcess(int processId, int sessionId, string name, Sid sid)
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs
index 7ed9432c9..5127762b1 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/ThreadHandle.cs
@@ -23,6 +23,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Runtime.InteropServices;
using ProcessHacker.Common;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -58,12 +59,13 @@ public static ThreadHandle Create(
bool createSuspended
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateThread(
+ if ((status = Win32.NtCreateThread(
out handle,
access,
ref oa,
@@ -72,7 +74,8 @@ bool createSuspended
ref threadContext,
ref initialTeb,
createSuspended
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -109,9 +112,10 @@ public static ThreadHandle CreateUserThread(
out ClientId clientId
)
{
+ NtStatus status;
IntPtr threadHandle;
- Win32.RtlCreateUserThread(
+ if ((status = Win32.RtlCreateUserThread(
processHandle,
IntPtr.Zero,
createSuspended,
@@ -122,7 +126,8 @@ out ClientId clientId
parameter,
out threadHandle,
out clientId
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return new ThreadHandle(threadHandle, true);
}
@@ -153,7 +158,7 @@ public static ThreadHandle GetCurrent()
/// A client ID.
public static ClientId GetCurrentCid()
{
- return new ClientId(ProcessHandle.CurrentId, GetCurrentId());
+ return new ClientId(ProcessHandle.GetCurrentId(), ThreadHandle.GetCurrentId());
}
///
@@ -223,7 +228,10 @@ public static ThreadHandle OpenWithAnyAccess(int tid)
/// A handle to a port.
public static void RegisterTerminationPort(PortHandle portHandle)
{
- Win32.NtRegisterThreadTerminatePort(portHandle).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRegisterThreadTerminatePort(portHandle)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -269,7 +277,12 @@ public static NtStatus Sleep(bool alertable, long timeout, bool relative)
///
public static NtStatus TestAlert()
{
- return Win32.NtTestAlert();
+ NtStatus status;
+
+ if ((status = Win32.NtTestAlert()) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return status;
}
///
@@ -299,24 +312,24 @@ public ThreadHandle(int tid)
/// The desired access to the thread.
public ThreadHandle(int tid, ThreadAccess access)
{
- //if (KProcessHacker.Instance != null)
- //{
- // try
- // {
- // this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenThread(tid, access));
- // }
- // catch (WindowsException)
- // {
- // // Open the thread with minimum access (SYNCHRONIZE) and set the granted access.
- // this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenThread(tid,
- // (ThreadAccess)StandardRights.Synchronize));
- // KProcessHacker.Instance.KphSetHandleGrantedAccess(this.Handle, (int)access);
- // }
- //}
- //else
- //{
+ if (KProcessHacker.Instance != null)
+ {
+ try
+ {
+ this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenThread(tid, access));
+ }
+ catch (WindowsException)
+ {
+ // Open the thread with minimum access (SYNCHRONIZE) and set the granted access.
+ this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenThread(tid,
+ (ThreadAccess)StandardRights.Synchronize));
+ KProcessHacker.Instance.KphSetHandleGrantedAccess(this.Handle, (int)access);
+ }
+ }
+ else
+ {
this.Handle = Win32.OpenThread(access, false, tid);
- //}
+ }
if (this.Handle == IntPtr.Zero)
{
@@ -333,6 +346,7 @@ public ThreadHandle(
ThreadAccess access
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
@@ -340,21 +354,23 @@ ThreadAccess access
{
if (clientId.ProcessId == 0 && clientId.ThreadId == 0)
{
- Win32.NtOpenThread(
+ if ((status = Win32.NtOpenThread(
out handle,
access,
ref oa,
IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
else
{
- Win32.NtOpenThread(
+ if ((status = Win32.NtOpenThread(
out handle,
access,
ref oa,
ref clientId
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
finally
@@ -374,7 +390,10 @@ public ThreadHandle(string name, ThreadAccess access)
///
public void Alert()
{
- Win32.NtAlertThread(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtAlertThread(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -382,9 +401,11 @@ public void Alert()
///
public int AlertResume()
{
+ NtStatus status;
int suspendCount;
- Win32.NtAlertResumeThread(this, out suspendCount).ThrowIf();
+ if ((status = Win32.NtAlertResumeThread(this, out suspendCount)) >= NtStatus.Error)
+ Win32.Throw(status);
return suspendCount;
}
@@ -405,24 +426,24 @@ public IntPtr[] CaptureKernelStack()
/// An array of function addresses.
public IntPtr[] CaptureKernelStack(int skipCount)
{
- //IntPtr[] stack = new IntPtr[62 - skipCount]; // 62 limit for XP and Server 2003
- //int hash;
+ IntPtr[] stack = new IntPtr[62 - skipCount]; // 62 limit for XP and Server 2003
+ int hash;
// Capture a kernel-mode stack trace.
- //int captured = KProcessHacker.Instance.KphCaptureStackBackTraceThread(
- // this,
- // skipCount,
- // stack.Length,
- // stack,
- // out hash
- // );
+ int captured = KProcessHacker.Instance.KphCaptureStackBackTraceThread(
+ this,
+ skipCount,
+ stack.Length,
+ stack,
+ out hash
+ );
// Create a new array with only the frames we captured.
- //IntPtr[] newStack = new IntPtr[captured];
+ IntPtr[] newStack = new IntPtr[captured];
- //Array.Copy(stack, 0, newStack, 0, captured);
+ Array.Copy(stack, 0, newStack, 0, captured);
- return null;// newStack;
+ return newStack;
}
///
@@ -444,7 +465,7 @@ public ThreadStackFrame[] CaptureUserStack(int skipCount)
List frames = new List();
// Walk the stack.
- this.WalkStack(frame => { frames.Add(frame); return true; });
+ this.WalkStack((frame) => { frames.Add(frame); return true; });
// If we want to skip frames than we have, just return an empty array.
if (frames.Count <= skipCount)
@@ -465,7 +486,7 @@ public ThreadStackFrame[] CaptureUserStack(int skipCount)
/// The exit status.
public void DangerousTerminate(NtStatus exitStatus)
{
- //KProcessHacker.Instance.KphDangerousTerminateThread(this, exitStatus);
+ KProcessHacker.Instance.KphDangerousTerminateThread(this, exitStatus);
}
///
@@ -496,16 +517,13 @@ public ThreadPriorityLevel GetBasePriorityWin32()
/// A THREAD_BASIC_INFORMATION structure.
public ThreadBasicInformation GetBasicInformation()
{
+ NtStatus status;
ThreadBasicInformation basicInfo = new ThreadBasicInformation();
int retLen;
- Win32.NtQueryInformationThread(
- this,
- ThreadInformationClass.ThreadBasicInformation,
- ref basicInfo,
- ThreadBasicInformation.SizeOf,
- out retLen
- ).ThrowIf();
+ if ((status = Win32.NtQueryInformationThread(this, ThreadInformationClass.ThreadBasicInformation,
+ ref basicInfo, Marshal.SizeOf(basicInfo), out retLen)) >= NtStatus.Error)
+ Win32.Throw(status);
return basicInfo;
}
@@ -516,11 +534,9 @@ out retLen
/// A CONTEXT struct.
public Context GetContext(ContextFlags flags)
{
- Context context = new Context
- {
- ContextFlags = flags
- };
+ Context context = new Context();
+ context.ContextFlags = flags;
this.GetContext(ref context);
return context;
@@ -532,7 +548,18 @@ public Context GetContext(ContextFlags flags)
/// A Context structure. The ContextFlags must be set appropriately.
public unsafe void GetContext(ref Context context)
{
- Win32.NtGetContextThread(this, ref context).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ fixed (Context* contextPtr = &context)
+ KProcessHacker.Instance.KphGetContextThread(this, contextPtr);
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = Win32.NtGetContextThread(this, ref context)) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
}
///
@@ -541,11 +568,9 @@ public unsafe void GetContext(ref Context context)
/// A CONTEXT struct.
public ContextAmd64 GetContext(ContextFlagsAmd64 flags)
{
- ContextAmd64 context = new ContextAmd64
- {
- ContextFlags = flags
- };
+ ContextAmd64 context = new ContextAmd64();
+ context.ContextFlags = flags;
this.GetContext(ref context);
return context;
@@ -557,13 +582,16 @@ public ContextAmd64 GetContext(ContextFlagsAmd64 flags)
/// A Context structure. The ContextFlags must be set appropriately.
public void GetContext(ref ContextAmd64 context)
{
+ NtStatus status;
+
// HACK: To avoid a datatype misalignment error, allocate some
// aligned memory.
- using (AlignedMemoryAlloc data = new AlignedMemoryAlloc(Utils.SizeOf(16, ContextAmd64.SizeOf), 16))
+ using (var data = new AlignedMemoryAlloc(Utils.SizeOf(16), 16))
{
- data.WriteStruct(context);
+ data.WriteStruct(context);
- Win32.NtGetContextThread(this, data).ThrowIf();
+ if ((status = Win32.NtGetContextThread(this, data)) >= NtStatus.Error)
+ Win32.Throw(status);
context = data.ReadStruct();
}
@@ -576,7 +604,10 @@ public void GetContext(ref ContextAmd64 context)
/// A Context structure. The ContextFlags must be set appropriately.
public void GetContextWow64(ref Context context)
{
- Win32.RtlWow64GetThreadContext(this, ref context).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.RtlWow64GetThreadContext(this, ref context)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -617,32 +648,46 @@ public NtStatus GetExitStatus()
private int GetInformationInt32(ThreadInformationClass infoClass)
{
- int value;
- int retLength;
-
- Win32.NtQueryInformationThread(
- this,
- infoClass,
- out value,
- sizeof(int),
- out retLength
- ).ThrowIf();
+ if (
+ KProcessHacker.Instance != null &&
+ infoClass == ThreadInformationClass.ThreadIoPriority
+ )
+ {
+ unsafe
+ {
+ int value;
+ int retLength;
- return value;
+ KProcessHacker.Instance.KphQueryInformationThread(
+ this, infoClass, new IntPtr(&value), sizeof(int), out retLength
+ );
+
+ return value;
+ }
+ }
+ else
+ {
+ NtStatus status;
+ int value;
+ int retLength;
+
+ if ((status = Win32.NtQueryInformationThread(
+ this, infoClass, out value, sizeof(int), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return value;
+ }
}
private IntPtr GetInformationIntPtr(ThreadInformationClass infoClass)
{
+ NtStatus status;
IntPtr value;
int retLength;
- Win32.NtQueryInformationThread(
- this,
- infoClass,
- out value,
- IntPtr.Size,
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQueryInformationThread(
+ this, infoClass, out value, IntPtr.Size, out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
return value;
}
@@ -673,16 +718,13 @@ public int GetLastSystemCall()
/// A system call number.
public unsafe int GetLastSystemCall(out int firstArgument)
{
+ NtStatus status;
int* data = stackalloc int[2];
int retLength;
- Win32.NtQueryInformationThread(
- this,
- ThreadInformationClass.ThreadLastSystemCall,
- data,
- sizeof(int) * 2,
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQueryInformationThread(
+ this, ThreadInformationClass.ThreadLastSystemCall, data, sizeof(int) * 2, out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
firstArgument = data[0];
@@ -766,13 +808,12 @@ public IntPtr GetWin32StartAddress()
/// The impersonation level to request.
public void Impersonate(ThreadHandle clientThreadHandle, SecurityImpersonationLevel impersonationLevel)
{
- SecurityQualityOfService securityQos = new SecurityQualityOfService(impersonationLevel, false, false);
+ NtStatus status;
+ SecurityQualityOfService securityQos =
+ new SecurityQualityOfService(impersonationLevel, false, false);
- Win32.NtImpersonateThread(
- this,
- clientThreadHandle,
- ref securityQos
- ).ThrowIf();
+ if ((status = Win32.NtImpersonateThread(this, clientThreadHandle, ref securityQos)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -780,7 +821,10 @@ ref securityQos
///
public void ImpersonateAnonymous()
{
- Win32.NtImpersonateAnonymousToken(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtImpersonateAnonymousToken(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -856,13 +900,16 @@ public void QueueApc(ApcRoutine action, IntPtr parameter)
/// The third parameter to pass to the function.
public void QueueApc(IntPtr address, IntPtr param1, IntPtr param2, IntPtr param3)
{
- Win32.NtQueueApcThread(
+ NtStatus status;
+
+ if ((status = Win32.NtQueueApcThread(
this,
address,
param1,
param2,
param3
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void RemoteCall(IntPtr address, IntPtr[] arguments)
@@ -872,7 +919,12 @@ public void RemoteCall(IntPtr address, IntPtr[] arguments)
public void RemoteCall(IntPtr address, IntPtr[] arguments, bool alreadySuspended)
{
- ProcessHandle processHandle = new ProcessHandle(this.GetProcessId(), ProcessAccess.VmWrite);
+ ProcessHandle processHandle;
+
+ if (KProcessHacker.Instance != null)
+ processHandle = this.GetProcess(ProcessAccess.VmWrite);
+ else
+ processHandle = new ProcessHandle(this.GetProcessId(), ProcessAccess.VmWrite);
using (processHandle)
this.RemoteCall(processHandle, address, arguments, alreadySuspended);
@@ -880,7 +932,9 @@ public void RemoteCall(IntPtr address, IntPtr[] arguments, bool alreadySuspended
public void RemoteCall(ProcessHandle processHandle, IntPtr address, IntPtr[] arguments, bool alreadySuspended)
{
- Win32.RtlRemoteCall(
+ NtStatus status;
+
+ if ((status = Win32.RtlRemoteCall(
processHandle,
this,
address,
@@ -888,7 +942,8 @@ public void RemoteCall(ProcessHandle processHandle, IntPtr address, IntPtr[] arg
arguments,
false,
alreadySuspended
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -896,9 +951,11 @@ public void RemoteCall(ProcessHandle processHandle, IntPtr address, IntPtr[] arg
///
public int Resume()
{
+ NtStatus status;
int suspendCount;
- Win32.NtResumeThread(this, out suspendCount).ThrowIf();
+ if ((status = Win32.NtResumeThread(this, out suspendCount)) >= NtStatus.Error)
+ Win32.Throw(status);
return suspendCount;
}
@@ -926,9 +983,19 @@ public void SetBasePriorityWin32(ThreadPriorityLevel basePriority)
/// Sets the thread's context.
///
/// A CONTEXT struct.
- public void SetContext(Context context)
+ public unsafe void SetContext(Context context)
{
- Win32.NtSetContextThread(this, ref context).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ KProcessHacker.Instance.KphSetContextThread(this, &context);
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = Win32.NtSetContextThread(this, ref context)) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
}
///
@@ -937,13 +1004,16 @@ public void SetContext(Context context)
/// A CONTEXT struct.
public void SetContext(ContextAmd64 context)
{
+ NtStatus status;
+
// HACK: To avoid a datatype misalignment error, allocate
// some aligned memory.
- using (AlignedMemoryAlloc data = new AlignedMemoryAlloc(Utils.SizeOf(16, ContextAmd64.SizeOf), 16))
+ using (var data = new AlignedMemoryAlloc(Utils.SizeOf(16), 16))
{
- data.WriteStruct(context);
+ data.WriteStruct(context);
- Win32.NtSetContextThread(this, data).ThrowIf();
+ if ((status = Win32.NtSetContextThread(this, data)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
@@ -954,7 +1024,10 @@ public void SetContext(ContextAmd64 context)
/// A CONTEXT struct.
public void SetContextWow64(Context context)
{
- Win32.RtlWow64SetThreadContext(this, ref context).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.RtlWow64SetThreadContext(this, ref context)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -968,22 +1041,35 @@ public void SetCritical(bool critical)
private void SetInformationInt32(ThreadInformationClass infoClass, int value)
{
- Win32.NtSetInformationThread(
- this,
- infoClass,
- ref value,
- sizeof(int)
- ).ThrowIf();
+ if (
+ KProcessHacker.Instance != null &&
+ infoClass == ThreadInformationClass.ThreadIoPriority
+ )
+ {
+ unsafe
+ {
+ KProcessHacker.Instance.KphSetInformationThread(
+ this, infoClass, new IntPtr(&value), sizeof(int)
+ );
+ }
+ }
+ else
+ {
+ NtStatus status;
+
+ if ((status = Win32.NtSetInformationThread(
+ this, infoClass, ref value, sizeof(int))) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
}
private void SetInformationIntPtr(ThreadInformationClass infoClass, IntPtr value)
{
- Win32.NtSetInformationThread(
- this,
- infoClass,
- ref value,
- sizeof(int)
- ).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtSetInformationThread(
+ this, infoClass, ref value, sizeof(int))) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void SetIoPriority(int ioPriority)
@@ -1031,9 +1117,11 @@ public void SetToken(TokenHandle tokenHandle)
///
public int Suspend()
{
+ NtStatus status;
int suspendCount;
- Win32.NtSuspendThread(this, out suspendCount).ThrowIf();
+ if ((status = Win32.NtSuspendThread(this, out suspendCount)) >= NtStatus.Error)
+ Win32.Throw(status);
return suspendCount;
}
@@ -1052,7 +1140,24 @@ public void Terminate()
/// The exit status.
public void Terminate(NtStatus exitStatus)
{
- Win32.NtTerminateThread(this, exitStatus).ThrowIf();
+ if (KProcessHacker.Instance != null)
+ {
+ try
+ {
+ KProcessHacker.Instance.KphTerminateThread(this, exitStatus);
+ return;
+ }
+ catch (WindowsException ex)
+ {
+ if (ex.ErrorCode != Win32Error.NotSupported)
+ throw ex;
+ }
+ }
+
+ NtStatus status;
+
+ if ((status = Win32.NtTerminateThread(this, exitStatus)) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -1075,14 +1180,23 @@ public void WalkStack(WalkStackDelegate walkStackCallback)
///
public void WalkStack(WalkStackDelegate walkStackCallback, OSArch architecture)
{
- // We need to duplicate the handle to get QueryInformation access.
- using (NativeHandle dupThreadHandle = this.Duplicate(OSVersion.MinThreadQueryInfoAccess))
- using (ProcessHandle phandle = new ProcessHandle(
- FromHandle(dupThreadHandle).GetBasicInformation().ClientId.ProcessId,
- ProcessAccess.QueryInformation | ProcessAccess.VmRead
- ))
+ if (KProcessHacker.Instance != null)
{
- this.WalkStack(phandle, walkStackCallback, architecture);
+ // Use KPH to open the parent process.
+ using (var phandle = this.GetProcess(ProcessAccess.QueryInformation | ProcessAccess.VmRead))
+ this.WalkStack(phandle, walkStackCallback, architecture);
+ }
+ else
+ {
+ // We need to duplicate the handle to get QueryInformation access.
+ using (var dupThreadHandle = this.Duplicate(OSVersion.MinThreadQueryInfoAccess))
+ using (var phandle = new ProcessHandle(
+ ThreadHandle.FromHandle(dupThreadHandle).GetBasicInformation().ClientId.ProcessId,
+ ProcessAccess.QueryInformation | ProcessAccess.VmRead
+ ))
+ {
+ this.WalkStack(phandle, walkStackCallback, architecture);
+ }
}
}
@@ -1091,7 +1205,7 @@ public void WalkStack(WalkStackDelegate walkStackCallback, OSArch architecture)
///
/// A handle to the thread's parent process.
/// A callback to execute.
- public void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCallback)
+ public unsafe void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCallback)
{
this.WalkStack(parentProcess, walkStackCallback, OSVersion.Architecture);
}
@@ -1106,9 +1220,9 @@ public void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCa
/// On 64-bit systems, this value can be set to I386 to walk the
/// 32-bit stack.
///
- public void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCallback, OSArch architecture)
+ public unsafe void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCallback, OSArch architecture)
{
- bool suspended;
+ bool suspended = false;
// Suspend the thread to avoid inaccurate thread stacks.
try
@@ -1124,24 +1238,24 @@ public void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCa
// Use KPH for reading memory if we can.
ReadProcessMemoryProc64 readMemoryProc = null;
- //if (KProcessHacker.Instance != null)
- //{
- // readMemoryProc =
- // (IntPtr processHandle, ulong baseAddress, IntPtr buffer, int size, out int bytesRead)
- // => KProcessHacker.Instance.KphReadVirtualMemorySafe(
- // ProcessHandle.FromHandle(processHandle), (int)baseAddress, buffer, size, out bytesRead
- // ).IsSuccess();
- //}
+ if (KProcessHacker.Instance != null)
+ {
+ readMemoryProc = new ReadProcessMemoryProc64(
+ delegate(IntPtr processHandle, ulong baseAddress, IntPtr buffer, int size, out int bytesRead)
+ {
+ return KProcessHacker.Instance.KphReadVirtualMemorySafe(
+ ProcessHandle.FromHandle(processHandle), (int)baseAddress, buffer, size, out bytesRead).IsSuccess();
+ });
+ }
try
{
// x86/WOW64 stack walk.
if (OSVersion.Architecture == OSArch.I386 || (OSVersion.Architecture == OSArch.Amd64 && architecture == OSArch.I386))
{
- Context context = new Context
- {
- ContextFlags = ContextFlags.All
- };
+ Context context = new Context();
+
+ context.ContextFlags = ContextFlags.All;
if (OSVersion.Architecture == OSArch.I386)
{
@@ -1155,24 +1269,14 @@ public void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCa
}
// Set up the initial stack frame structure.
- StackFrame64 stackFrame = new StackFrame64
- {
- AddrPC =
- {
- Mode = AddressMode.AddrModeFlat,
- Offset = (ulong)context.Eip
- },
- AddrStack =
- {
- Mode = AddressMode.AddrModeFlat,
- Offset = (ulong)context.Esp
- },
- AddrFrame =
- {
- Mode = AddressMode.AddrModeFlat,
- Offset = (ulong)context.Ebp
- }
- };
+ var stackFrame = new StackFrame64();
+
+ stackFrame.AddrPC.Mode = AddressMode.AddrModeFlat;
+ stackFrame.AddrPC.Offset = (ulong)context.Eip;
+ stackFrame.AddrStack.Mode = AddressMode.AddrModeFlat;
+ stackFrame.AddrStack.Offset = (ulong)context.Esp;
+ stackFrame.AddrFrame.Mode = AddressMode.AddrModeFlat;
+ stackFrame.AddrFrame.Offset = (ulong)context.Ebp;
while (true)
{
@@ -1204,34 +1308,21 @@ public void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCa
// x64 stack walk.
else if (OSVersion.Architecture == OSArch.Amd64)
{
- ContextAmd64 context = new ContextAmd64
- {
- ContextFlags = ContextFlagsAmd64.All
- };
+ ContextAmd64 context = new ContextAmd64();
+ context.ContextFlags = ContextFlagsAmd64.All;
// Get the context.
this.GetContext(ref context);
// Set up the initial stack frame structure.
- StackFrame64 stackFrame = new StackFrame64
- {
- AddrPC =
- {
- Mode = AddressMode.AddrModeFlat,
- Offset = (ulong)context.Rip
- },
- AddrStack =
- {
- Mode = AddressMode.AddrModeFlat,
- Offset = (ulong)context.Rsp
- },
- AddrFrame =
- {
- Mode = AddressMode.AddrModeFlat,
- Offset = (ulong)context.Rbp
- }
- };
+ var stackFrame = new StackFrame64();
+ stackFrame.AddrPC.Mode = AddressMode.AddrModeFlat;
+ stackFrame.AddrPC.Offset = (ulong)context.Rip;
+ stackFrame.AddrStack.Mode = AddressMode.AddrModeFlat;
+ stackFrame.AddrStack.Offset = (ulong)context.Rsp;
+ stackFrame.AddrFrame.Mode = AddressMode.AddrModeFlat;
+ stackFrame.AddrFrame.Offset = (ulong)context.Rbp;
while (true)
{
@@ -1279,12 +1370,12 @@ public void WalkStack(ProcessHandle parentProcess, WalkStackDelegate walkStackCa
public class ThreadStackFrame
{
- private readonly IntPtr _pcAddress;
- private readonly IntPtr _returnAddress;
- private readonly IntPtr _frameAddress;
- private readonly IntPtr _stackAddress;
- private readonly IntPtr _bStoreAddress;
- private readonly IntPtr[] _params;
+ private IntPtr _pcAddress;
+ private IntPtr _returnAddress;
+ private IntPtr _frameAddress;
+ private IntPtr _stackAddress;
+ private IntPtr _bStoreAddress;
+ private IntPtr[] _params;
internal ThreadStackFrame(ref StackFrame64 stackFrame)
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/TimerHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/TimerHandle.cs
index 2a7b8308f..fd75b906c 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/TimerHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/TimerHandle.cs
@@ -1,4 +1,5 @@
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -46,12 +47,14 @@ public static TimerHandle Create(TimerAccess access, string name, TimerType type
/// A handle to the timer.
public static TimerHandle Create(TimerAccess access, string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, TimerType type)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtCreateTimer(out handle, access, ref oa, type).ThrowIf();
+ if ((status = Win32.NtCreateTimer(out handle, access, ref oa, type)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -66,18 +69,22 @@ public static TimerHandle FromHandle(IntPtr handle)
return new TimerHandle(handle, false);
}
+ private TimerApcRoutine _routine;
+
private TimerHandle(IntPtr handle, bool owned)
: base(handle, owned)
{ }
public TimerHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, TimerAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenTimer(out handle, access, ref oa).ThrowIf();
+ if ((status = Win32.NtOpenTimer(out handle, access, ref oa)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -97,9 +104,11 @@ public TimerHandle(string name, TimerAccess access)
/// The state of the timer (whether it is signaled).
public bool Cancel()
{
+ NtStatus status;
bool currentState;
- Win32.NtCancelTimer(this, out currentState).ThrowIf();
+ if ((status = Win32.NtCancelTimer(this, out currentState)) >= NtStatus.Error)
+ Win32.Throw(status);
return currentState;
}
@@ -107,23 +116,17 @@ public bool Cancel()
///
/// Gets information about the timer.
///
- public TimerBasicInformation BasicInformation
+ public TimerBasicInformation GetBasicInformation()
{
- get
- {
- TimerBasicInformation tbi;
- int retLength;
-
- Win32.NtQueryTimer(
- this,
- TimerInformationClass.TimerBasicInformation,
- out tbi,
- TimerBasicInformation.SizeOf,
- out retLength
- ).ThrowIf();
-
- return tbi;
- }
+ NtStatus status;
+ TimerBasicInformation tbi;
+ int retLength;
+
+ if ((status = Win32.NtQueryTimer(this, TimerInformationClass.TimerBasicInformation,
+ out tbi, Marshal.SizeOf(typeof(TimerBasicInformation)), out retLength)) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return tbi;
}
///
@@ -203,12 +206,14 @@ public bool Set(long dueTime, bool relative, TimerApcRoutine routine, IntPtr con
/// The state of the timer (whether it is signaled).
public bool Set(long dueTime, bool relative, TimerApcRoutine routine, IntPtr context, bool resume, int period)
{
+ NtStatus status;
long realDueTime = relative ? -dueTime : dueTime;
bool previousState;
// Keep the APC routine alive.
+ _routine = routine;
- Win32.NtSetTimer(
+ if ((status = Win32.NtSetTimer(
this,
ref realDueTime,
routine,
@@ -216,7 +221,8 @@ public bool Set(long dueTime, bool relative, TimerApcRoutine routine, IntPtr con
resume,
period,
out previousState
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return previousState;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/TmHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/TmHandle.cs
index 40eb00148..6450d191a 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/TmHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/TmHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -37,24 +38,33 @@ public static TmHandle Create(
TmOptions createOptions
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
- UnicodeString logFileNameStr = new UnicodeString(logFileName);
IntPtr handle;
try
{
- Win32.NtCreateTransactionManager(
- out handle,
- access,
- ref oa,
- ref logFileNameStr,
- createOptions,
- 0
- ).ThrowIf();
+ UnicodeString logFileNameStr = new UnicodeString(logFileName);
+
+ try
+ {
+ if ((status = Win32.NtCreateTransactionManager(
+ out handle,
+ access,
+ ref oa,
+ ref logFileNameStr,
+ createOptions,
+ 0
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+ }
+ finally
+ {
+ logFileNameStr.Dispose();
+ }
}
finally
{
- logFileNameStr.Dispose();
oa.Dispose();
}
@@ -72,19 +82,21 @@ private TmHandle(IntPtr handle, bool owned)
public TmHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory, TmAccess access)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenTransactionManager(
+ if ((status = Win32.NtOpenTransactionManager(
out handle,
access,
ref oa,
IntPtr.Zero,
IntPtr.Zero,
0
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -94,113 +106,115 @@ public TmHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirect
this.Handle = handle;
}
- public TmBasicInformation BasicInformation
+ public TmBasicInformation GetBasicInformation()
{
- get
- {
- TmBasicInformation basicInfo;
- int retLength;
+ NtStatus status;
+ TmBasicInformation basicInfo;
+ int retLength;
- Win32.NtQueryInformationTransactionManager(
- this,
- TmInformationClass.TransactionManagerBasicInformation,
- out basicInfo,
- TmBasicInformation.SizeOf,
- out retLength
- ).ThrowIf();
-
- return basicInfo;
- }
+ if ((status = Win32.NtQueryInformationTransactionManager(
+ this,
+ TmInformationClass.TransactionManagerBasicInformation,
+ out basicInfo,
+ Marshal.SizeOf(typeof(TmBasicInformation)),
+ out retLength
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return basicInfo;
}
- public long LastRecoveredLsn
+ public long GetLastRecoveredLsn()
{
- get
- {
- TmRecoveryInformation recoveryInfo;
- int retLength;
-
- Win32.NtQueryInformationTransactionManager(
- this,
- TmInformationClass.TransactionManagerRecoveryInformation,
- out recoveryInfo,
- TmRecoveryInformation.SizeOf,
- out retLength
- ).ThrowIf();
+ NtStatus status;
+ TmRecoveryInformation recoveryInfo;
+ int retLength;
- return recoveryInfo.LastRecoveredLsn;
- }
+ if ((status = Win32.NtQueryInformationTransactionManager(
+ this,
+ TmInformationClass.TransactionManagerRecoveryInformation,
+ out recoveryInfo,
+ Marshal.SizeOf(typeof(TmRecoveryInformation)),
+ out retLength
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return recoveryInfo.LastRecoveredLsn;
}
- public string LogFileName
+ public string GetLogFileName()
{
- get
+ NtStatus status;
+ int retLength;
+
+ using (var data = new MemoryAlloc(0x1000))
{
- int retLength;
+ status = Win32.NtQueryInformationTransactionManager(
+ this,
+ TmInformationClass.TransactionManagerLogPathInformation,
+ data,
+ data.Size,
+ out retLength
+ );
- using (MemoryAlloc data = new MemoryAlloc(0x1000))
+ if (status == NtStatus.BufferTooSmall)
{
- NtStatus status = Win32.NtQueryInformationTransactionManager(
+ // Resize the buffer and try again.
+ data.ResizeNew(retLength);
+
+ status = Win32.NtQueryInformationTransactionManager(
this,
TmInformationClass.TransactionManagerLogPathInformation,
data,
data.Size,
out retLength
);
+ }
- if (status == NtStatus.BufferTooSmall)
- {
- // Resize the buffer and try again.
- data.ResizeNew(retLength);
-
- Win32.NtQueryInformationTransactionManager(
- this,
- TmInformationClass.TransactionManagerLogPathInformation,
- data,
- data.Size,
- out retLength
- ).ThrowIf();
- }
-
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
- TmLogPathInformation logPathInfo = data.ReadStruct();
+ TmLogPathInformation logPathInfo = data.ReadStruct();
- return data.ReadUnicodeString(TmLogPathInformation.LogPathOffset, logPathInfo.LogPathLength);
- }
+ return data.ReadUnicodeString(TmLogPathInformation.LogPathOffset, logPathInfo.LogPathLength);
}
}
- public Guid LogIdentity
+ public Guid GetLogIdentity()
{
- get
- {
- TmLogInformation logInfo;
- int retLength;
-
- Win32.NtQueryInformationTransactionManager(
- this,
- TmInformationClass.TransactionManagerLogInformation,
- out logInfo,
- TmLogInformation.SizeOf,
- out retLength
- ).ThrowIf();
+ NtStatus status;
+ TmLogInformation logInfo;
+ int retLength;
- return logInfo.LogIdentity;
- }
+ if ((status = Win32.NtQueryInformationTransactionManager(
+ this,
+ TmInformationClass.TransactionManagerLogInformation,
+ out logInfo,
+ Marshal.SizeOf(typeof(TmLogInformation)),
+ out retLength
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return logInfo.LogIdentity;
}
public void Recover()
{
- Win32.NtRecoverTransactionManager(this).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRecoverTransactionManager(this)) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void Rollforward(long virtualClock)
{
- Win32.NtRollforwardTransactionManager(
+ NtStatus status;
+
+ if ((status = Win32.NtRollforwardTransactionManager(
this,
ref virtualClock
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/TokenHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/TokenHandle.cs
index b3f0d1225..7415127dd 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/TokenHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/TokenHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
using ProcessHacker.Native.Security.AccessControl;
@@ -48,7 +49,7 @@ PrivilegeSet privileges
)
{
using (var administratorsSid = Sid.GetWellKnownSid(WellKnownSidType.WinBuiltinAdministratorsSid))
- using (var thandle = OpenCurrentPrimary(TokenAccess.Query))
+ using (var thandle = TokenHandle.OpenCurrentPrimary(TokenAccess.Query))
return Create(access, 0, thandle, tokenType, user, groups, privileges, administratorsSid, administratorsSid);
}
@@ -64,7 +65,7 @@ public static TokenHandle Create(
Sid primaryGroup
)
{
- var statistics = existingTokenHandle.Statistics;
+ var statistics = existingTokenHandle.GetStatistics();
return Create(
access,
@@ -101,6 +102,7 @@ public static TokenHandle Create(
TokenSource source
)
{
+ NtStatus status;
TokenUser tokenUser = new TokenUser(user);
TokenGroups tokenGroups = new TokenGroups(groups);
TokenPrivileges tokenPrivileges = new TokenPrivileges(privileges);
@@ -112,7 +114,7 @@ TokenSource source
try
{
- Win32.NtCreateToken(
+ if ((status = Win32.NtCreateToken(
out handle,
access,
ref oa,
@@ -126,7 +128,8 @@ TokenSource source
ref tokenPrimaryGroup,
ref tokenDefaultDacl,
ref source
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -174,7 +177,7 @@ public static TokenHandle OpenSelf(TokenAccess access)
public static TokenHandle OpenSystemToken(TokenAccess access)
{
- using (ProcessHandle phandle = new ProcessHandle(4, OSVersion.MinProcessQueryInfoAccess))
+ using (var phandle = new ProcessHandle(4, OSVersion.MinProcessQueryInfoAccess))
{
return phandle.GetToken(access);
}
@@ -182,9 +185,9 @@ public static TokenHandle OpenSystemToken(TokenAccess access)
public static TokenHandle OpenSystemToken(TokenAccess access, SecurityImpersonationLevel impersonationLevel, TokenType type)
{
- using (ProcessHandle phandle = new ProcessHandle(4, OSVersion.MinProcessQueryInfoAccess))
+ using (var phandle = new ProcessHandle(4, OSVersion.MinProcessQueryInfoAccess))
{
- using (TokenHandle thandle = phandle.GetToken(TokenAccess.Duplicate | access))
+ using (var thandle = phandle.GetToken(TokenAccess.Duplicate | access))
{
return thandle.Duplicate(access, impersonationLevel, type);
}
@@ -202,22 +205,22 @@ public TokenHandle(IntPtr handle, bool owned)
/// The desired access to the token.
public TokenHandle(ProcessHandle handle, TokenAccess access)
{
- if (KProcessHacker2.Instance != null && KProcessHacker2.Instance.KphIsConnected)
+ IntPtr h;
+
+ if (KProcessHacker.Instance != null)
{
- this.Handle = KProcessHacker2.Instance.KphOpenProcessToken(handle, access);
+ h = new IntPtr(KProcessHacker.Instance.KphOpenProcessToken(handle, access));
}
else
{
- IntPtr thandle;
-
- if (!Win32.OpenProcessToken(handle, access, out thandle))
+ if (!Win32.OpenProcessToken(handle, access, out h))
{
this.MarkAsInvalid();
Win32.Throw();
}
-
- this.Handle = thandle;
}
+
+ this.Handle = h;
}
///
@@ -250,11 +253,10 @@ public TokenHandle(ThreadHandle handle, TokenAccess access, bool openAsSelf)
public void AdjustGroups(Sid[] groups)
{
- TokenGroups tokenGroups = new TokenGroups
- {
- GroupCount = groups.Length,
- Groups = new SidAndAttributes[groups.Length]
- };
+ TokenGroups tokenGroups = new TokenGroups();
+
+ tokenGroups.GroupCount = groups.Length;
+ tokenGroups.Groups = new SidAndAttributes[groups.Length];
for (int i = 0; i < groups.Length; i++)
tokenGroups.Groups[i] = groups[i].ToSidAndAttributes();
@@ -267,20 +269,25 @@ public void AdjustPrivileges(PrivilegeSet privileges)
{
var tokenPrivileges = privileges.ToTokenPrivileges();
- Win32.NtAdjustPrivilegesToken(this, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero).ThrowIf();
+ Win32.AdjustTokenPrivileges(this, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero);
+
+ if (Marshal.GetLastWin32Error() != 0)
+ Win32.Throw();
}
public bool CheckPrivileges(PrivilegeSet privileges)
{
+ NtStatus status;
bool result;
- using (MemoryAlloc privilegesMemory = privileges.ToMemory())
+ using (var privilegesMemory = privileges.ToMemory())
{
- Win32.NtPrivilegeCheck(
+ if ((status = Win32.NtPrivilegeCheck(
this,
privilegesMemory,
out result
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return result;
}
@@ -310,13 +317,15 @@ public TokenHandle Duplicate(TokenAccess access, SecurityImpersonationLevel impe
/// Whether they are equal.
public bool Equals(TokenHandle other)
{
+ NtStatus status;
bool equal;
- Win32.NtCompareTokens(
+ if ((status = Win32.NtCompareTokens(
this,
other,
out equal
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return equal;
}
@@ -325,56 +334,135 @@ out equal
/// Gets the elevation type of the token.
///
/// A TOKEN_ELEVATION_TYPE enum.
- public TokenElevationType ElevationType
+ public TokenElevationType GetElevationType()
{
- get { return (TokenElevationType)this.GetInformationInt32(TokenInformationClass.TokenElevationType); }
+ return (TokenElevationType)this.GetInformationInt32(TokenInformationClass.TokenElevationType);
}
///
/// Gets the token's groups.
///
/// A TokenGroupsData struct.
- public Sid[] Groups
+ public Sid[] GetGroups()
{
- get { return this.GetGroupsInternal(TokenInformationClass.TokenGroups); }
+ return this.GetGroupsInternal(TokenInformationClass.TokenGroups);
}
- public TokenHandle LinkedToken
+ private Sid[] GetGroupsInternal(TokenInformationClass infoClass)
{
- get
- {
- NtStatus status;
+ int retLen = 0;
- IntPtr handle = this.GetInformationIntPtr(TokenInformationClass.TokenLinkedToken, out status);
+ Win32.GetTokenInformation(this, infoClass, IntPtr.Zero, 0, out retLen);
+
+ using (MemoryAlloc data = new MemoryAlloc(retLen))
+ {
+ if (!Win32.GetTokenInformation(this, infoClass, data,
+ data.Size, out retLen))
+ Win32.Throw();
- if (status == NtStatus.NoSuchLogonSession)
- return null;
+ int count = data.ReadStruct().GroupCount;
+ Sid[] sids = new Sid[count];
- status.ThrowIf();
+ for (int i = 0; i < count; i++)
+ {
+ var saa = data.ReadStruct(TokenGroups.GroupsOffset, i);
+ sids[i] = new Sid(saa.Sid, saa.Attributes);
+ }
- return new TokenHandle(handle, true);
+ return sids;
}
}
+ private int GetInformationInt32(TokenInformationClass infoClass)
+ {
+ NtStatus status;
+ int value;
+
+ value = this.GetInformationInt32(infoClass, out status);
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return value;
+ }
+
+ private int GetInformationInt32(TokenInformationClass infoClass, out NtStatus status)
+ {
+ int value;
+ int retLength;
+
+ status = Win32.NtQueryInformationToken(
+ this,
+ infoClass,
+ out value,
+ sizeof(int),
+ out retLength
+ );
+
+ return value;
+ }
+
+ private IntPtr GetInformationIntPtr(TokenInformationClass infoClass)
+ {
+ NtStatus status;
+ IntPtr value;
+
+ value = this.GetInformationIntPtr(infoClass, out status);
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return value;
+ }
+
+ private IntPtr GetInformationIntPtr(TokenInformationClass infoClass, out NtStatus status)
+ {
+ IntPtr value;
+ int retLength;
+
+ status = Win32.NtQueryInformationToken(
+ this,
+ infoClass,
+ out value,
+ IntPtr.Size,
+ out retLength
+ );
+
+ return value;
+ }
+
+ public TokenHandle GetLinkedToken()
+ {
+ NtStatus status;
+ IntPtr handle;
+
+ handle = this.GetInformationIntPtr(TokenInformationClass.TokenLinkedToken, out status);
+
+ if (status == NtStatus.NoSuchLogonSession)
+ return null;
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
+
+ return new TokenHandle(handle, true);
+ }
+
///
/// Gets the token's owner.
///
/// A WindowsSID instance.
- public Sid Owner
+ public Sid GetOwner()
{
- get
- {
- int retLen;
+ int retLen;
- Win32.GetTokenInformation(this, TokenInformationClass.TokenOwner, IntPtr.Zero, 0, out retLen);
+ Win32.GetTokenInformation(this, TokenInformationClass.TokenOwner, IntPtr.Zero, 0, out retLen);
- using (MemoryAlloc data = new MemoryAlloc(retLen))
- {
- if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenOwner, data, data.Size, out retLen))
- Win32.Throw();
+ using (MemoryAlloc data = new MemoryAlloc(retLen))
+ {
+ if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenOwner, data,
+ data.Size, out retLen))
+ Win32.Throw();
- return new Sid(data.ReadIntPtr(0));
- }
+ return new Sid(data.ReadIntPtr(0));
}
}
@@ -382,21 +470,19 @@ public Sid Owner
/// Gets the token's primary group.
///
/// A WindowsSID instance.
- public Sid PrimaryGroup
+ public Sid GetPrimaryGroup()
{
- get
- {
- int retLen;
+ int retLen;
- Win32.GetTokenInformation(this, TokenInformationClass.TokenPrimaryGroup, IntPtr.Zero, 0, out retLen);
+ Win32.GetTokenInformation(this, TokenInformationClass.TokenPrimaryGroup, IntPtr.Zero, 0, out retLen);
- using (MemoryAlloc data = new MemoryAlloc(retLen))
- {
- if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenPrimaryGroup, data, data.Size, out retLen))
- Win32.Throw();
+ using (MemoryAlloc data = new MemoryAlloc(retLen))
+ {
+ if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenPrimaryGroup, data,
+ data.Size, out retLen))
+ Win32.Throw();
- return new Sid(data.ReadIntPtr(0));
- }
+ return new Sid(data.ReadIntPtr(0));
}
}
@@ -404,30 +490,28 @@ public Sid PrimaryGroup
/// Gets the token's privileges.
///
/// A TOKEN_PRIVILEGES structure.
- public Privilege[] Privileges
+ public Privilege[] GetPrivileges()
{
- get
- {
- int retLen;
-
- Win32.GetTokenInformation(this, TokenInformationClass.TokenPrivileges, IntPtr.Zero, 0, out retLen);
+ int retLen;
- using (MemoryAlloc data = new MemoryAlloc(retLen))
- {
- if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenPrivileges, data, data.Size, out retLen))
- Win32.Throw();
+ Win32.GetTokenInformation(this, TokenInformationClass.TokenPrivileges, IntPtr.Zero, 0, out retLen);
- uint count = data.ReadUInt32(0);
- Privilege[] privileges = new Privilege[count];
+ using (MemoryAlloc data = new MemoryAlloc(retLen))
+ {
+ if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenPrivileges, data,
+ data.Size, out retLen))
+ Win32.Throw();
- for (int i = 0; i < count; i++)
- {
- var laa = data.ReadStruct(sizeof(int), LuidAndAttributes.SizeOf, i);
- privileges[i] = new Privilege(this, laa.Luid, laa.Attributes);
- }
+ uint count = data.ReadUInt32(0);
+ Privilege[] privileges = new Privilege[count];
- return privileges;
+ for (int i = 0; i < count; i++)
+ {
+ var laa = data.ReadStruct(sizeof(int), i);
+ privileges[i] = new Privilege(this, laa.Luid, laa.Attributes);
}
+
+ return privileges;
}
}
@@ -435,77 +519,71 @@ public Privilege[] Privileges
/// Gets the restricted token's restricting SIDs.
///
/// A TokenGroupsData struct.
- public Sid[] RestrictingGroups
+ public Sid[] GetRestrictingGroups()
{
- get { return this.GetGroupsInternal(TokenInformationClass.TokenRestrictedSids); }
+ return this.GetGroupsInternal(TokenInformationClass.TokenRestrictedSids);
}
///
- /// Gets/Sets the token's session ID.
+ /// Gets the token's session ID.
///
/// The session ID.
- public int SessionId
+ public int GetSessionId()
{
- get { return this.GetInformationInt32(TokenInformationClass.TokenSessionId); }
- set { this.SetInformationInt32(TokenInformationClass.TokenSessionId, value); }
+ return this.GetInformationInt32(TokenInformationClass.TokenSessionId);
}
///
/// Gets the token's source.
///
/// A TOKEN_SOURCE struct.
- public TokenSource Source
+ public TokenSource GetSource()
{
- get
- {
- TokenSource source;
- int retLen;
+ TokenSource source;
+ int retLen;
- if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenSource, out source, TokenSource.SizeOf, out retLen))
- Win32.Throw();
+ if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenSource,
+ out source, Marshal.SizeOf(typeof(TokenSource)), out retLen))
+ Win32.Throw();
- return source;
- }
+ return source;
}
///
/// Gets statistics about the token.
///
/// A TOKEN_STATISTICS structure.
- public TokenStatistics Statistics
+ public TokenStatistics GetStatistics()
{
- get
- {
- TokenStatistics statistics;
- int retLen;
+ TokenStatistics statistics;
+ int retLen;
- if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenStatistics, out statistics, TokenStatistics.SizeOf, out retLen))
- Win32.Throw();
+ if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenStatistics,
+ out statistics, Marshal.SizeOf(typeof(TokenStatistics)), out retLen))
+ Win32.Throw();
- return statistics;
- }
+ return statistics;
}
///
/// Gets the token's user.
///
/// A WindowsSID instance.
- public Sid User
+ public Sid GetUser()
{
- get
- {
- int retLen;
+ int retLen;
- Win32.NtQueryInformationToken(this, TokenInformationClass.TokenUser, IntPtr.Zero, 0, out retLen);
+ Win32.GetTokenInformation(this, TokenInformationClass.TokenUser, IntPtr.Zero, 0, out retLen);
- using (MemoryAlloc data = new MemoryAlloc(retLen))
- {
- Win32.NtQueryInformationToken(this.Handle, TokenInformationClass.TokenUser, data, data.Size, out retLen).ThrowIf();
+ using (MemoryAlloc data = new MemoryAlloc(retLen))
+ {
+ if (!Win32.GetTokenInformation(this.Handle, TokenInformationClass.TokenUser, data,
+ data.Size, out retLen))
+ Win32.Throw();
- TokenUser user = data.ReadStruct();
+ TokenUser user = data.ReadStruct();
- return new Sid(user.User.Sid, user.User.Attributes);
- }
+ return new Sid(user.User.Sid, user.User.Attributes);
}
}
@@ -513,124 +591,42 @@ public Sid User
/// Gets whether the token has UAC elevation applied.
///
/// A boolean.
- public bool IsElevated
+ public bool IsElevated()
{
- get { return this.GetInformationInt32(TokenInformationClass.TokenElevation) != 0; }
+ return this.GetInformationInt32(TokenInformationClass.TokenElevation) != 0;
}
///
/// Gets whether virtualization is allowed.
///
/// A boolean.
- public bool IsVirtualizationAllowed
+ public bool IsVirtualizationAllowed()
{
- get { return this.GetInformationInt32(TokenInformationClass.TokenVirtualizationAllowed) != 0; }
+ return this.GetInformationInt32(TokenInformationClass.TokenVirtualizationAllowed) != 0;
}
///
- /// Gets/Sets whether virtualization is enabled or disabled.
+ /// Gets whether virtualization is enabled.
///
/// A boolean.
- public bool IsVirtualizationEnabled
+ public bool IsVirtualizationEnabled()
{
- get { return this.GetInformationInt32(TokenInformationClass.TokenVirtualizationEnabled) != 0; }
- set
- {
- int val = value ? 1 : 0;
-
- Win32.NtSetInformationToken(this, TokenInformationClass.TokenVirtualizationEnabled, ref val, 4).ThrowIf();
- }
+ return this.GetInformationInt32(TokenInformationClass.TokenVirtualizationEnabled) != 0;
}
- private Sid[] GetGroupsInternal(TokenInformationClass infoClass)
- {
- int retLen;
-
- Win32.GetTokenInformation(this, infoClass, IntPtr.Zero, 0, out retLen);
-
- using (MemoryAlloc data = new MemoryAlloc(retLen))
- {
- if (!Win32.GetTokenInformation(this, infoClass, data,
- data.Size, out retLen))
- Win32.Throw();
-
- int count = data.ReadStruct(0, TokenGroups.SizeOf, 0).GroupCount;
- Sid[] sids = new Sid[count];
-
- for (int i = 0; i < count; i++)
- {
- var saa = data.ReadStruct(TokenGroups.GroupsOffset, SidAndAttributes.SizeOf, i);
- sids[i] = new Sid(saa.Sid, saa.Attributes);
- }
-
- return sids;
- }
- }
-
- private int GetInformationInt32(TokenInformationClass infoClass)
+ private void SetInformationInt32(TokenInformationClass infoClass, int value)
{
NtStatus status;
-
- int value = this.GetInformationInt32(infoClass, out status);
-
- status.ThrowIf();
- return value;
- }
-
- private int GetInformationInt32(TokenInformationClass infoClass, out NtStatus status)
- {
- int value;
- int retLength;
-
- status = Win32.NtQueryInformationToken(
- this,
- infoClass,
- out value,
- sizeof(int),
- out retLength
- );
-
- return value;
- }
-
- private void SetInformationInt32(TokenInformationClass infoClass, int value)
- {
- Win32.NtSetInformationToken(
+ if ((status = Win32.NtSetInformationToken(
this,
infoClass,
ref value,
sizeof(int)
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
- private IntPtr GetInformationIntPtr(TokenInformationClass infoClass)
- {
- NtStatus status;
-
- IntPtr value = this.GetInformationIntPtr(infoClass, out status);
-
- status.ThrowIf();
-
- return value;
- }
-
- private IntPtr GetInformationIntPtr(TokenInformationClass infoClass, out NtStatus status)
- {
- IntPtr value;
- int retLength;
-
- status = Win32.NtQueryInformationToken(
- this,
- infoClass,
- out value,
- IntPtr.Size,
- out retLength
- );
-
- return value;
- }
-
///
/// Sets a privilege's attributes.
///
@@ -638,12 +634,33 @@ out retLength
/// The new attributes of the privilege.
public void SetPrivilege(string privilegeName, SePrivilegeAttributes attributes)
{
- this.TrySetPrivilege(privilegeName, attributes).ThrowIf();
+ if (!this.TrySetPrivilege(privilegeName, attributes))
+ Win32.Throw();
}
public void SetPrivilege(Luid privilegeLuid, SePrivilegeAttributes attributes)
{
- this.TrySetPrivilege(privilegeLuid, attributes).ThrowIf();
+ if (!this.TrySetPrivilege(privilegeLuid, attributes))
+ Win32.Throw();
+ }
+
+ public void SetSessionId(int sessionId)
+ {
+ this.SetInformationInt32(TokenInformationClass.TokenSessionId, sessionId);
+ }
+
+ ///
+ /// Sets whether virtualization is enabled.
+ ///
+ /// Whether virtualization is enabled.
+ public void SetVirtualizationEnabled(bool enabled)
+ {
+ int value = enabled ? 1 : 0;
+
+ if (!Win32.SetTokenInformation(this, TokenInformationClass.TokenVirtualizationEnabled, ref value, 4))
+ {
+ Win32.Throw();
+ }
}
///
@@ -652,7 +669,7 @@ public void SetPrivilege(Luid privilegeLuid, SePrivilegeAttributes attributes)
/// The name of the privilege.
/// The new attributes of the privilege.
/// True if the function succeeded, otherwise false.
- public NtStatus TrySetPrivilege(string privilegeName, SePrivilegeAttributes attributes)
+ public bool TrySetPrivilege(string privilegeName, SePrivilegeAttributes attributes)
{
return this.TrySetPrivilege(
LsaPolicyHandle.LookupPolicyHandle.LookupPrivilegeValue(privilegeName),
@@ -660,18 +677,22 @@ public NtStatus TrySetPrivilege(string privilegeName, SePrivilegeAttributes attr
);
}
- public NtStatus TrySetPrivilege(Luid privilegeLuid, SePrivilegeAttributes attributes)
+ public bool TrySetPrivilege(Luid privilegeLuid, SePrivilegeAttributes attributes)
{
- TokenPrivileges tkp = new TokenPrivileges
- {
- Privileges = new LuidAndAttributes[1],
- PrivilegeCount = 1
- };
+ TokenPrivileges tkp = new TokenPrivileges();
+ tkp.Privileges = new LuidAndAttributes[1];
+
+ tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = attributes;
tkp.Privileges[0].Luid = privilegeLuid;
- return Win32.NtAdjustPrivilegesToken(this, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero);
+ Win32.AdjustTokenPrivileges(this, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero);
+
+ if (Marshal.GetLastWin32Error() != 0)
+ return false;
+
+ return true;
}
}
}
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/TokenWithLinkedToken.cs b/1.x/trunk/ProcessHacker.Native/Objects/TokenWithLinkedToken.cs
index aec73840b..4fc88a731 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/TokenWithLinkedToken.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/TokenWithLinkedToken.cs
@@ -20,13 +20,15 @@
* along with Process Hacker. If not, see .
*/
+using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
+using System;
namespace ProcessHacker.Native.Objects
{
public sealed class TokenWithLinkedToken : IWithToken
{
- private readonly TokenHandle _token;
+ private TokenHandle _token;
public TokenWithLinkedToken(TokenHandle token)
{
@@ -35,7 +37,7 @@ public TokenWithLinkedToken(TokenHandle token)
public TokenHandle GetToken()
{
- return _token.LinkedToken;
+ return _token.GetLinkedToken();
}
public TokenHandle GetToken(TokenAccess access)
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/TransactionHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/TransactionHandle.cs
index 8870ed89b..765dd1c33 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/TransactionHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/TransactionHandle.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -30,7 +31,7 @@ public class TransactionHandle : NativeHandle
{
public struct CurrentTransactionContext : IDisposable
{
- private readonly TransactionHandle _oldHandle;
+ private TransactionHandle _oldHandle;
private bool _disposed;
internal CurrentTransactionContext(TransactionHandle handle)
@@ -83,6 +84,7 @@ public static TransactionHandle Create(
string description
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
@@ -95,7 +97,7 @@ string description
try
{
- Win32.NtCreateTransaction(
+ if ((status = Win32.NtCreateTransaction(
out handle,
access,
ref oa,
@@ -106,7 +108,8 @@ string description
0,
ref timeout,
ref descriptionStr
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -123,12 +126,14 @@ ref descriptionStr
public static TransactionHandle GetCurrent()
{
- IntPtr handle = Win32.RtlGetCurrentTransaction();
+ IntPtr handle;
+
+ handle = Win32.RtlGetCurrentTransaction();
if (handle != IntPtr.Zero)
return new TransactionHandle(handle, false);
-
- return null;
+ else
+ return null;
}
public static void SetCurrent(TransactionHandle transactionHandle)
@@ -154,18 +159,20 @@ public TransactionHandle(
TransactionAccess access
)
{
+ NtStatus status;
ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
IntPtr handle;
try
{
- Win32.NtOpenTransaction(
+ if ((status = Win32.NtOpenTransaction(
out handle,
access,
ref oa,
ref unitOfWorkGuid,
tmHandle ?? IntPtr.Zero
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -182,51 +189,51 @@ public static TransactionHandle FromHandle(IntPtr handle)
public void Commit(bool wait)
{
- Win32.NtCommitTransaction(this, wait).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtCommitTransaction(this, wait)) >= NtStatus.Error)
+ Win32.Throw(status);
}
- public TransactionBasicInformation BasicInformation
+ public TransactionBasicInformation GetBasicInformation()
{
- get
- {
- TransactionBasicInformation basicInfo;
- int retLength;
+ NtStatus status;
+ TransactionBasicInformation basicInfo;
+ int retLength;
- Win32.NtQueryInformationTransaction(
- this,
- TransactionInformationClass.TransactionBasicInformation,
- out basicInfo,
- TransactionBasicInformation.SizeOf,
- out retLength
- ).ThrowIf();
+ if ((status = Win32.NtQueryInformationTransaction(
+ this,
+ TransactionInformationClass.TransactionBasicInformation,
+ out basicInfo,
+ Marshal.SizeOf(typeof(TransactionBasicInformation)),
+ out retLength
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
- return basicInfo;
- }
+ return basicInfo;
}
- public string Description
+ public string GetDescription()
{
- get
+ using (var data = this.GetPropertiesInformation())
{
- using (MemoryAlloc data = this.GetPropertiesInformation())
- {
- TransactionPropertiesInformation propertiesInfo = data.ReadStruct();
+ var propertiesInfo = data.ReadStruct();
- return data.ReadUnicodeString(
- TransactionPropertiesInformation.DescriptionOffset,
- propertiesInfo.DescriptionLength / 2
- );
- }
+ return data.ReadUnicodeString(
+ TransactionPropertiesInformation.DescriptionOffset,
+ propertiesInfo.DescriptionLength / 2
+ );
}
}
private MemoryAlloc GetPropertiesInformation()
{
+ NtStatus status;
int retLength;
- MemoryAlloc data = new MemoryAlloc(0x1000);
+ var data = new MemoryAlloc(0x1000);
- NtStatus status = Win32.NtQueryInformationTransaction(
+ status = Win32.NtQueryInformationTransaction(
this,
TransactionInformationClass.TransactionPropertiesInformation,
data,
@@ -248,29 +255,27 @@ out retLength
);
}
- if (status.IsError())
+ if (status >= NtStatus.Error)
{
data.Dispose();
- status.Throw();
+ Win32.Throw(status);
}
return data;
}
- public long Timeout
+ public long GetTimeout()
{
- get
- {
- using (MemoryAlloc data = this.GetPropertiesInformation())
- {
- return data.ReadStruct().Timeout;
- }
- }
+ using (var data = this.GetPropertiesInformation())
+ return data.ReadStruct().Timeout;
}
public void Rollback(bool wait)
{
- Win32.NtRollbackTransaction(this, wait).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtRollbackTransaction(this, wait)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/TypeObjectHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/TypeObjectHandle.cs
index 21fa5b789..85cf0b29a 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/TypeObjectHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/TypeObjectHandle.cs
@@ -1,4 +1,8 @@
-using ProcessHacker.Native.Api;
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ProcessHacker.Native;
+using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
namespace ProcessHacker.Native.Objects
@@ -15,7 +19,7 @@ public TypeObjectHandle(string name, ObjectFlags objectFlags, DirectoryHandle ro
try
{
- //this.Handle = KProcessHacker.Instance.KphOpenType(oa).ToIntPtr();
+ this.Handle = KProcessHacker.Instance.KphOpenType(oa).ToIntPtr();
}
finally
{
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/WindowHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/WindowHandle.cs
index e67a00a66..91e29aae4 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/WindowHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/WindowHandle.cs
@@ -1,5 +1,7 @@
using System;
using System.Drawing;
+using System.Runtime.InteropServices;
+using System.Text;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Objects
@@ -8,7 +10,7 @@ namespace ProcessHacker.Native.Objects
public struct WindowHandle : IEquatable, IEquatable, System.Windows.Forms.IWin32Window
{
- private static readonly WindowHandle _zero = new WindowHandle(IntPtr.Zero);
+ private static WindowHandle _zero = new WindowHandle(IntPtr.Zero);
public static WindowHandle Zero
{
@@ -52,7 +54,7 @@ public static implicit operator IntPtr(WindowHandle windowHandle)
return windowHandle.Handle;
}
- private readonly IntPtr _handle;
+ private IntPtr _handle;
public WindowHandle(IntPtr handle)
{
@@ -104,83 +106,70 @@ public bool Equals(IntPtr other)
return this.Handle.Equals(other);
}
- public ClientId ClientId
+ public ClientId GetClientId()
{
- get
- {
- int pid;
+ int tid, pid;
- int tid = Win32.GetWindowThreadProcessId(this, out pid);
+ tid = Win32.GetWindowThreadProcessId(this, out pid);
- return new ClientId(pid, tid);
- }
+ return new ClientId(pid, tid);
}
- public WindowHandle Parent
+ public WindowHandle GetParent()
{
- get { return new WindowHandle(Win32.GetParent(this)); }
+ return new WindowHandle(Win32.GetParent(this));
}
- public WindowPlacement Placement
+ public WindowPlacement GetPlacement()
{
- get
- {
- WindowPlacement placement = new WindowPlacement
- {
- Length = WindowPlacement.SizeOf
- };
+ WindowPlacement placement = new WindowPlacement();
+ placement.Length = Marshal.SizeOf(placement);
+ Win32.GetWindowPlacement(this, ref placement);
- Win32.GetWindowPlacement(this, ref placement);
-
- return placement;
- }
+ return placement;
}
- public Rectangle Rectangle
+ public Rectangle GetRectangle()
{
- get
- {
- Rect rect;
-
- if (!Win32.GetWindowRect(this, out rect))
- return Rectangle.Empty;
+ Rect rect;
+ if (!Win32.GetWindowRect(this, out rect))
+ return Rectangle.Empty;
+ else
return rect.ToRectangle();
- }
}
- public string Text
+ public string GetText()
{
- get
+ int retChars;
+
+ using (var data = new MemoryAlloc(0x200))
{
- using (MemoryAlloc data = new MemoryAlloc(0x200))
- {
- int retChars = Win32.InternalGetWindowText(this, data, data.Size/2);
+ retChars = Win32.InternalGetWindowText(this, data, data.Size / 2);
- return data.ReadUnicodeString(0, retChars);
- }
+ return data.ReadUnicodeString(0, retChars);
}
}
- public bool IsHung
+ public bool IsHung()
{
- get { return Win32.IsHungAppWindow(this); }
+ return Win32.IsHungAppWindow(this);
}
- public bool IsParent
+ public bool IsParent()
{
- get { return this.Parent.Equals(Zero); }
+ return this.GetParent().Equals(WindowHandle.Zero);
}
- public bool IsWindow
+ public bool IsWindow()
{
- get { return Win32.IsWindow(this); }
+ return Win32.IsWindow(this);
}
- public bool IsVisible
+ public bool IsVisible()
{
- get { return Win32.IsWindowVisible(this); }
+ return Win32.IsWindowVisible(this);
}
public bool PostMessage(WindowMessage message, int wParam, int lParam)
@@ -188,7 +177,7 @@ public bool PostMessage(WindowMessage message, int wParam, int lParam)
return Win32.PostMessage(this, message, wParam, lParam);
}
- public IntPtr SendMessage(WindowMessage message, IntPtr wParam, IntPtr lParam)
+ public IntPtr SendMessage(WindowMessage message, int wParam, int lParam)
{
return Win32.SendMessage(this, message, wParam, lParam);
}
diff --git a/1.x/trunk/ProcessHacker.Native/Objects/WindowStationHandle.cs b/1.x/trunk/ProcessHacker.Native/Objects/WindowStationHandle.cs
index 63fb29e5f..180a970f0 100644
--- a/1.x/trunk/ProcessHacker.Native/Objects/WindowStationHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/Objects/WindowStationHandle.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security;
@@ -48,7 +50,7 @@ public WindowStationHandle(string name, WindowStationAccess access)
{
this.Handle = Win32.OpenWindowStation(name, false, access);
- if (this.Handle == IntPtr.Zero)
+ if (this.Handle == System.IntPtr.Zero)
Win32.Throw();
}
diff --git a/1.x/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj b/1.x/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj
index f91925c68..e6e74a769 100644
--- a/1.x/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj
+++ b/1.x/trunk/ProcessHacker.Native/ProcessHacker.Native.csproj
@@ -10,7 +10,7 @@
Properties
ProcessHacker.Native
ProcessHacker.Native
- v4.5
+ v4.0
512
@@ -47,8 +47,7 @@
AnyCPU
- MinimumRecommendedRules.ruleset
- false
+ AllRules.ruleset
pdbonly
@@ -62,7 +61,6 @@
1591
AnyCPU
AllRules.ruleset
- false
@@ -126,7 +124,6 @@
-
@@ -152,12 +149,6 @@
-
- UserControl
-
-
- UserControl
-
@@ -280,6 +271,18 @@
+
+ Form
+
+
+ ChooseProcessDialog.cs
+
+
+ Form
+
+
+ HandlePropertiesWindow.cs
+
@@ -289,6 +292,14 @@
+
+
+ ChooseProcessDialog.cs
+
+
+ HandlePropertiesWindow.cs
+
+
{8E10F5E8-D4FA-4980-BB23-2EDD134AC15E}
diff --git a/1.x/trunk/ProcessHacker.Native/PropertySheet/ProcessPropertySheetPage.cs b/1.x/trunk/ProcessHacker.Native/PropertySheet/ProcessPropertySheetPage.cs
deleted file mode 100644
index 425d78117..000000000
--- a/1.x/trunk/ProcessHacker.Native/PropertySheet/ProcessPropertySheetPage.cs
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Process Hacker -
- * Process Property Sheet Control
- *
- * Copyright (C) 2011 wj32
- * Copyright (C) 2011 dmex
- *
- * This file is part of Process Hacker.
- *
- * Process Hacker is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * Process Hacker is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Process Hacker. If not, see .
- */
-
-using System;
-using System.Runtime.InteropServices;
-
-using ProcessHacker.Native;
-using ProcessHacker.Native.Api;
-
-namespace ProcessHacker.Api
-{
- public class ProcessPropertySheetPage : PropertySheetPage
- {
- private IntPtr _pageHandle;
- private IntPtr _dialogTemplate;
- private readonly DialogProc _dialogProc;
- private readonly PropSheetPageCallback _pagePageProc;
-
- public ProcessPropertySheetPage()
- {
- _dialogProc = this.DialogProc;
- _pagePageProc = this.PropPageProc;
- }
-
- protected override void Dispose(bool disposing)
- {
- MemoryAlloc.PrivateHeap.Free(this._dialogTemplate);
-
- base.Dispose(disposing);
- }
-
- public override IntPtr CreatePageHandle()
- {
- if (_pageHandle != IntPtr.Zero)
- return _pageHandle;
-
- PropSheetPageW psp = new PropSheetPageW();
-
- // *Must* be 260x260. See PhAddPropPageLayoutItem in procprp.c.
- _dialogTemplate = CreateDialogTemplate(260, 260, this.Text, 8, "MS Shell Dlg");
-
- psp.dwSize = PropSheetPageW.SizeOf;
- psp.dwFlags = PropSheetPageFlags.UseCallback | PropSheetPageFlags.DlgIndirect | PropSheetPageFlags.UseTitle | PropSheetPageFlags.DlgIndirect;
-
- psp.pszTitle = Marshal.StringToHGlobalUni("Details");
-
- psp.pResource = _dialogTemplate;
-
- psp.pfnDlgProc = Marshal.GetFunctionPointerForDelegate(_dialogProc);
- psp.pfnCallback = Marshal.GetFunctionPointerForDelegate(_pagePageProc);
-
- _pageHandle = Win32.CreatePropertySheetPageW(ref psp);
-
- return _pageHandle;
- }
-
- protected override bool DialogProc(IntPtr hwndDlg, WindowMessage uMsg, IntPtr wParam, IntPtr lParam)
- {
- switch (uMsg)
- {
- case WindowMessage.InitDialog:
- {
- Rect initialSize = new Rect
- {
- Left = 0,
- Top = 0,
- Right = 260,
- Bottom = 260
- };
-
- Win32.MapDialogRect(hwndDlg, ref initialSize);
-
- this.Size = new System.Drawing.Size(initialSize.Right, initialSize.Bottom);
-
- this.Refresh();
- }
- break;
- }
-
- return base.DialogProc(hwndDlg, uMsg, wParam, lParam);
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker.Native/PropertySheet/PropertySheetPage.cs b/1.x/trunk/ProcessHacker.Native/PropertySheet/PropertySheetPage.cs
deleted file mode 100644
index 278b1a0d3..000000000
--- a/1.x/trunk/ProcessHacker.Native/PropertySheet/PropertySheetPage.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Process Hacker -
- * Property Sheet Control
- *
- * Copyright (C) 2010 wj32
- * Copyright (C) 2010 dmex
- *
- * This file is part of Process Hacker.
- *
- * Process Hacker is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * Process Hacker is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Process Hacker. If not, see .
- */
-
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Windows.Forms;
-using ProcessHacker.Native;
-using ProcessHacker.Native.Api;
-
-namespace ProcessHacker.Api
-{
- public class PropertySheetPage : UserControl
- {
- private static readonly List _keepAliveList = new List();
-
- public unsafe static IntPtr CreateDialogTemplate(int width, int height, string title, short fontSize, string fontName)
- {
- DlgTemplate* template;
- int templateStructSize;
- int offset;
-
- templateStructSize = DlgTemplate.SizeOf;
- template = (DlgTemplate*)MemoryAlloc.PrivateHeap.Allocate(templateStructSize + 2 + 2 + (title.Length + 1) * 2 + 2 + (fontName.Length + 1) * 2);
- template->style = 0x40; // DS_SETFONT
- template->dwExtendedStyle = 0;
- template->cdit = 0;
- template->x = 0;
- template->y = 0;
- template->cx = (short)width;
- template->cy = (short)height;
-
- offset = templateStructSize;
-
- // No menu
- *(short*)((byte*)template + offset) = 0;
- offset += 2;
-
- // No class
- *(short*)((byte*)template + offset) = 0;
- offset += 2;
-
- // Title
- fixed (char* titlePtr = title)
- Win32.RtlMoveMemory((byte*)template + offset, titlePtr, (IntPtr)((title.Length + 1) * 2));
- offset += (title.Length + 1) * 2;
-
- // Font size
- *(short*)((byte*)template + offset) = fontSize;
- offset += 2;
-
- // Font name
- fixed (char* fontNamePtr = fontName)
- Win32.RtlMoveMemory((byte*)template + offset, fontNamePtr, (IntPtr)((fontName.Length + 1) * 2));
- //offset += (fontName.Length + 1) * 2;
-
- return (IntPtr)template;
- }
-
- public event EventHandler PageGotFocus;
- public event EventHandler PageLostFocus;
-
- private readonly IContainer components;
- private IntPtr _dialogWindowParentHandle;
-
- public PropertySheetPage()
- {
- components = new Container();
- this.AutoScaleMode = AutoScaleMode.Font;
- }
-
- ///
- /// Clean up any resources being used.
- ///
- /// true if managed resources should be disposed; otherwise, false.
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
-
- base.Dispose(disposing);
- }
-
- public virtual IntPtr CreatePageHandle()
- {
- throw new NotImplementedException();
- }
-
- protected virtual bool DialogProc(IntPtr hwndDlg, WindowMessage uMsg, IntPtr wParam, IntPtr lParam)
- {
- switch (uMsg)
- {
- case WindowMessage.InitDialog:
- {
- _dialogWindowParentHandle = Win32.GetParent(hwndDlg);
- Win32.SetParent(this.Handle, hwndDlg);
-
- this.Refresh();
- }
- break;
- case WindowMessage.Notify:
- return OnDialogNotify(hwndDlg, wParam, lParam);
- }
-
- return false;
- }
-
- private unsafe bool OnDialogNotify(IntPtr hwndDlg, IntPtr wParam, IntPtr lParam)
- {
- Win32.NmHdr* hdr = (Win32.NmHdr*)lParam;
-
- if (hdr->hwndFrom != _dialogWindowParentHandle)
- return false;
-
- switch (hdr->code)
- {
- case (uint)PropSheetNotification.SetActive:
- if (this.PageGotFocus != null)
- this.PageGotFocus(this, new EventArgs());
- break;
- case (uint)PropSheetNotification.KillActive:
- if (this.PageLostFocus != null)
- this.PageLostFocus(this, new EventArgs());
- break;
- }
-
- return false;
- }
-
- protected int PropPageProc(IntPtr hwnd, PropSheetPageCallbackMessage uMsg, IntPtr ppsp)
- {
- switch (uMsg)
- {
- case PropSheetPageCallbackMessage.AddRef:
- _keepAliveList.Add(this);
- break;
- case PropSheetPageCallbackMessage.Release:
- _keepAliveList.Remove(this);
- break;
- }
-
- return 1;
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/Acl.cs b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/Acl.cs
index 02bdf0a97..cdc3b0bb0 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/Acl.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/Acl.cs
@@ -22,6 +22,7 @@
using System;
using System.Collections.Generic;
+using System.Runtime.InteropServices;
using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
@@ -39,10 +40,12 @@ public static implicit operator IntPtr(Acl acl)
return acl.Memory;
}
- private readonly MemoryRegion _memory;
+ private MemoryRegion _memory;
public Acl(int size)
{
+ NtStatus status;
+
// Reserve 8 bytes for the ACL header.
if (size < 8)
throw new ArgumentException("Size must be greater than or equal to 8 bytes.");
@@ -51,11 +54,11 @@ public Acl(int size)
_memory = new MemoryAlloc(size);
// Initialize the ACL.
- if (Win32.RtlCreateAcl(
+ if ((status = Win32.RtlCreateAcl(
_memory,
size,
Win32.AclRevision
- ).IsError())
+ )) >= NtStatus.Error)
{
// Dispose memory and disable ownership.
_memory.Dispose();
@@ -137,61 +140,78 @@ public bool IsValid()
public void AddAccessAllowed(int accessMask, Sid sid)
{
- Win32.RtlAddAccessAllowedAce(
+ NtStatus status;
+
+ if ((status = Win32.RtlAddAccessAllowedAce(
this,
Win32.AclRevision,
accessMask,
sid
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddAccessAllowed(int accessMask, Sid sid, AceFlags flags)
{
- Win32.RtlAddAccessAllowedAceEx(
+ NtStatus status;
+
+ if ((status = Win32.RtlAddAccessAllowedAceEx(
this,
Win32.AclRevision,
flags,
accessMask,
sid
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddAccessDenied(int accessMask, Sid sid)
{
- Win32.RtlAddAccessDeniedAce(
+ NtStatus status;
+
+ if ((status = Win32.RtlAddAccessDeniedAce(
this,
Win32.AclRevision,
accessMask,
sid
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddAccessDenied(int accessMask, Sid sid, AceFlags flags)
{
- Win32.RtlAddAccessDeniedAceEx(
+ NtStatus status;
+
+ if ((status = Win32.RtlAddAccessDeniedAceEx(
this,
Win32.AclRevision,
flags,
accessMask,
sid
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddAuditAccess(int accessMask, Sid sid, bool auditSuccess, bool auditFailure)
{
- Win32.RtlAddAuditAccessAce(
+ NtStatus status;
+
+ if ((status = Win32.RtlAddAuditAccessAce(
this,
Win32.AclRevision,
accessMask,
sid,
auditSuccess,
auditFailure
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddAuditAccess(int accessMask, Sid sid, bool auditSuccess, bool auditFailure, AceFlags flags)
{
- Win32.RtlAddAuditAccessAceEx(
+ NtStatus status;
+
+ if ((status = Win32.RtlAddAuditAccessAceEx(
this,
Win32.AclRevision,
flags,
@@ -199,19 +219,23 @@ public void AddAuditAccess(int accessMask, Sid sid, bool auditSuccess, bool audi
sid,
auditSuccess,
auditFailure
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddCompound(AceType type, int accessMask, Sid serverSid, Sid clientSid)
{
- Win32.RtlAddCompoundAce(
+ NtStatus status;
+
+ if ((status = Win32.RtlAddCompoundAce(
this,
Win32.AclRevision,
type,
accessMask,
serverSid,
clientSid
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
public void AddRange(int index, IEnumerable aceList)
@@ -224,7 +248,7 @@ public void AddRange(int index, IEnumerable aceList)
totalSize += ace.Size;
}
- using (MemoryAlloc aceListMemory = new MemoryAlloc(totalSize))
+ using (var aceListMemory = new MemoryAlloc(totalSize))
{
int i = 0;
@@ -235,22 +259,27 @@ public void AddRange(int index, IEnumerable aceList)
i += ace.Size;
}
+ NtStatus status;
+
// Add the ACEs to the ACL.
- Win32.RtlAddAce(
+ if ((status = Win32.RtlAddAce(
this,
Win32.AclRevision,
index,
aceListMemory,
totalSize
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
public Ace GetAt(int index)
{
+ NtStatus status;
IntPtr ace;
- Win32.RtlGetAce(this, index, out ace).ThrowIf();
+ if ((status = Win32.RtlGetAce(this, index, out ace)) >= NtStatus.Error)
+ Win32.Throw(status);
return Ace.GetAce(ace);
}
@@ -268,21 +297,26 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
public AclSizeInformation GetSizeInformation()
{
+ NtStatus status;
AclSizeInformation sizeInfo;
- Win32.RtlQueryInformationAcl(
+ if ((status = Win32.RtlQueryInformationAcl(
this,
out sizeInfo,
- AclSizeInformation.SizeOf,
+ Marshal.SizeOf(typeof(AclSizeInformation)),
AclInformationClass.AclSizeInformation
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return sizeInfo;
}
public void RemoveAt(int index)
{
- Win32.RtlDeleteAce(this, index).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.RtlDeleteAce(this, index)) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/KnownAce.cs b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/KnownAce.cs
index c464cca2b..8b5c12192 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/KnownAce.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/KnownAce.cs
@@ -22,15 +22,19 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Security.AccessControl
{
- public sealed class KnownAce : Ace
+ public class KnownAce : Ace
{
private int _mask;
private Sid _sid;
+ protected KnownAce()
+ { }
+
public KnownAce(AceType type, AceFlags flags, int mask, Sid sid)
{
if (
@@ -42,25 +46,20 @@ public KnownAce(AceType type, AceFlags flags, int mask, Sid sid)
throw new ArgumentException("Invalid ACE type.");
this.MemoryRegion = new MemoryAlloc(
- KnownAceStruct.SizeOf - // known ace struct size
+ Marshal.SizeOf(typeof(KnownAceStruct)) - // known ace struct size
sizeof(int) + // minus SidStart field
sid.Length // plus SID length
);
- // Initialize the ACE (minus the SID).
- KnownAceStruct knownAce = new KnownAceStruct
- {
- Mask = mask,
- Header =
- {
- AceType = type,
- AceFlags = flags,
- AceSize = (ushort)this.MemoryRegion.Size
- }
- };
+ KnownAceStruct knownAce = new KnownAceStruct();
+ // Initialize the ACE (minus the SID).
+ knownAce.Header.AceType = type;
+ knownAce.Header.AceFlags = flags;
+ knownAce.Header.AceSize = (ushort)this.MemoryRegion.Size;
+ knownAce.Mask = mask;
// Write the ACE to memory.
- this.MemoryRegion.WriteStruct(knownAce);
+ this.MemoryRegion.WriteStruct(knownAce);
// Write the SID.
this.MemoryRegion.WriteMemory(Win32.KnownAceSidStartOffset.ToInt32(), sid, sid.Length);
// Update the cached info.
diff --git a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityDescriptor.cs b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityDescriptor.cs
index 3c45ab86a..116f03917 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityDescriptor.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityDescriptor.cs
@@ -40,11 +40,12 @@ public sealed class SecurityDescriptor : BaseObject
/// A security descriptor.
public static SecurityDescriptor GetSecurity(IntPtr handle, SecurityInformation securityInformation)
{
- using (MemoryAlloc data = new MemoryAlloc(0x100))
- {
- int retLength;
+ NtStatus status;
+ int retLength;
- NtStatus status = Win32.NtQuerySecurityObject(
+ using (var data = new MemoryAlloc(0x100))
+ {
+ status = Win32.NtQuerySecurityObject(
handle,
securityInformation,
data,
@@ -56,16 +57,17 @@ out retLength
{
data.ResizeNew(retLength);
- Win32.NtQuerySecurityObject(
+ status = Win32.NtQuerySecurityObject(
handle,
securityInformation,
data,
data.Size,
out retLength
- ).ThrowIf();
+ );
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return new SecurityDescriptor(data);
}
@@ -103,11 +105,14 @@ out securityDescriptor
/// The security descriptor.
public static void SetSecurity(IntPtr handle, SecurityInformation securityInformation, SecurityDescriptor securityDescriptor)
{
- Win32.NtSetSecurityObject(
+ NtStatus status;
+
+ if ((status = Win32.NtSetSecurityObject(
handle,
securityInformation,
securityDescriptor
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
///
@@ -125,13 +130,13 @@ public static void SetSecurity(IntPtr handle, SeObjectType objectType, SecurityI
IntPtr owner = IntPtr.Zero;
IntPtr sacl = IntPtr.Zero;
- if (securityInformation.HasFlag(SecurityInformation.Dacl))
+ if ((securityInformation & SecurityInformation.Dacl) == SecurityInformation.Dacl)
dacl = securityDescriptor.Dacl ?? IntPtr.Zero;
- if (securityInformation.HasFlag(SecurityInformation.Group))
+ if ((securityInformation & SecurityInformation.Group) == SecurityInformation.Group)
group = securityDescriptor.Group;
- if (securityInformation.HasFlag(SecurityInformation.Owner))
+ if ((securityInformation & SecurityInformation.Owner) == SecurityInformation.Owner)
owner = securityDescriptor.Owner;
- if (securityInformation.HasFlag(SecurityInformation.Sacl))
+ if ((securityInformation & SecurityInformation.Sacl) == SecurityInformation.Sacl)
sacl = securityDescriptor.Sacl ?? IntPtr.Zero;
if ((result = Win32.SetSecurityInfo(
@@ -151,7 +156,7 @@ public static implicit operator IntPtr(SecurityDescriptor securityDescriptor)
return securityDescriptor.Memory;
}
- private readonly MemoryRegion _memory;
+ private MemoryRegion _memory;
private Acl _dacl;
private Acl _sacl;
private Sid _owner;
@@ -169,7 +174,7 @@ public SecurityDescriptor()
if ((status = Win32.RtlCreateSecurityDescriptor(
_memory,
Win32.SecurityDescriptorRevision
- )).IsError())
+ )) >= NtStatus.Error)
{
_memory.Dispose();
_memory = null;
@@ -229,24 +234,29 @@ public SecurityDescriptorControlFlags ControlFlags
{
get
{
+ NtStatus status;
SecurityDescriptorControlFlags control;
int revision;
- Win32.RtlGetControlSecurityDescriptor(
+ if ((status = Win32.RtlGetControlSecurityDescriptor(
this,
out control,
out revision
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return control;
}
set
{
- Win32.RtlSetControlSecurityDescriptor(
+ NtStatus status;
+
+ if ((status = Win32.RtlSetControlSecurityDescriptor(
this,
value,
value
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
}
}
@@ -258,12 +268,15 @@ public Acl Dacl
get { return _dacl; }
set
{
- Win32.RtlSetDaclSecurityDescriptor(
+ NtStatus status;
+
+ if ((status = Win32.RtlSetDaclSecurityDescriptor(
this,
value != null,
value ?? IntPtr.Zero,
false
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.SwapDacl(value);
}
@@ -274,7 +287,11 @@ public Acl Dacl
///
public bool DaclDefaulted
{
- get { return this.ControlFlags.HasFlag(SecurityDescriptorControlFlags.DaclDefaulted); }
+ get
+ {
+ return (this.ControlFlags & SecurityDescriptorControlFlags.DaclDefaulted) ==
+ SecurityDescriptorControlFlags.DaclDefaulted;
+ }
set
{
if (value)
@@ -292,11 +309,14 @@ public Sid Group
get { return _group; }
set
{
- Win32.RtlSetGroupSecurityDescriptor(
+ NtStatus status;
+
+ if ((status = Win32.RtlSetGroupSecurityDescriptor(
this,
value,
false
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.SwapGroup(value);
}
@@ -307,7 +327,11 @@ public Sid Group
///
public bool GroupDefaulted
{
- get { return this.ControlFlags.HasFlag(SecurityDescriptorControlFlags.GroupDefaulted); }
+ get
+ {
+ return (this.ControlFlags & SecurityDescriptorControlFlags.GroupDefaulted) ==
+ SecurityDescriptorControlFlags.GroupDefaulted;
+ }
set
{
if (value)
@@ -341,11 +365,14 @@ public Sid Owner
get { return _owner; }
set
{
- Win32.RtlSetOwnerSecurityDescriptor(
+ NtStatus status;
+
+ if ((status = Win32.RtlSetOwnerSecurityDescriptor(
this,
value,
false
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.SwapOwner(value);
}
@@ -378,12 +405,15 @@ public Acl Sacl
get { return _sacl; }
set
{
- Win32.RtlSetSaclSecurityDescriptor(
+ NtStatus status;
+
+ if ((status = Win32.RtlSetSaclSecurityDescriptor(
this,
value != null,
value ?? IntPtr.Zero,
false
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
this.SwapSacl(value);
}
@@ -394,7 +424,11 @@ public Acl Sacl
///
public bool SaclDefaulted
{
- get { return this.ControlFlags.HasFlag(SecurityDescriptorControlFlags.SaclDefaulted); }
+ get
+ {
+ return (this.ControlFlags & SecurityDescriptorControlFlags.SaclDefaulted) ==
+ SecurityDescriptorControlFlags.SaclDefaulted;
+ }
set
{
if (value)
@@ -409,7 +443,11 @@ public bool SaclDefaulted
///
public bool SelfRelative
{
- get { return this.ControlFlags.HasFlag(SecurityDescriptorControlFlags.SelfRelative); }
+ get
+ {
+ return (this.ControlFlags & SecurityDescriptorControlFlags.SelfRelative) ==
+ SecurityDescriptorControlFlags.SelfRelative;
+ }
}
///
@@ -422,10 +460,11 @@ public bool SelfRelative
/// Success if access was granted, otherwise another NT status value.
public NtStatus CheckAccess(TokenHandle tokenHandle, int desiredAccess, GenericMapping genericMapping, out int grantedAccess)
{
+ NtStatus status;
NtStatus accessStatus;
int privilegeSetLength = 0;
- Win32.NtAccessCheck(
+ if ((status = Win32.NtAccessCheck(
this,
tokenHandle,
desiredAccess,
@@ -434,7 +473,8 @@ public NtStatus CheckAccess(TokenHandle tokenHandle, int desiredAccess, GenericM
ref privilegeSetLength,
out grantedAccess,
out accessStatus
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return accessStatus;
}
@@ -443,23 +483,25 @@ out accessStatus
/// Checks whether the security descriptor is valid.
///
/// True if the security descriptor is valid, otherwise false.
- public bool IsValid
+ public bool IsValid()
{
- get { return Win32.RtlValidSecurityDescriptor(this); }
+ return Win32.RtlValidSecurityDescriptor(this);
}
private void Read()
{
+ NtStatus status;
bool present, defaulted;
IntPtr dacl, group, owner, sacl;
// Read the DACL.
- Win32.RtlGetDaclSecurityDescriptor(
+ if ((status = Win32.RtlGetDaclSecurityDescriptor(
this,
out present,
out dacl,
out defaulted
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (present && dacl != IntPtr.Zero)
this.SwapDacl(new Acl(Acl.FromPointer(dacl)));
@@ -467,12 +509,13 @@ out defaulted
this.SwapDacl(null);
// Read the SACL.
- Win32.RtlGetSaclSecurityDescriptor(
+ if ((status = Win32.RtlGetSaclSecurityDescriptor(
this,
out present,
out sacl,
out defaulted
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (present && sacl != IntPtr.Zero)
this.SwapSacl(new Acl(Acl.FromPointer(sacl)));
@@ -480,11 +523,12 @@ out defaulted
this.SwapSacl(null);
// Read the group.
- Win32.RtlGetGroupSecurityDescriptor(
+ if ((status = Win32.RtlGetGroupSecurityDescriptor(
this,
out group,
out defaulted
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (group != IntPtr.Zero)
this.SwapGroup(new Sid(group));
@@ -492,11 +536,12 @@ out defaulted
this.SwapGroup(null);
// Read the owner.
- Win32.RtlGetOwnerSecurityDescriptor(
+ if ((status = Win32.RtlGetOwnerSecurityDescriptor(
this,
out owner,
out defaulted
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
if (owner != IntPtr.Zero)
this.SwapOwner(new Sid(owner));
@@ -506,22 +551,22 @@ out defaulted
private void SwapDacl(Acl dacl)
{
- BaseObject.SwapRef(ref _dacl, dacl);
+ BaseObject.SwapRef(ref _dacl, dacl);
}
private void SwapGroup(Sid group)
{
- BaseObject.SwapRef(ref _group, group);
+ BaseObject.SwapRef(ref _group, group);
}
private void SwapOwner(Sid owner)
{
- BaseObject.SwapRef(ref _owner, owner);
+ BaseObject.SwapRef(ref _owner, owner);
}
private void SwapSacl(Acl sacl)
{
- BaseObject.SwapRef(ref _sacl, sacl);
+ BaseObject.SwapRef(ref _sacl, sacl);
}
///
@@ -530,11 +575,13 @@ private void SwapSacl(Acl sacl)
/// A new self-relative security descriptor.
public SecurityDescriptor ToSelfRelative()
{
- using (MemoryAlloc data = new MemoryAlloc(Win32.SecurityDescriptorMinLength))
- {
- int retLength = data.Size;
+ NtStatus status;
+ int retLength;
- NtStatus status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);
+ using (var data = new MemoryAlloc(Win32.SecurityDescriptorMinLength))
+ {
+ retLength = data.Size;
+ status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);
if (status == NtStatus.BufferTooSmall)
{
@@ -542,7 +589,8 @@ public SecurityDescriptor ToSelfRelative()
status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return new SecurityDescriptor(data);
}
diff --git a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityEditor.cs b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityEditor.cs
index f63653404..a2c609d3b 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityEditor.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/AccessControl/SecurityEditor.cs
@@ -22,9 +22,11 @@
using System;
using System.Collections.Generic;
+using System.Runtime.InteropServices;
using System.Windows.Forms;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
+using ProcessHacker.Native.Security.AccessControl;
namespace ProcessHacker.Native.Security.AccessControl
{
@@ -32,7 +34,7 @@ public class SecurityEditor : IDisposable, ISecurityInformation
{
private class SecurableObjectWrapper : ISecurable
{
- private readonly Func _openMethod;
+ private Func _openMethod;
public SecurableObjectWrapper(Func openMethod)
{
@@ -63,8 +65,8 @@ public void SetSecurity(SecurityInformation securityInformation, SecurityDescrip
private class SeSecurableObjectWrapper : ISecurable
{
- private readonly SeObjectType _objectType;
- private readonly Func _openMethod;
+ private SeObjectType _objectType;
+ private Func _openMethod;
public SeSecurableObjectWrapper(SeObjectType objectType, Func openMethod)
{
@@ -96,24 +98,18 @@ public void SetSecurity(SecurityInformation securityInformation, SecurityDescrip
public static void EditSecurity(IWin32Window owner, ISecurable securable, string name, IEnumerable accessEntries)
{
- using (SecurityEditor osi = new SecurityEditor(securable, name, accessEntries))
+ using (var osi = new SecurityEditor(securable, name, accessEntries))
Win32.EditSecurity(owner != null ? owner.Handle : IntPtr.Zero, osi);
}
-
- public static SecurityEditor EditSecurity2(IWin32Window owner, ISecurable securable, string name, IEnumerable accessEntries)
- {
- return new SecurityEditor(securable, name, accessEntries);
- }
-
public static ISecurable GetSecurableWrapper(IntPtr handle)
{
- return GetSecurableWrapper(access => new NativeHandle(handle, access));
+ return GetSecurableWrapper((access) => new NativeHandle(handle, access));
}
public static ISecurable GetSecurableWrapper(SeObjectType objectType, IntPtr handle)
{
- return GetSecurableWrapper(objectType, access => new NativeHandle(handle, access));
+ return GetSecurableWrapper(objectType, (access) => new NativeHandle(handle, access));
}
public static ISecurable GetSecurableWrapper(Func openMethod)
@@ -126,25 +122,27 @@ public static ISecurable GetSecurableWrapper(SeObjectType objectType, Func _pool = new List();
- private readonly string _name;
- private readonly MemoryAlloc _accessRights;
- private readonly int _accessRightCount;
+ private bool _disposed = false;
+ private ISecurable _securable;
+ private List _pool = new List();
+ private string _name;
+ private MemoryAlloc _accessRights;
+ private int _accessRightCount;
internal SecurityEditor(ISecurable securable, string name, IEnumerable accessEntries)
{
+ List accesses;
+
_securable = securable;
_name = name;
- List accesses = new List();
+ accesses = new List();
- foreach (AccessEntry entry in accessEntries)
+ foreach (var entry in accessEntries)
{
if (entry.Mask != 0)
{
- accesses.Add(new SiAccess
+ accesses.Add(new SiAccess()
{
Guid = IntPtr.Zero,
Mask = entry.Mask,
@@ -154,7 +152,7 @@ internal SecurityEditor(ISecurable securable, string name, IEnumerable(accesses.ToArray());
_accessRightCount = accesses.Count;
}
@@ -162,7 +160,7 @@ public void Dispose()
{
if (!_disposed)
{
- _pool.ForEach(alloc => alloc.Dispose());
+ _pool.ForEach((alloc) => alloc.Dispose());
_pool.Clear();
_disposed = true;
}
@@ -202,37 +200,39 @@ private MemoryAlloc AllocateStringFromPool(string value)
return m;
}
- private MemoryAlloc AllocateStruct(int size, T value) where T : struct
+ private MemoryAlloc AllocateStruct(T value)
+ where T : struct
{
- MemoryAlloc alloc = new MemoryAlloc(size);
+ MemoryAlloc alloc = new MemoryAlloc(Marshal.SizeOf(typeof(T)));
- alloc.WriteStruct(0, size, value);
+ alloc.WriteStruct(0, value);
return alloc;
}
- private MemoryAlloc AllocateStructFromPool(int size, T value)
+ private MemoryAlloc AllocateStructFromPool(T value)
where T : struct
{
- MemoryAlloc m = this.AllocateStruct(size, value);
+ MemoryAlloc m = this.AllocateStruct(value);
_pool.Add(m);
return m;
}
- private MemoryAlloc AllocateStructArray(int size, T[] value) where T : struct
+ private MemoryAlloc AllocateStructArray(T[] value)
+ where T : struct
{
- MemoryAlloc alloc = new MemoryAlloc(size * value.Length);
+ MemoryAlloc alloc = new MemoryAlloc(Marshal.SizeOf(typeof(T)) * value.Length);
for (int i = 0; i < value.Length; i++)
- alloc.WriteStruct(i, size, value[i]);
+ alloc.WriteStruct(i, value[i]);
return alloc;
}
- private MemoryAlloc AllocateStructArrayFromPool(int size, T[] value)
+ private MemoryAlloc AllocateStructArrayFromPool(T[] value)
where T : struct
{
- MemoryAlloc m = this.AllocateStructArray(size, value);
+ MemoryAlloc m = this.AllocateStructArray(value);
_pool.Add(m);
return m;
}
@@ -241,18 +241,17 @@ private MemoryAlloc AllocateStructArrayFromPool(int size, T[] value)
public HResult GetObjectInformation(out SiObjectInfo ObjectInfo)
{
- SiObjectInfo soi = new SiObjectInfo
- {
- Flags = SiObjectInfoFlags.EditAudits |
- SiObjectInfoFlags.EditOwner |
- SiObjectInfoFlags.EditPerms |
- SiObjectInfoFlags.Advanced |
- SiObjectInfoFlags.NoAclProtect |
- SiObjectInfoFlags.NoTreeApply,
- Instance = IntPtr.Zero,
- ObjectName = this.AllocateStringFromPool(this._name)
- };
-
+ SiObjectInfo soi = new SiObjectInfo();
+
+ soi.Flags =
+ SiObjectInfoFlags.EditAudits |
+ SiObjectInfoFlags.EditOwner |
+ SiObjectInfoFlags.EditPerms |
+ SiObjectInfoFlags.Advanced |
+ SiObjectInfoFlags.NoAclProtect |
+ SiObjectInfoFlags.NoTreeApply;
+ soi.Instance = IntPtr.Zero;
+ soi.ObjectName = this.AllocateStringFromPool(_name);
ObjectInfo = soi;
return HResult.OK;
@@ -262,12 +261,12 @@ public HResult GetSecurity(SecurityInformation RequestedInformation, out IntPtr
{
try
{
- using (SecurityDescriptor sd = _securable.GetSecurity(RequestedInformation))
+ using (var sd = _securable.GetSecurity(RequestedInformation))
{
// Since the ACL editor will free the security descriptor using
// LocalFree, we need to use a local memory allocation and copy
// the security descriptor into it.
- using (LocalMemoryAlloc localAlloc = new LocalMemoryAlloc(sd.Length))
+ using (var localAlloc = new LocalMemoryAlloc(sd.Length))
{
localAlloc.WriteMemory(0, sd.Memory, sd.Length);
localAlloc.Reference(); // reference for ACL editor
@@ -334,10 +333,10 @@ public HResult PropertySheetPageCallback(IntPtr hWnd, SiCallbackMessage Msg, SiP
public struct AccessEntry
{
- private readonly bool _general;
- private readonly int _mask;
- private readonly string _name;
- private readonly bool _specific;
+ private bool _general;
+ private int _mask;
+ private string _name;
+ private bool _specific;
public AccessEntry(string name, object mask, bool general, bool specific)
{
diff --git a/1.x/trunk/ProcessHacker.Native/Security/Authentication/Credentials.cs b/1.x/trunk/ProcessHacker.Native/Security/Authentication/Credentials.cs
index f00eb2973..55cbfbc3f 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/Authentication/Credentials.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/Authentication/Credentials.cs
@@ -33,10 +33,10 @@ public static MemoryRegion PackCredentials(CredPackFlags flags, string userName,
MemoryAlloc data = new MemoryAlloc(0x100);
int size = data.Size;
- if (string.IsNullOrEmpty(userName))
- userName = string.Empty;
- if (string.IsNullOrEmpty(password))
- password = string.Empty;
+ if (userName == null)
+ userName = "";
+ if (password == null)
+ password = "";
if (!Win32.CredPackAuthenticationBuffer(flags, userName, password, data, ref size))
{
@@ -57,9 +57,9 @@ public static void UnpackCredentials(
out string password
)
{
- using (MemoryAlloc domainNameBuffer = new MemoryAlloc(0x100))
- using (MemoryAlloc userNameBuffer = new MemoryAlloc(0x100))
- using (MemoryAlloc passwordBuffer = new MemoryAlloc(0x100))
+ using (var domainNameBuffer = new MemoryAlloc(0x100))
+ using (var userNameBuffer = new MemoryAlloc(0x100))
+ using (var passwordBuffer = new MemoryAlloc(0x100))
{
int domainNameSize = domainNameBuffer.Size / 2 - 1;
int userNameSize = userNameBuffer.Size / 2 - 1;
@@ -122,13 +122,13 @@ CredUiFlags flags
if (userName.Length > maxChars || password.Length > maxChars)
throw new ArgumentException("The user name or password string is too long.");
- info.Size = CredUiInfo.SizeOf;
+ info.Size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(CredUiInfo));
info.Parent = parent != null ? parent.Handle : IntPtr.Zero;
info.MessageText = messageText;
info.CaptionText = captionText;
- using (MemoryAlloc userNameAlloc = new MemoryAlloc(maxBytes))
- using (MemoryAlloc passwordAlloc = new MemoryAlloc(maxBytes))
+ using (var userNameAlloc = new MemoryAlloc(maxBytes))
+ using (var passwordAlloc = new MemoryAlloc(maxBytes))
{
userNameAlloc.WriteUnicodeString(0, userName);
userNameAlloc.WriteInt16(userName.Length * 2, 0);
@@ -178,12 +178,12 @@ CredUiWinFlags flags
IntPtr outAuthBuffer;
int outAuthBufferSize;
- info.Size = CredUiInfo.SizeOf;
+ info.Size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(CredUiInfo));
info.Parent = parent != null ? parent.Handle : IntPtr.Zero;
info.MessageText = messageText;
info.CaptionText = captionText;
- using (MemoryRegion inAuthBuffer = PackCredentials(0, userName, password))
+ using (var inAuthBuffer = PackCredentials(0, userName, password))
{
result = Win32.CredUIPromptForWindowsCredentials(
ref info,
@@ -223,10 +223,11 @@ out password
public static SecPkgInfo[] GetSSPackages()
{
+ int result;
int count;
IntPtr packages;
- int result = Win32.EnumerateSecurityPackages(out count, out packages);
+ result = Win32.EnumerateSecurityPackages(out count, out packages);
if (result != 0)
Win32.Throw(result);
@@ -238,7 +239,7 @@ public static SecPkgInfo[] GetSSPackages()
SecPkgInfo[] array = new SecPkgInfo[count];
for (int i = 0; i < count; i++)
- array[i] = alloc.ReadStruct(0, SecPkgInfo.SizeOf, i);
+ array[i] = alloc.ReadStruct(i);
return array;
}
diff --git a/1.x/trunk/ProcessHacker.Native/Security/Authentication/Msv1_0_InteractivePackage.cs b/1.x/trunk/ProcessHacker.Native/Security/Authentication/Msv1_0_InteractivePackage.cs
index 1cd2595cb..ae0e2e3f6 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/Authentication/Msv1_0_InteractivePackage.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/Authentication/Msv1_0_InteractivePackage.cs
@@ -20,6 +20,9 @@
* along with Process Hacker. If not, see .
*/
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Security.Authentication
@@ -77,24 +80,27 @@ public string Password
public MemoryRegion GetAuthData()
{
- string lDomainName = !string.IsNullOrEmpty(_domainName) ? _domainName : string.Empty;
- string lUserName = !string.IsNullOrEmpty(_userName) ? _userName : string.Empty;
- string lPassword = !string.IsNullOrEmpty(_password) ? _password : string.Empty;
+ MemoryAlloc data;
+ int dataSize;
+ int domainNameOffset;
+ int userNameOffset;
+ int passwordOffset;
+ string lDomainName = _domainName != null ? _domainName : "";
+ string lUserName = _userName != null ? _userName : "";
+ string lPassword = _password != null ? _password : "";
// The structure plus the strings must be stored in the same buffer,
// so we have to do some computation.
- int domainNameOffset = Msv1_0_InteractiveLogon.SizeOf;
- int userNameOffset = domainNameOffset + lDomainName.Length * 2;
- int passwordOffset = userNameOffset + lUserName.Length * 2;
- int dataSize = passwordOffset + lPassword.Length * 2;
+ domainNameOffset = Marshal.SizeOf(typeof(Msv1_0_InteractiveLogon));
+ userNameOffset = domainNameOffset + lDomainName.Length * 2;
+ passwordOffset = userNameOffset + lUserName.Length * 2;
+ dataSize = passwordOffset + lPassword.Length * 2;
+ data = new MemoryAlloc(dataSize);
- MemoryAlloc data = new MemoryAlloc(dataSize);
+ Msv1_0_InteractiveLogon info = new Msv1_0_InteractiveLogon();
- Msv1_0_InteractiveLogon info = new Msv1_0_InteractiveLogon
- {
- MessageType = Msv1_0_LogonSubmitType.Interactive
- };
+ info.MessageType = Msv1_0_LogonSubmitType.Interactive;
info.LogonDomainName.MaximumLength = info.LogonDomainName.Length = (ushort)(lDomainName.Length * 2);
info.LogonDomainName.Buffer = data.Memory.Increment(domainNameOffset);
@@ -108,7 +114,7 @@ public MemoryRegion GetAuthData()
info.Password.Buffer = data.Memory.Increment(passwordOffset);
data.WriteUnicodeString(passwordOffset, lPassword);
- data.WriteStruct(info);
+ data.WriteStruct(info);
return data;
}
@@ -130,9 +136,9 @@ public void ReadAuthData(MemoryRegion buffer)
if (info.Password.Buffer.CompareTo(buffer.Size) < 0)
info.Password.Buffer = info.Password.Buffer.Increment(buffer);
- _domainName = info.LogonDomainName.Text;
- _userName = info.UserName.Text;
- _password = info.Password.Text;
+ _domainName = info.LogonDomainName.Read();
+ _userName = info.UserName.Read();
+ _password = info.Password.Read();
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/Security/DesktopAccess.cs b/1.x/trunk/ProcessHacker.Native/Security/DesktopAccess.cs
index 09c6e1eb5..e6268edbc 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/DesktopAccess.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/DesktopAccess.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Native.Security
{
diff --git a/1.x/trunk/ProcessHacker.Native/Security/EnlistmentAccess.cs b/1.x/trunk/ProcessHacker.Native/Security/EnlistmentAccess.cs
index d3d12c451..061fd1f79 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/EnlistmentAccess.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/EnlistmentAccess.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Native.Security
{
diff --git a/1.x/trunk/ProcessHacker.Native/Security/ISecurable.cs b/1.x/trunk/ProcessHacker.Native/Security/ISecurable.cs
index 552104ede..1c28e4ad1 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/ISecurable.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/ISecurable.cs
@@ -1,4 +1,7 @@
-using ProcessHacker.Native.Api;
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ProcessHacker.Native.Api;
using ProcessHacker.Native.Security.AccessControl;
namespace ProcessHacker.Native.Security
diff --git a/1.x/trunk/ProcessHacker.Native/Security/IoCompletionAccess.cs b/1.x/trunk/ProcessHacker.Native/Security/IoCompletionAccess.cs
index ba9646428..dc10c1ee0 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/IoCompletionAccess.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/IoCompletionAccess.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Native.Security
{
diff --git a/1.x/trunk/ProcessHacker.Native/Security/Privilege.cs b/1.x/trunk/ProcessHacker.Native/Security/Privilege.cs
index c3fc71857..3b15299b3 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/Privilege.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/Privilege.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Text;
using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
@@ -44,8 +45,8 @@ public static Privilege Enable(string name)
}
}
- private readonly TokenHandle _tokenHandle;
- private readonly Luid _luid;
+ private TokenHandle _tokenHandle;
+ private Luid _luid;
private SePrivilegeAttributes _attributes;
private string _name;
private string _displayName;
@@ -121,7 +122,8 @@ public bool Disabled
{
get
{
- return (_attributes & SePrivilegeAttributes.Disabled)!= SePrivilegeAttributes.Disabled;
+ return (_attributes & SePrivilegeAttributes.Disabled)
+ != SePrivilegeAttributes.Disabled;
}
set
{
@@ -133,7 +135,7 @@ public string DisplayName
{
get
{
- if (string.IsNullOrEmpty(_displayName))
+ if (_displayName == null)
{
_displayName = LsaPolicyHandle.LookupPolicyHandle.LookupPrivilegeDisplayName(this.Name);
}
@@ -177,7 +179,7 @@ public string Name
{
get
{
- if (string.IsNullOrEmpty(_name))
+ if (_name == null)
{
_name = LsaPolicyHandle.LookupPolicyHandle.LookupPrivilegeName(_luid);
}
@@ -262,7 +264,7 @@ private void SetState(TokenHandle tokenHandle, SePrivilegeAttributes attributes)
public LuidAndAttributes ToLuidAndAttributes()
{
- return new LuidAndAttributes
+ return new LuidAndAttributes()
{
Attributes = _attributes,
Luid = _luid
diff --git a/1.x/trunk/ProcessHacker.Native/Security/PrivilegeSet.cs b/1.x/trunk/ProcessHacker.Native/Security/PrivilegeSet.cs
index f32ed2ae0..01c18e857 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/PrivilegeSet.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/PrivilegeSet.cs
@@ -22,14 +22,16 @@
using System;
using System.Collections.Generic;
-
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.Security
{
public sealed class PrivilegeSet : IList
{
- private readonly List _privileges;
+ private static int _sizeOfLaa = Marshal.SizeOf(typeof(LuidAndAttributes));
+
+ private List _privileges;
private PrivilegeSetFlags _flags;
public PrivilegeSet()
@@ -61,7 +63,7 @@ public PrivilegeSet(IntPtr memory)
for (int i = 0; i < privilegeSet.Count; i++)
{
- _privileges.Add(new Privilege(memoryRegion.ReadStruct(PrivilegeSetStruct.PrivilegesOffset, LuidAndAttributes.SizeOf, i)));
+ _privileges.Add(new Privilege(memoryRegion.ReadStruct(PrivilegeSetStruct.PrivilegesOffset, i)));
}
}
@@ -73,24 +75,25 @@ public PrivilegeSetFlags Flags
public MemoryAlloc ToMemory()
{
- int requiredSize = 8 + LuidAndAttributes.SizeOf * _privileges.Count;
+ int requiredSize = 8 + _sizeOfLaa * _privileges.Count;
MemoryAlloc memory = new MemoryAlloc(requiredSize);
memory.WriteInt32(0, _privileges.Count);
memory.WriteInt32(4, (int)_flags);
for (int i = 0; i < _privileges.Count; i++)
- memory.WriteStruct(8, LuidAndAttributes.SizeOf, i, _privileges[i].ToLuidAndAttributes());
+ memory.WriteStruct(8, i, _privileges[i].ToLuidAndAttributes());
return memory;
}
public TokenPrivileges ToTokenPrivileges()
{
- return new TokenPrivileges
+ return new TokenPrivileges()
{
PrivilegeCount = _privileges.Count,
- Privileges = _privileges.ConvertAll(privilege => privilege.ToLuidAndAttributes()).ToArray()
+ Privileges = _privileges.ConvertAll(
+ (privilege) => privilege.ToLuidAndAttributes()).ToArray()
};
}
diff --git a/1.x/trunk/ProcessHacker.Native/Security/Sid.cs b/1.x/trunk/ProcessHacker.Native/Security/Sid.cs
index 76dfe500f..b3fdc29a3 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/Sid.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/Sid.cs
@@ -21,6 +21,7 @@
*/
using System;
+using System.Text;
using ProcessHacker.Common;
using ProcessHacker.Common.Objects;
using ProcessHacker.Native.Api;
@@ -51,7 +52,7 @@ public static Sid CurrentUser
if (currentUser == null)
{
using (var thandle = TokenHandle.OpenCurrentPrimary(TokenAccess.Query))
- _currentUser = currentUser = thandle.User;
+ _currentUser = currentUser = thandle.GetUser();
}
return currentUser;
@@ -119,8 +120,8 @@ private static byte[] GetWellKnownSidIdentifierAuthority(WellKnownSidIdentifierA
if (copy)
return array.Duplicate();
-
- return array;
+ else
+ return array;
}
public static implicit operator IntPtr(Sid sid)
@@ -128,10 +129,10 @@ public static implicit operator IntPtr(Sid sid)
return sid.Memory;
}
- private readonly MemoryRegion _memory;
- private readonly string _systemName;
- private readonly bool _hasAttributes;
- private readonly SidAttributes _attributes;
+ private MemoryRegion _memory;
+ private string _systemName;
+ private bool _hasAttributes;
+ private SidAttributes _attributes;
private string _stringSid;
private string _domain;
@@ -214,9 +215,12 @@ public Sid(IntPtr sid, SidAttributes attributes, string systemName)
private Sid(IntPtr sid, bool hasAttributes, SidAttributes attributes, string systemName)
{
+ NtStatus status;
+
_memory = new MemoryAlloc(Win32.RtlLengthSid(sid));
- Win32.RtlCopySid(_memory.Size, _memory, sid).ThrowIf();
+ if ((status = Win32.RtlCopySid(_memory.Size, _memory, sid)) >= NtStatus.Error)
+ Win32.Throw(status);
_hasAttributes = hasAttributes;
_attributes = attributes;
@@ -243,9 +247,15 @@ public string DomainName
}
}
- public unsafe byte[] IdentifierAuthority
+ public byte[] IdentifierAuthority
{
- get { return Utils.Create((*Win32.RtlIdentifierAuthoritySid(this)).Value, 6); }
+ get
+ {
+ unsafe
+ {
+ return Utils.Create((*Win32.RtlIdentifierAuthoritySid(this)).Value, 6);
+ }
+ }
}
public bool HasAttributes
@@ -267,9 +277,8 @@ public string Name
{
get
{
- if (string.IsNullOrEmpty(_name))
+ if (_name == null)
this.GetNameAndUse(out _domain, out _name, out _nameUse);
-
return _name;
}
}
@@ -280,22 +289,24 @@ public SidNameUse NameUse
{
if (_nameUse == 0)
this.GetNameAndUse(out _domain, out _name, out _nameUse);
-
return _nameUse;
}
}
- public unsafe int[] SubAuthorities
+ public int[] SubAuthorities
{
get
{
- byte count = *Win32.RtlSubAuthorityCountSid(this);
- int[] subAuthorities = new int[count];
+ unsafe
+ {
+ byte count = *Win32.RtlSubAuthorityCountSid(this);
+ int[] subAuthorities = new int[count];
- for (int i = 0; i < count; i++)
- subAuthorities[i] = *Win32.RtlSubAuthoritySid(this, i);
+ for (int i = 0; i < count; i++)
+ subAuthorities[i] = *Win32.RtlSubAuthoritySid(this, i);
- return subAuthorities;
+ return subAuthorities;
+ }
}
}
@@ -303,9 +314,8 @@ public string StringSid
{
get
{
- if (string.IsNullOrEmpty(_stringSid))
- _stringSid = this.String;
-
+ if (_stringSid == null)
+ _stringSid = this.GetString();
return _stringSid;
}
}
@@ -344,8 +354,8 @@ public string GetFullName(bool includeDomain)
if (includeDomain && !string.IsNullOrEmpty(this.DomainName))
return this.DomainName + "\\" + this.Name;
-
- return this.Name;
+ else
+ return this.Name;
}
catch
{
@@ -359,7 +369,7 @@ public override int GetHashCode()
byte[] identifierAuthority = this.IdentifierAuthority;
int[] subAuthorities = this.SubAuthorities;
- foreach (int t in subAuthorities)
+ for (int i = 0; i < subAuthorities.Length; i++)
{
hashCode ^= identifierAuthority[(uint)hashCode % identifierAuthority.Length];
// Reverse and XOR.
@@ -379,7 +389,8 @@ public WellKnownSidIdentifierAuthority GetWellKnownIdentifierAuthority()
{
byte[] identifierAuthority = this.IdentifierAuthority;
- foreach (WellKnownSidIdentifierAuthority value in Enum.GetValues(typeof(WellKnownSidIdentifierAuthority)))
+ foreach (WellKnownSidIdentifierAuthority value in
+ Enum.GetValues(typeof(WellKnownSidIdentifierAuthority)))
{
if (value == WellKnownSidIdentifierAuthority.None)
continue;
@@ -391,19 +402,16 @@ public WellKnownSidIdentifierAuthority GetWellKnownIdentifierAuthority()
return WellKnownSidIdentifierAuthority.None;
}
- private string String
+ private string GetString()
{
- get
- {
- UnicodeString str = new UnicodeString();
+ NtStatus status;
+ UnicodeString str = new UnicodeString();
- Win32.RtlConvertSidToUnicodeString(ref str, this, true).ThrowIf();
+ if ((status = Win32.RtlConvertSidToUnicodeString(ref str, this, true)) >= NtStatus.Error)
+ Win32.Throw(status);
- using (str)
- {
- return str.Text;
- }
- }
+ using (str)
+ return str.Read();
}
public bool IsValid()
@@ -418,7 +426,7 @@ public bool PrefixEquals(Sid obj)
public SidAndAttributes ToSidAndAttributes()
{
- return new SidAndAttributes
+ return new SidAndAttributes()
{
Attributes = _attributes,
Sid = this
diff --git a/1.x/trunk/ProcessHacker.Native/Security/TransactionAccess.cs b/1.x/trunk/ProcessHacker.Native/Security/TransactionAccess.cs
index bcf99cbff..870a38b8c 100644
--- a/1.x/trunk/ProcessHacker.Native/Security/TransactionAccess.cs
+++ b/1.x/trunk/ProcessHacker.Native/Security/TransactionAccess.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Text;
namespace ProcessHacker.Native.Security
{
diff --git a/1.x/trunk/ProcessHacker.Native/SsLogging/FilterType.cs b/1.x/trunk/ProcessHacker.Native/SsLogging/FilterType.cs
index 17a32f6e0..111c53720 100644
--- a/1.x/trunk/ProcessHacker.Native/SsLogging/FilterType.cs
+++ b/1.x/trunk/ProcessHacker.Native/SsLogging/FilterType.cs
@@ -1,4 +1,8 @@
-namespace ProcessHacker.Native.SsLogging
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ProcessHacker.Native.SsLogging
{
public enum FilterType
{
@@ -12,8 +16,8 @@ public static KphSsFilterType ToKphSs(this FilterType filterType)
{
if (filterType == FilterType.Include)
return KphSsFilterType.Include;
-
- return KphSsFilterType.Exclude;
+ else
+ return KphSsFilterType.Exclude;
}
}
}
diff --git a/1.x/trunk/ProcessHacker.Native/SsLogging/KphTypes.cs b/1.x/trunk/ProcessHacker.Native/SsLogging/KphTypes.cs
index 1e8b40d90..00b066e84 100644
--- a/1.x/trunk/ProcessHacker.Native/SsLogging/KphTypes.cs
+++ b/1.x/trunk/ProcessHacker.Native/SsLogging/KphTypes.cs
@@ -58,17 +58,24 @@ public enum KphSsRuleSetAction : int
Log
}
+ public class KphSsClientEntryHandle : KphHandle
+ {
+ internal KphSsClientEntryHandle(IntPtr handle)
+ : base(handle)
+ { }
+ }
+
+ public class KphSsRuleSetEntryHandle : KphHandle
+ {
+ internal KphSsRuleSetEntryHandle(IntPtr handle)
+ : base(handle)
+ { }
+ }
+
[StructLayout(LayoutKind.Sequential)]
public struct KphSsArgumentBlock
{
- public static readonly int SizeOf;
- public static readonly int DataOffset;
-
- static KphSsArgumentBlock()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsArgumentBlock));
- DataOffset = Marshal.OffsetOf(typeof(KphSsArgumentBlock), "Data").ToInt32();
- }
+ public static readonly int DataOffset = Marshal.OffsetOf(typeof(KphSsArgumentBlock), "Data").ToInt32();
[StructLayout(LayoutKind.Explicit)]
public struct KphSsArgumentUnion
@@ -94,41 +101,22 @@ public struct KphSsArgumentUnion
[StructLayout(LayoutKind.Sequential)]
public struct KphSsBlockHeader
{
- public static readonly int SizeOf;
-
public ushort Size;
public KphSsBlockType Type;
-
- static KphSsBlockHeader()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsBlockHeader));
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct KphSsBytes
{
- public static readonly int BufferOffset;
+ public static readonly int BufferOffset = Marshal.OffsetOf(typeof(KphSsBytes), "Buffer").ToInt32();
public ushort Length;
public byte Buffer;
-
- static KphSsBytes()
- {
- BufferOffset = Marshal.OffsetOf(typeof(KphSsBytes), "Buffer").ToInt32();
- }
}
[StructLayout(LayoutKind.Sequential)]
public struct KphSsClientInformation
{
- public static readonly int SizeOf;
-
- static KphSsClientInformation()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsClientInformation));
- }
-
public IntPtr ProcessId;
public IntPtr BufferBase;
public int BufferSize;
@@ -139,13 +127,6 @@ static KphSsClientInformation()
[StructLayout(LayoutKind.Sequential)]
public struct KphSsEventBlock
{
- public static readonly int SizeOf;
-
- static KphSsEventBlock()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsEventBlock));
- }
-
public KphSsBlockHeader Header;
public KphSsEventFlags Flags;
public long Time;
@@ -161,14 +142,7 @@ static KphSsEventBlock()
[StructLayout(LayoutKind.Sequential)]
public struct KphSsHandle
- {
- public static readonly int SizeOf;
-
- static KphSsHandle()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsHandle));
- }
-
+ {
public ClientId ClientId;
public ushort TypeNameOffset;
public ushort NameOffset;
@@ -177,13 +151,6 @@ static KphSsHandle()
[StructLayout(LayoutKind.Sequential)]
public struct KphSsObjectAttributes
{
- public static readonly int SizeOf;
-
- static KphSsObjectAttributes()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsObjectAttributes));
- }
-
public ObjectAttributes ObjectAttributes;
public ushort RootDirectoryOffset;
public ushort ObjectNameOffset;
@@ -192,14 +159,7 @@ static KphSsObjectAttributes()
[StructLayout(LayoutKind.Sequential)]
public struct KphSsUnicodeString
{
- public static readonly int SizeOf;
- public static readonly int BufferOffset;
-
- static KphSsUnicodeString()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsUnicodeString));
- BufferOffset = Marshal.OffsetOf(typeof(KphSsUnicodeString), "Buffer").ToInt32();
- }
+ public static readonly int BufferOffset = Marshal.OffsetOf(typeof(KphSsUnicodeString), "Buffer").ToInt32();
public ushort Length;
public ushort MaximumLength;
@@ -210,14 +170,7 @@ static KphSsUnicodeString()
[StructLayout(LayoutKind.Sequential)]
public struct KphSsWString
{
- public static readonly int SizeOf;
- public static readonly int BufferOffset;
-
- static KphSsWString()
- {
- SizeOf = Marshal.SizeOf(typeof(KphSsWString));
- BufferOffset = Marshal.OffsetOf(typeof(KphSsWString), "Buffer").ToInt32();
- }
+ public static readonly int BufferOffset = Marshal.OffsetOf(typeof(KphSsWString), "Buffer").ToInt32();
public ushort Length;
public byte Buffer;
diff --git a/1.x/trunk/ProcessHacker.Native/SsLogging/SsClientId.cs b/1.x/trunk/ProcessHacker.Native/SsLogging/SsClientId.cs
index 323d075f3..7563d7766 100644
--- a/1.x/trunk/ProcessHacker.Native/SsLogging/SsClientId.cs
+++ b/1.x/trunk/ProcessHacker.Native/SsLogging/SsClientId.cs
@@ -1,4 +1,7 @@
-using ProcessHacker.Native.Api;
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.SsLogging
{
@@ -6,7 +9,7 @@ public class SsClientId : SsData
{
public SsClientId(MemoryRegion data)
{
- this.Original = data.ReadStruct(0, ClientId.SizeOf, 0);
+ this.Original = data.ReadStruct();
}
public ClientId Original
diff --git a/1.x/trunk/ProcessHacker.Native/SsLogging/SsHandle.cs b/1.x/trunk/ProcessHacker.Native/SsLogging/SsHandle.cs
index e3f67af7f..d964e09e4 100644
--- a/1.x/trunk/ProcessHacker.Native/SsLogging/SsHandle.cs
+++ b/1.x/trunk/ProcessHacker.Native/SsLogging/SsHandle.cs
@@ -1,10 +1,14 @@
-namespace ProcessHacker.Native.SsLogging
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ProcessHacker.Native.SsLogging
{
public sealed class SsHandle : SsData
{
internal SsHandle(MemoryRegion data)
{
- KphSsHandle handleInfo = data.ReadStruct(0, KphSsHandle.SizeOf, 0);
+ KphSsHandle handleInfo = data.ReadStruct();
if (handleInfo.TypeNameOffset != 0)
{
diff --git a/1.x/trunk/ProcessHacker.Native/SsLogging/SsLogger.cs b/1.x/trunk/ProcessHacker.Native/SsLogging/SsLogger.cs
index 455a57e05..01f606245 100644
--- a/1.x/trunk/ProcessHacker.Native/SsLogging/SsLogger.cs
+++ b/1.x/trunk/ProcessHacker.Native/SsLogging/SsLogger.cs
@@ -1,4 +1,5 @@
using System;
+using System.Runtime.InteropServices;
using System.Threading;
using ProcessHacker.Common;
using ProcessHacker.Native.Api;
@@ -19,7 +20,7 @@ public sealed class SsLogger
public static SsData ReadArgumentBlock(MemoryRegion data)
{
- KphSsArgumentBlock argBlock = data.ReadStruct(0, KphSsArgumentBlock.SizeOf, 0);
+ var argBlock = data.ReadStruct();
MemoryRegion dataRegion;
SsData ssArg = null;
@@ -31,45 +32,37 @@ public static SsData ReadArgumentBlock(MemoryRegion data)
{
case KphSsArgumentType.Int8:
{
- SsSimple simpleArg = new SsSimple
- {
- Argument = argBlock.Data.Int8,
- Type = typeof(Byte)
- };
+ SsSimple simpleArg = new SsSimple();
+ simpleArg.Argument = argBlock.Data.Int8;
+ simpleArg.Type = typeof(Byte);
ssArg = simpleArg;
}
break;
case KphSsArgumentType.Int16:
{
- SsSimple simpleArg = new SsSimple
- {
- Argument = argBlock.Data.Int16,
- Type = typeof(Int16)
- };
+ SsSimple simpleArg = new SsSimple();
+ simpleArg.Argument = argBlock.Data.Int16;
+ simpleArg.Type = typeof(Int16);
ssArg = simpleArg;
}
break;
case KphSsArgumentType.Int32:
{
- SsSimple simpleArg = new SsSimple
- {
- Argument = argBlock.Data.Int32,
- Type = typeof(Int32)
- };
+ SsSimple simpleArg = new SsSimple();
+ simpleArg.Argument = argBlock.Data.Int32;
+ simpleArg.Type = typeof(Int32);
ssArg = simpleArg;
}
break;
case KphSsArgumentType.Int64:
{
- SsSimple simpleArg = new SsSimple
- {
- Argument = argBlock.Data.Int64,
- Type = typeof(Int64)
- };
+ SsSimple simpleArg = new SsSimple();
+ simpleArg.Argument = argBlock.Data.Int64;
+ simpleArg.Type = typeof(Int64);
ssArg = simpleArg;
}
break;
@@ -107,12 +100,15 @@ public static SsData ReadArgumentBlock(MemoryRegion data)
public static SsEvent ReadEventBlock(MemoryRegion data)
{
- KphSsEventBlock eventBlock = data.ReadStruct(0, KphSsEventBlock.SizeOf, 0);
+ var eventBlock = data.ReadStruct();
+
+ int[] arguments;
+ IntPtr[] stackTrace;
// Reconstruct the argument and stack trace arrays.
- int[] arguments = new int[eventBlock.NumberOfArguments];
- IntPtr[] stackTrace = new IntPtr[eventBlock.TraceCount];
+ arguments = new int[eventBlock.NumberOfArguments];
+ stackTrace = new IntPtr[eventBlock.TraceCount];
for (int i = 0; i < arguments.Length; i++)
arguments[i] = data.ReadInt32(eventBlock.ArgumentsOffset, i);
@@ -120,20 +116,22 @@ public static SsEvent ReadEventBlock(MemoryRegion data)
stackTrace[i] = data.ReadIntPtr(eventBlock.TraceOffset, i);
// Create an event object.
- SsEvent ssEvent = new SsEvent
- {
- // Basic information
- Time = DateTime.FromFileTime(eventBlock.Time),
- ThreadId = eventBlock.ClientId.ThreadId,
- ProcessId = eventBlock.ClientId.ProcessId,
- Arguments = arguments,
- StackTrace = stackTrace, ArgumentsCopyFailed =
- eventBlock.Flags.HasFlag(KphSsEventFlags.CopyArgumentsFailed),
- ArgumentsProbeFailed = eventBlock.Flags.HasFlag(KphSsEventFlags.ProbeArgumentsFailed),
- CallNumber = eventBlock.Number
- };
+ SsEvent ssEvent = new SsEvent();
+
+ // Basic information
+ ssEvent.Time = DateTime.FromFileTime(eventBlock.Time);
+ ssEvent.ThreadId = eventBlock.ClientId.ThreadId;
+ ssEvent.ProcessId = eventBlock.ClientId.ProcessId;
+ ssEvent.Arguments = arguments;
+ ssEvent.StackTrace = stackTrace;
// Flags
+ ssEvent.ArgumentsCopyFailed =
+ (eventBlock.Flags & KphSsEventFlags.CopyArgumentsFailed) == KphSsEventFlags.CopyArgumentsFailed;
+ ssEvent.ArgumentsProbeFailed =
+ (eventBlock.Flags & KphSsEventFlags.ProbeArgumentsFailed) == KphSsEventFlags.ProbeArgumentsFailed;
+ ssEvent.CallNumber = eventBlock.Number;
+
if ((eventBlock.Flags & KphSsEventFlags.UserMode) == KphSsEventFlags.UserMode)
ssEvent.Mode = KProcessorMode.UserMode;
else
@@ -144,7 +142,7 @@ public static SsEvent ReadEventBlock(MemoryRegion data)
public static string ReadWString(MemoryRegion data)
{
- KphSsWString wString = data.ReadStruct(0, KphSsWString.SizeOf, 0);
+ KphSsWString wString = data.ReadStruct();
return data.ReadUnicodeString(KphSsWString.BufferOffset, wString.Length / 2);
}
@@ -154,18 +152,20 @@ public static string ReadWString(MemoryRegion data)
public event RawArgumentBlockReceivedDelegate RawArgumentBlockReceived;
public event RawEventBlockReceivedDelegate RawEventBlockReceived;
- private bool _started;
- private readonly object _startLock = new object();
+ private bool _started = false;
+ private object _startLock = new object();
- private bool _terminating;
+ private bool _terminating = false;
private Thread _bufferWorkerThread;
private ThreadHandle _bufferWorkerThreadHandle;
- private readonly Event _bufferWorkerThreadReadyEvent = new Event(true, false);
+ private Event _bufferWorkerThreadReadyEvent = new Event(true, false);
- private readonly VirtualMemoryAlloc _buffer;
- private readonly SemaphoreHandle _readSemaphore;
- private readonly SemaphoreHandle _writeSemaphore;
- private int _cursor;
+ private VirtualMemoryAlloc _buffer;
+ private SemaphoreHandle _readSemaphore;
+ private SemaphoreHandle _writeSemaphore;
+ private int _cursor = 0;
+ private KphSsClientEntryHandle _clientEntryHandle;
+ private KphSsRuleSetEntryHandle _ruleSetEntryHandle;
public SsLogger(int bufferedBlockCount, bool includeAll)
{
@@ -180,57 +180,57 @@ public SsLogger(int bufferedBlockCount, bool includeAll)
_writeSemaphore = SemaphoreHandle.Create(SemaphoreAccess.All, bufferedBlockCount, bufferedBlockCount);
// Create the client entry.
- //_clientEntryHandle = KProcessHacker.Instance.SsCreateClientEntry(
- // ProcessHandle.Current,
- // _readSemaphore,
- // _writeSemaphore,
- // _buffer,
- // _buffer.Size
- // );
+ _clientEntryHandle = KProcessHacker.Instance.SsCreateClientEntry(
+ ProcessHandle.Current,
+ _readSemaphore,
+ _writeSemaphore,
+ _buffer,
+ _buffer.Size
+ );
// Create the ruleset entry.
- //_ruleSetEntryHandle = KProcessHacker.Instance.SsCreateRuleSetEntry(
- // _clientEntryHandle,
- // includeAll ? KphSsFilterType.Include : KphSsFilterType.Exclude,
- // KphSsRuleSetAction.Log
- // );
+ _ruleSetEntryHandle = KProcessHacker.Instance.SsCreateRuleSetEntry(
+ _clientEntryHandle,
+ includeAll ? KphSsFilterType.Include : KphSsFilterType.Exclude,
+ KphSsRuleSetAction.Log
+ );
+ }
+
+ public IntPtr AddNumberRule(FilterType filterType, int number)
+ {
+ return KProcessHacker.Instance.SsAddNumberRule(
+ _ruleSetEntryHandle,
+ filterType.ToKphSs(),
+ number
+ );
+ }
+
+ public IntPtr AddPreviousModeRule(FilterType filterType, KProcessorMode previousMode)
+ {
+ return KProcessHacker.Instance.SsAddPreviousModeRule(
+ _ruleSetEntryHandle,
+ filterType.ToKphSs(),
+ previousMode
+ );
}
- //public IntPtr AddNumberRule(FilterType filterType, int number)
- //{
- // return KProcessHacker.Instance.SsAddNumberRule(
- // _ruleSetEntryHandle,
- // filterType.ToKphSs(),
- // number
- // );
- //}
-
- //public IntPtr AddPreviousModeRule(FilterType filterType, KProcessorMode previousMode)
- //{
- // return KProcessHacker.Instance.SsAddPreviousModeRule(
- // _ruleSetEntryHandle,
- // filterType.ToKphSs(),
- // previousMode
- // );
- //}
-
- //public IntPtr AddProcessIdRule(FilterType filterType, int pid)
- //{
- // return KProcessHacker.Instance.SsAddProcessIdRule(
- // _ruleSetEntryHandle,
- // filterType.ToKphSs(),
- // pid.ToIntPtr()
- // );
- //}
-
- //public IntPtr AddThreadIdRule(FilterType filterType, int tid)
- //{
- // return KProcessHacker.Instance.SsAddProcessIdRule(
- // _ruleSetEntryHandle,
- // filterType.ToKphSs(),
- // tid.ToIntPtr()
- // );
- //}
+ public IntPtr AddProcessIdRule(FilterType filterType, int pid)
+ {
+ return KProcessHacker.Instance.SsAddProcessIdRule(
+ _ruleSetEntryHandle,
+ filterType.ToKphSs(),
+ pid.ToIntPtr()
+ );
+ }
+
+ public IntPtr AddThreadIdRule(FilterType filterType, int tid)
+ {
+ return KProcessHacker.Instance.SsAddProcessIdRule(
+ _ruleSetEntryHandle,
+ filterType.ToKphSs(),
+ tid.ToIntPtr()
+ );
+ }
private void BufferWorkerThreadStart()
{
@@ -255,34 +255,37 @@ private void BufferWorkerThreadStart()
return;
// Check if we have an implicit cursor reset.
- if (_buffer.Size - _cursor < KphSsBlockHeader.SizeOf)
+ if (_buffer.Size - _cursor < Marshal.SizeOf(typeof(KphSsBlockHeader)))
_cursor = 0;
// Read the block header.
- blockHeader = _buffer.ReadStruct(_cursor, KphSsBlockHeader.SizeOf, 0);
+ blockHeader = _buffer.ReadStruct(_cursor, 0);
// Check if we have an explicit cursor reset.
if (blockHeader.Type == KphSsBlockType.Reset)
{
_cursor = 0;
- blockHeader = _buffer.ReadStruct(_cursor, KphSsBlockHeader.SizeOf, 0);
+ blockHeader = _buffer.ReadStruct(_cursor, 0);
}
// Process the block.
- switch (blockHeader.Type)
+ if (blockHeader.Type == KphSsBlockType.Event)
{
- case KphSsBlockType.Event:
- if (this.EventBlockReceived != null)
- this.EventBlockReceived(ReadEventBlock(new MemoryRegion(this._buffer, this._cursor)));
- if (this.RawEventBlockReceived != null)
- this.RawEventBlockReceived(new MemoryRegion(this._buffer, this._cursor));
- break;
- case KphSsBlockType.Argument:
- if (this.ArgumentBlockReceived != null)
- this.ArgumentBlockReceived(ReadArgumentBlock(new MemoryRegion(this._buffer, this._cursor)));
- if (this.RawArgumentBlockReceived != null)
- this.RawArgumentBlockReceived(new MemoryRegion(this._buffer, this._cursor));
- break;
+ // Raise the events.
+
+ if (this.EventBlockReceived != null)
+ this.EventBlockReceived(ReadEventBlock(new MemoryRegion(_buffer, _cursor)));
+ if (this.RawEventBlockReceived != null)
+ this.RawEventBlockReceived(new MemoryRegion(_buffer, _cursor));
+ }
+ else if (blockHeader.Type == KphSsBlockType.Argument)
+ {
+ // Raise the events.
+
+ if (this.ArgumentBlockReceived != null)
+ this.ArgumentBlockReceived(ReadArgumentBlock(new MemoryRegion(_buffer, _cursor)));
+ if (this.RawArgumentBlockReceived != null)
+ this.RawArgumentBlockReceived(new MemoryRegion(_buffer, _cursor));
}
// Advance the cursor.
@@ -294,24 +297,23 @@ private void BufferWorkerThreadStart()
public void GetStatistics(out int blocksWritten, out int blocksDropped)
{
- //KphSsClientInformation info;
- //KProcessHacker.Instance.SsQueryClientEntry(
- // _clientEntryHandle,
- // out info,
- // KphSsClientInformation.SizeOf,
- // out retLength
- // );
-
- //blocksWritten = info.NumberOfBlocksWritten;
- //blocksDropped = info.NumberOfBlocksDropped;
-
- blocksWritten = 0;
- blocksDropped = 0;
+ KphSsClientInformation info;
+ int retLength;
+
+ KProcessHacker.Instance.SsQueryClientEntry(
+ _clientEntryHandle,
+ out info,
+ Marshal.SizeOf(typeof(KphSsClientInformation)),
+ out retLength
+ );
+
+ blocksWritten = info.NumberOfBlocksWritten;
+ blocksDropped = info.NumberOfBlocksDropped;
}
public void RemoveRule(IntPtr handle)
{
- //KProcessHacker.Instance.SsRemoveRule(_ruleSetEntryHandle, handle);
+ KProcessHacker.Instance.SsRemoveRule(_ruleSetEntryHandle, handle);
}
public void Start()
@@ -320,17 +322,15 @@ public void Start()
{
if (!_started)
{
- //KProcessHacker.Instance.SsRef();
- //KProcessHacker.Instance.SsEnableClientEntry(_clientEntryHandle, true);
+ KProcessHacker.Instance.SsRef();
+ KProcessHacker.Instance.SsEnableClientEntry(_clientEntryHandle, true);
_started = true;
_terminating = false;
// Create the buffer worker thread.
- _bufferWorkerThread = new Thread(this.BufferWorkerThreadStart, Utils.SixteenthStackSize)
- {
- IsBackground = true
- };
+ _bufferWorkerThread = new Thread(this.BufferWorkerThreadStart, Utils.SixteenthStackSize);
+ _bufferWorkerThread.IsBackground = true;
_bufferWorkerThread.Start();
// Wait for the thread to initialize.
_bufferWorkerThreadReadyEvent.Wait();
@@ -344,8 +344,8 @@ public void Stop()
{
if (_started)
{
- //KProcessHacker.Instance.SsEnableClientEntry(_clientEntryHandle, false);
- //KProcessHacker.Instance.SsUnref();
+ KProcessHacker.Instance.SsEnableClientEntry(_clientEntryHandle, false);
+ KProcessHacker.Instance.SsUnref();
_started = false;
// Tell the worker thread to stop.
diff --git a/1.x/trunk/ProcessHacker.Native/SsLogging/SsObjectAttributes.cs b/1.x/trunk/ProcessHacker.Native/SsLogging/SsObjectAttributes.cs
index 6ba92e00b..82e4cc591 100644
--- a/1.x/trunk/ProcessHacker.Native/SsLogging/SsObjectAttributes.cs
+++ b/1.x/trunk/ProcessHacker.Native/SsLogging/SsObjectAttributes.cs
@@ -1,4 +1,7 @@
-using ProcessHacker.Native.Api;
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.SsLogging
{
@@ -6,7 +9,7 @@ public class SsObjectAttributes : SsData
{
internal SsObjectAttributes(MemoryRegion data)
{
- KphSsObjectAttributes oaInfo = data.ReadStruct(0, KphSsObjectAttributes.SizeOf, 0);
+ KphSsObjectAttributes oaInfo = data.ReadStruct();
if (oaInfo.ObjectNameOffset != 0)
this.ObjectName = new SsUnicodeString(new MemoryRegion(data, oaInfo.ObjectNameOffset));
diff --git a/1.x/trunk/ProcessHacker.Native/SsLogging/SsUnicodeString.cs b/1.x/trunk/ProcessHacker.Native/SsLogging/SsUnicodeString.cs
index 7a59c87dd..a224af7d4 100644
--- a/1.x/trunk/ProcessHacker.Native/SsLogging/SsUnicodeString.cs
+++ b/1.x/trunk/ProcessHacker.Native/SsLogging/SsUnicodeString.cs
@@ -1,4 +1,7 @@
-using ProcessHacker.Native.Api;
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ProcessHacker.Native.Api;
namespace ProcessHacker.Native.SsLogging
{
@@ -8,13 +11,12 @@ internal SsUnicodeString(MemoryRegion data)
{
KphSsUnicodeString unicodeStringInfo = data.ReadStruct();
- this.Original = new UnicodeString
+ this.Original = new UnicodeString()
{
Length = unicodeStringInfo.Length,
MaximumLength = unicodeStringInfo.MaximumLength,
Buffer = unicodeStringInfo.Pointer
};
-
this.String = data.ReadUnicodeString(
KphSsUnicodeString.BufferOffset,
unicodeStringInfo.Length / 2
diff --git a/1.x/trunk/ProcessHacker.Native/Symbols/SymbolProvider.cs b/1.x/trunk/ProcessHacker.Native/Symbols/SymbolProvider.cs
index e0b4724a6..e2bf114c8 100644
--- a/1.x/trunk/ProcessHacker.Native/Symbols/SymbolProvider.cs
+++ b/1.x/trunk/ProcessHacker.Native/Symbols/SymbolProvider.cs
@@ -38,7 +38,7 @@ public sealed class SymbolProvider : IDisposable
{
private sealed class SymbolHandle : BaseObject
{
- private readonly ProcessHandle _processHandle;
+ private ProcessHandle _processHandle;
private IntPtr _handle;
public static implicit operator IntPtr(SymbolHandle symbolHandle)
@@ -99,7 +99,7 @@ public IntPtr Handle
}
private const int _maxNameLen = 0x100;
- private static readonly IdGenerator _idGen = new IdGenerator();
+ private static IdGenerator _idGen = new IdGenerator();
public static SymbolOptions Options
{
@@ -116,8 +116,8 @@ public static SymbolOptions Options
}
}
- private readonly SymbolHandle _handle;
- private readonly List> _modules = new List>();
+ private SymbolHandle _handle;
+ private List> _modules = new List>();
public SymbolProvider()
{
@@ -142,9 +142,11 @@ public bool Busy
{
return true;
}
-
- Win32.DbgHelpLock.Release();
- return false;
+ else
+ {
+ Win32.DbgHelpLock.Release();
+ return false;
+ }
}
}
@@ -164,7 +166,7 @@ public string SearchPath
using (Win32.DbgHelpLock.AcquireContext())
{
if (!Win32.SymGetSearchPath(_handle, data, data.Capacity))
- return string.Empty;
+ return "";
}
return data.ToString();
@@ -195,9 +197,10 @@ public void EnumSymbols(ulong moduleBase, string mask, SymbolEnumDelegate enumDe
_handle,
moduleBase,
mask,
- (symbolInfo, symbolSize, userContext) => enumDelegate(new SymbolInformation(symbolInfo, symbolSize)),
- IntPtr.Zero)
- )
+ (symbolInfo, symbolSize, userContext) =>
+ enumDelegate(new SymbolInformation(symbolInfo, symbolSize)),
+ IntPtr.Zero
+ ))
Win32.Throw();
}
}
@@ -209,10 +212,10 @@ public string GetLineFromAddress(ulong address)
this.GetLineFromAddress(address, out fileName, out lineNumber);
- if (!string.IsNullOrEmpty(fileName))
- return fileName + ": line " + lineNumber;
-
- return null;
+ if (fileName != null)
+ return fileName + ": line " + lineNumber.ToString();
+ else
+ return null;
}
public void GetLineFromAddress(ulong address, out string fileName, out int lineNumber)
@@ -334,15 +337,14 @@ public string GetSymbolFromAddress(ulong address, out SymbolResolveLevel level,
}
// Allocate some memory for the symbol information.
- using (MemoryAlloc data = new MemoryAlloc(SymbolInfo.SizeOf + _maxNameLen))
+ using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(SymbolInfo)) + _maxNameLen))
{
- SymbolInfo info = new SymbolInfo
- {
- SizeOfStruct = SymbolInfo.SizeOf,
- MaxNameLen = _maxNameLen - 1
- };
+ var info = new SymbolInfo();
- data.WriteStruct(info);
+ info.SizeOfStruct = Marshal.SizeOf(info);
+ info.MaxNameLen = _maxNameLen - 1;
+
+ Marshal.StructureToPtr(info, data, false);
// Hack for drivers, since we don't get their module sizes.
// Preloading modules will fix this.
@@ -384,7 +386,7 @@ public string GetSymbolFromAddress(ulong address, out SymbolResolveLevel level,
}
// If we don't have a module name, return an address.
- if (string.IsNullOrEmpty(modFileName))
+ if (modFileName == null)
{
level = SymbolResolveLevel.Address;
flags = 0;
@@ -418,10 +420,12 @@ public string GetSymbolFromAddress(ulong address, out SymbolResolveLevel level,
{
return fi.Name + "+0x" + (address - modBase).ToString("x");
}
+ else
+ {
+ var s = modFileName.Split('\\');
- var s = modFileName.Split('\\');
-
- return s[s.Length - 1] + "+0x" + (address - modBase).ToString("x");
+ return s[s.Length - 1] + "+0x" + (address - modBase).ToString("x");
+ }
}
// If we have everything, return the full symbol name: module!symbol+offset.
@@ -433,22 +437,21 @@ public string GetSymbolFromAddress(ulong address, out SymbolResolveLevel level,
if (displacement == 0)
return fi.Name + "!" + name;
-
- return fi.Name + "!" + name + "+0x" + displacement.ToString("x");
+ else
+ return fi.Name + "!" + name + "+0x" + displacement.ToString("x");
}
}
public SymbolInformation GetSymbolFromName(string symbolName)
{
- using (MemoryAlloc data = new MemoryAlloc(SymbolInfo.SizeOf + _maxNameLen))
+ using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(SymbolInfo)) + _maxNameLen))
{
- SymbolInfo info = new SymbolInfo
- {
- SizeOfStruct = SymbolInfo.SizeOf,
- MaxNameLen = _maxNameLen - 1
- };
+ var info = new SymbolInfo();
+
+ info.SizeOfStruct = Marshal.SizeOf(info);
+ info.MaxNameLen = _maxNameLen - 1;
- data.WriteStruct(info);
+ Marshal.StructureToPtr(info, data, false);
using (Win32.DbgHelpLock.AcquireContext())
{
diff --git a/1.x/trunk/ProcessHacker.Native/Threading/CurrentThread.cs b/1.x/trunk/ProcessHacker.Native/Threading/CurrentThread.cs
index 3d9cb8d79..a269c9e0f 100644
--- a/1.x/trunk/ProcessHacker.Native/Threading/CurrentThread.cs
+++ b/1.x/trunk/ProcessHacker.Native/Threading/CurrentThread.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
diff --git a/1.x/trunk/ProcessHacker.Native/Threading/Event.cs b/1.x/trunk/ProcessHacker.Native/Threading/Event.cs
index c00551171..19b716f82 100644
--- a/1.x/trunk/ProcessHacker.Native/Threading/Event.cs
+++ b/1.x/trunk/ProcessHacker.Native/Threading/Event.cs
@@ -20,6 +20,9 @@
* along with Process Hacker. If not, see .
*/
+using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -93,7 +96,11 @@ public Event(string name, bool autoReset, bool initialState)
///
public bool AutoReset
{
- get { return this.Handle.BasicInformation.EventType == EventType.SynchronizationEvent; }
+ get
+ {
+ return this.Handle.GetBasicInformation().EventType ==
+ EventType.SynchronizationEvent;
+ }
}
///
@@ -101,7 +108,7 @@ public bool AutoReset
///
public bool Signaled
{
- get { return this.Handle.BasicInformation.EventState != 0; }
+ get { return this.Handle.GetBasicInformation().EventState != 0; }
}
///
diff --git a/1.x/trunk/ProcessHacker.Native/Threading/EventPair.cs b/1.x/trunk/ProcessHacker.Native/Threading/EventPair.cs
index bd4f3c1ca..4b78b733e 100644
--- a/1.x/trunk/ProcessHacker.Native/Threading/EventPair.cs
+++ b/1.x/trunk/ProcessHacker.Native/Threading/EventPair.cs
@@ -20,6 +20,9 @@
* along with Process Hacker. If not, see .
*/
+using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
diff --git a/1.x/trunk/ProcessHacker.Native/Threading/KeyedEvent.cs b/1.x/trunk/ProcessHacker.Native/Threading/KeyedEvent.cs
index 966f5eef9..8c38b1f4c 100644
--- a/1.x/trunk/ProcessHacker.Native/Threading/KeyedEvent.cs
+++ b/1.x/trunk/ProcessHacker.Native/Threading/KeyedEvent.cs
@@ -21,6 +21,8 @@
*/
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
diff --git a/1.x/trunk/ProcessHacker.Native/Threading/Mutant.cs b/1.x/trunk/ProcessHacker.Native/Threading/Mutant.cs
index 4e3bcadda..f3841fcbf 100644
--- a/1.x/trunk/ProcessHacker.Native/Threading/Mutant.cs
+++ b/1.x/trunk/ProcessHacker.Native/Threading/Mutant.cs
@@ -20,6 +20,9 @@
* along with Process Hacker. If not, see .
*/
+using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -85,7 +88,7 @@ public Mutant(string name, bool owned)
///
public bool Owned
{
- get { return this.Handle.BasicInformation.CurrentCount <= 0; }
+ get { return this.Handle.GetBasicInformation().CurrentCount <= 0; }
}
///
diff --git a/1.x/trunk/ProcessHacker.Native/Threading/NativeThreadPool.cs b/1.x/trunk/ProcessHacker.Native/Threading/NativeThreadPool.cs
index 14bdf0d37..3074a7801 100644
--- a/1.x/trunk/ProcessHacker.Native/Threading/NativeThreadPool.cs
+++ b/1.x/trunk/ProcessHacker.Native/Threading/NativeThreadPool.cs
@@ -1,5 +1,8 @@
using System;
+using System.Collections.Generic;
+using System.Text;
using ProcessHacker.Native.Api;
+using ProcessHacker.Native.Objects;
namespace ProcessHacker.Native.Threading
{
@@ -9,7 +12,7 @@ public static class NativeThreadPool
{
public static void QueueWorkItem(Action
public sealed class Timer : NativeObject
{
+ private TimerCallback _callback;
+
///
/// Creates a timer.
///
@@ -90,7 +92,7 @@ public Timer(string name, bool autoReset)
///
public TimeSpan RemainingTime
{
- get { return new TimeSpan(this.Handle.BasicInformation.RemainingTime); }
+ get { return new TimeSpan(this.Handle.GetBasicInformation().RemainingTime); }
}
///
@@ -98,7 +100,7 @@ public TimeSpan RemainingTime
///
public bool Signaled
{
- get { return this.Handle.BasicInformation.TimerState; }
+ get { return this.Handle.GetBasicInformation().TimerState; }
}
///
@@ -150,6 +152,7 @@ public void Set(TimerCallback callback, int dueTime, int period, IntPtr context)
{
TimerApcRoutine apcRoutine = (context_, lowPart, highPart) => callback(context_);
+ _callback = callback;
this.Handle.Set(
dueTime * Win32.TimeMsTo100Ns,
true,
@@ -200,6 +203,7 @@ public void Set(TimerCallback callback, DateTime dueTime, int period, IntPtr con
{
TimerApcRoutine apcRoutine = (context_, lowPart, highPart) => callback(context_);
+ _callback = callback;
this.Handle.Set(
dueTime.ToFileTime(),
false,
diff --git a/1.x/trunk/ProcessHacker.Native/Threading/Waiter.cs b/1.x/trunk/ProcessHacker.Native/Threading/Waiter.cs
index 0cdfff408..07f3f9461 100644
--- a/1.x/trunk/ProcessHacker.Native/Threading/Waiter.cs
+++ b/1.x/trunk/ProcessHacker.Native/Threading/Waiter.cs
@@ -41,22 +41,20 @@ private class WaiterThread : BaseObject
{
public event ObjectSignaledDelegate ObjectSignaled;
- private readonly Waiter _owner;
- private bool _terminating;
- private readonly Thread _thread;
+ private Waiter _owner;
+ private bool _terminating = false;
+ private Thread _thread;
private FastEvent _threadInitializedEvent = new FastEvent(false);
private ThreadHandle _threadHandle;
- private readonly List _waitObjects = new List();
+ private List _waitObjects = new List();
public WaiterThread(Waiter owner)
{
_owner = owner;
// Create the waiter thread.
- _thread = new Thread(this.WaiterThreadStart, Common.Utils.SixteenthStackSize)
- {
- IsBackground = true
- };
+ _thread = new Thread(this.WaiterThreadStart, ProcessHacker.Common.Utils.SixteenthStackSize);
+ _thread.IsBackground = true;
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
@@ -233,8 +231,8 @@ private void WaiterThreadStart()
///
public event ObjectSignaledDelegate ObjectSignaled;
- private readonly List _waiterThreads = new List();
- private readonly List _waitObjects = new List();
+ private List _waiterThreads = new List();
+ private List _waitObjects = new List();
///
/// Creates a waiter.
@@ -303,7 +301,12 @@ internal void BalanceWaiterThreads()
}
}
- private void CreateWaiterThread(ISynchronizable obj = null)
+ private WaiterThread CreateWaiterThread()
+ {
+ return this.CreateWaiterThread(null);
+ }
+
+ private WaiterThread CreateWaiterThread(ISynchronizable obj)
{
WaiterThread waiterThread = new WaiterThread(this);
@@ -314,6 +317,8 @@ private void CreateWaiterThread(ISynchronizable obj = null)
lock (_waiterThreads)
_waiterThreads.Add(waiterThread);
+
+ return waiterThread;
}
private void DeleteWaiterThread(WaiterThread waiterThread)
diff --git a/1.x/trunk/ProcessHacker/Forms/Ui/ChooseProcessDialog.Designer.cs b/1.x/trunk/ProcessHacker.Native/Ui/ChooseProcessDialog.Designer.cs
similarity index 100%
rename from 1.x/trunk/ProcessHacker/Forms/Ui/ChooseProcessDialog.Designer.cs
rename to 1.x/trunk/ProcessHacker.Native/Ui/ChooseProcessDialog.Designer.cs
diff --git a/1.x/trunk/ProcessHacker/Forms/Ui/ChooseProcessDialog.cs b/1.x/trunk/ProcessHacker.Native/Ui/ChooseProcessDialog.cs
similarity index 76%
rename from 1.x/trunk/ProcessHacker/Forms/Ui/ChooseProcessDialog.cs
rename to 1.x/trunk/ProcessHacker.Native/Ui/ChooseProcessDialog.cs
index 5a18f44c7..12d82eb22 100644
--- a/1.x/trunk/ProcessHacker/Forms/Ui/ChooseProcessDialog.cs
+++ b/1.x/trunk/ProcessHacker.Native/Ui/ChooseProcessDialog.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ProcessHacker.Native.Objects;
@@ -28,7 +27,7 @@ public int SelectedPid
private void RefreshProcesses()
{
- Dictionary processes = Windows.GetProcesses();
+ var processes = Windows.GetProcesses();
listProcesses.BeginUpdate();
listProcesses.Items.Clear();
@@ -39,29 +38,30 @@ private void RefreshProcesses()
foreach (var process in processes.Values)
{
- string userName = string.Empty;
+ string userName = "";
string fileName = null;
try
{
- using (ProcessHandle phandle = new ProcessHandle(process.Process.ProcessId, OSVersion.MinProcessQueryInfoAccess))
+ using (var phandle = new ProcessHandle(process.Process.ProcessId, OSVersion.MinProcessQueryInfoAccess))
{
- using (TokenHandle thandle = phandle.GetToken(TokenAccess.Query))
- using (Sid sid = thandle.User)
+ using (var thandle = phandle.GetToken(TokenAccess.Query))
+ using (var sid = thandle.GetUser())
userName = sid.GetFullName(true);
- fileName = phandle.ImageFileName;
+ fileName = FileUtils.GetFileName(phandle.GetImageFileName());
}
}
catch
{ }
- ListViewItem item = new ListViewItem(new string[]
- {
- process.Process.ProcessId == 0 ? "System Idle Process" : process.Name,
- process.Process.ProcessId.ToString(),
- userName
- });
+ ListViewItem item = new ListViewItem(
+ new string[]
+ {
+ process.Process.ProcessId == 0 ? "System Idle Process" : process.Name,
+ process.Process.ProcessId.ToString(),
+ userName
+ });
if (!string.IsNullOrEmpty(fileName))
{
diff --git a/1.x/trunk/ProcessHacker/Forms/Ui/ChooseProcessDialog.resx b/1.x/trunk/ProcessHacker.Native/Ui/ChooseProcessDialog.resx
similarity index 100%
rename from 1.x/trunk/ProcessHacker/Forms/Ui/ChooseProcessDialog.resx
rename to 1.x/trunk/ProcessHacker.Native/Ui/ChooseProcessDialog.resx
diff --git a/1.x/trunk/ProcessHacker/Components/HandleDetails.Designer.cs b/1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.Designer.cs
similarity index 63%
rename from 1.x/trunk/ProcessHacker/Components/HandleDetails.Designer.cs
rename to 1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.Designer.cs
index 2e1263e1b..3b5f6a828 100644
--- a/1.x/trunk/ProcessHacker/Components/HandleDetails.Designer.cs
+++ b/1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.Designer.cs
@@ -1,13 +1,13 @@
-namespace ProcessHacker.Components
+namespace ProcessHacker.Native.Ui
{
- partial class HandleDetails
+ partial class HandlePropertiesWindow
{
- ///
+ ///
/// Required designer variable.
///
private System.ComponentModel.IContainer components = null;
- ///
+ ///
/// Clean up any resources being used.
///
/// true if managed resources should be disposed; otherwise, false.
@@ -17,17 +17,20 @@ protected override void Dispose(bool disposing)
{
components.Dispose();
}
+
base.Dispose(disposing);
}
- #region Component Designer generated code
+ #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
+ ///
+ /// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
+ this.tabControl = new System.Windows.Forms.TabControl();
+ this.tabDetails = new System.Windows.Forms.TabPage();
this.groupObjectInfo = new System.Windows.Forms.GroupBox();
this.groupQuotaCharges = new System.Windows.Forms.GroupBox();
this.labelNonPaged = new System.Windows.Forms.Label();
@@ -44,33 +47,63 @@ private void InitializeComponent()
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
+ this.buttonClose = new System.Windows.Forms.Button();
+ this.buttonPermissions = new System.Windows.Forms.Button();
+ this.tabControl.SuspendLayout();
+ this.tabDetails.SuspendLayout();
this.groupQuotaCharges.SuspendLayout();
this.groupReferences.SuspendLayout();
this.groupBasicInfo.SuspendLayout();
this.SuspendLayout();
//
+ // tabControl
+ //
+ this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.tabControl.Controls.Add(this.tabDetails);
+ this.tabControl.Location = new System.Drawing.Point(12, 12);
+ this.tabControl.Name = "tabControl";
+ this.tabControl.SelectedIndex = 0;
+ this.tabControl.Size = new System.Drawing.Size(370, 382);
+ this.tabControl.TabIndex = 0;
+ //
+ // tabDetails
+ //
+ this.tabDetails.Controls.Add(this.groupObjectInfo);
+ this.tabDetails.Controls.Add(this.groupQuotaCharges);
+ this.tabDetails.Controls.Add(this.groupReferences);
+ this.tabDetails.Controls.Add(this.groupBasicInfo);
+ this.tabDetails.Location = new System.Drawing.Point(4, 22);
+ this.tabDetails.Name = "tabDetails";
+ this.tabDetails.Padding = new System.Windows.Forms.Padding(3);
+ this.tabDetails.Size = new System.Drawing.Size(362, 356);
+ this.tabDetails.TabIndex = 0;
+ this.tabDetails.Text = "Details";
+ this.tabDetails.UseVisualStyleBackColor = true;
+ //
// groupObjectInfo
//
- this.groupObjectInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.groupObjectInfo.Location = new System.Drawing.Point(6, 189);
+ this.groupObjectInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupObjectInfo.Location = new System.Drawing.Point(6, 215);
this.groupObjectInfo.Name = "groupObjectInfo";
- this.groupObjectInfo.Size = new System.Drawing.Size(430, 234);
- this.groupObjectInfo.TabIndex = 7;
+ this.groupObjectInfo.Size = new System.Drawing.Size(350, 135);
+ this.groupObjectInfo.TabIndex = 3;
this.groupObjectInfo.TabStop = false;
this.groupObjectInfo.Text = "Object Information";
//
// groupQuotaCharges
//
- this.groupQuotaCharges.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupQuotaCharges.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.groupQuotaCharges.Controls.Add(this.labelNonPaged);
this.groupQuotaCharges.Controls.Add(this.labelPaged);
- this.groupQuotaCharges.Location = new System.Drawing.Point(188, 112);
+ this.groupQuotaCharges.Location = new System.Drawing.Point(179, 138);
this.groupQuotaCharges.Name = "groupQuotaCharges";
- this.groupQuotaCharges.Size = new System.Drawing.Size(248, 71);
- this.groupQuotaCharges.TabIndex = 6;
+ this.groupQuotaCharges.Size = new System.Drawing.Size(177, 71);
+ this.groupQuotaCharges.TabIndex = 2;
this.groupQuotaCharges.TabStop = false;
this.groupQuotaCharges.Text = "Quota Charges";
//
@@ -96,10 +129,10 @@ private void InitializeComponent()
//
this.groupReferences.Controls.Add(this.labelHandles);
this.groupReferences.Controls.Add(this.labelReferences);
- this.groupReferences.Location = new System.Drawing.Point(6, 112);
+ this.groupReferences.Location = new System.Drawing.Point(6, 138);
this.groupReferences.Name = "groupReferences";
- this.groupReferences.Size = new System.Drawing.Size(176, 71);
- this.groupReferences.TabIndex = 5;
+ this.groupReferences.Size = new System.Drawing.Size(167, 71);
+ this.groupReferences.TabIndex = 1;
this.groupReferences.TabStop = false;
this.groupReferences.Text = "References";
//
@@ -123,8 +156,9 @@ private void InitializeComponent()
//
// groupBasicInfo
//
- this.groupBasicInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupBasicInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupBasicInfo.Controls.Add(this.buttonPermissions);
this.groupBasicInfo.Controls.Add(this.textGrantedAccess);
this.groupBasicInfo.Controls.Add(this.textAddress);
this.groupBasicInfo.Controls.Add(this.textType);
@@ -135,49 +169,49 @@ private void InitializeComponent()
this.groupBasicInfo.Controls.Add(this.label1);
this.groupBasicInfo.Location = new System.Drawing.Point(6, 6);
this.groupBasicInfo.Name = "groupBasicInfo";
- this.groupBasicInfo.Size = new System.Drawing.Size(430, 102);
+ this.groupBasicInfo.Size = new System.Drawing.Size(350, 126);
this.groupBasicInfo.TabIndex = 0;
this.groupBasicInfo.TabStop = false;
this.groupBasicInfo.Text = "Basic Information";
//
// textGrantedAccess
//
- this.textGrantedAccess.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textGrantedAccess.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textGrantedAccess.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textGrantedAccess.Location = new System.Drawing.Point(98, 76);
this.textGrantedAccess.Name = "textGrantedAccess";
- this.textGrantedAccess.Size = new System.Drawing.Size(326, 13);
- this.textGrantedAccess.TabIndex = 20;
+ this.textGrantedAccess.Size = new System.Drawing.Size(246, 13);
+ this.textGrantedAccess.TabIndex = 1;
//
// textAddress
//
- this.textAddress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textAddress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textAddress.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textAddress.Location = new System.Drawing.Point(98, 57);
this.textAddress.Name = "textAddress";
- this.textAddress.Size = new System.Drawing.Size(326, 13);
+ this.textAddress.Size = new System.Drawing.Size(246, 13);
this.textAddress.TabIndex = 1;
//
// textType
//
- this.textType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textType.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textType.Location = new System.Drawing.Point(60, 38);
this.textType.Name = "textType";
- this.textType.Size = new System.Drawing.Size(364, 13);
+ this.textType.Size = new System.Drawing.Size(284, 13);
this.textType.TabIndex = 1;
//
// textName
//
- this.textName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textName.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textName.Location = new System.Drawing.Point(60, 19);
this.textName.Name = "textName";
- this.textName.Size = new System.Drawing.Size(364, 13);
+ this.textName.Size = new System.Drawing.Size(284, 13);
this.textName.TabIndex = 1;
//
// label4
@@ -186,7 +220,7 @@ private void InitializeComponent()
this.label4.Location = new System.Drawing.Point(6, 76);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(86, 13);
- this.label4.TabIndex = 21;
+ this.label4.TabIndex = 0;
this.label4.Text = "Granted Access:";
//
// label3
@@ -204,7 +238,7 @@ private void InitializeComponent()
this.label2.Location = new System.Drawing.Point(6, 38);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(34, 13);
- this.label2.TabIndex = 2;
+ this.label2.TabIndex = 0;
this.label2.Text = "Type:";
//
// label1
@@ -216,18 +250,47 @@ private void InitializeComponent()
this.label1.TabIndex = 0;
this.label1.Text = "Name:";
//
- // HandleDetails
+ // buttonClose
+ //
+ this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
+ this.buttonClose.Location = new System.Drawing.Point(307, 400);
+ this.buttonClose.Name = "buttonClose";
+ this.buttonClose.Size = new System.Drawing.Size(75, 23);
+ this.buttonClose.TabIndex = 1;
+ this.buttonClose.Text = "Close";
+ this.buttonClose.UseVisualStyleBackColor = true;
+ this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
+ //
+ // buttonPermissions
+ //
+ this.buttonPermissions.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonPermissions.FlatStyle = System.Windows.Forms.FlatStyle.System;
+ this.buttonPermissions.Location = new System.Drawing.Point(269, 97);
+ this.buttonPermissions.Name = "buttonPermissions";
+ this.buttonPermissions.Size = new System.Drawing.Size(75, 23);
+ this.buttonPermissions.TabIndex = 2;
+ this.buttonPermissions.Text = "Permissions";
+ this.buttonPermissions.UseVisualStyleBackColor = true;
+ this.buttonPermissions.Click += new System.EventHandler(this.buttonPermissions_Click);
+ //
+ // HandlePropertiesWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.White;
- this.Controls.Add(this.groupObjectInfo);
- this.Controls.Add(this.groupQuotaCharges);
- this.Controls.Add(this.groupReferences);
- this.Controls.Add(this.groupBasicInfo);
- this.Name = "HandleDetails";
- this.Padding = new System.Windows.Forms.Padding(3);
- this.Size = new System.Drawing.Size(442, 429);
+ this.ClientSize = new System.Drawing.Size(394, 435);
+ this.Controls.Add(this.buttonClose);
+ this.Controls.Add(this.tabControl);
+ this.MaximizeBox = false;
+ this.MinimizeBox = false;
+ this.Name = "HandlePropertiesWindow";
+ this.ShowIcon = false;
+ this.ShowInTaskbar = false;
+ this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+ this.Text = "Handle Properties";
+ this.Load += new System.EventHandler(this.HandlePropertiesWindow_Load);
+ this.tabControl.ResumeLayout(false);
+ this.tabDetails.ResumeLayout(false);
this.groupQuotaCharges.ResumeLayout(false);
this.groupQuotaCharges.PerformLayout();
this.groupReferences.ResumeLayout(false);
@@ -240,22 +303,25 @@ private void InitializeComponent()
#endregion
- private System.Windows.Forms.GroupBox groupObjectInfo;
- private System.Windows.Forms.GroupBox groupQuotaCharges;
- private System.Windows.Forms.Label labelNonPaged;
- private System.Windows.Forms.Label labelPaged;
- private System.Windows.Forms.GroupBox groupReferences;
- private System.Windows.Forms.Label labelHandles;
- private System.Windows.Forms.Label labelReferences;
+ private System.Windows.Forms.TabControl tabControl;
+ private System.Windows.Forms.TabPage tabDetails;
+ private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.GroupBox groupBasicInfo;
- private System.Windows.Forms.TextBox textGrantedAccess;
- private System.Windows.Forms.TextBox textAddress;
- private System.Windows.Forms.TextBox textType;
private System.Windows.Forms.TextBox textName;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
-
+ private System.Windows.Forms.TextBox textGrantedAccess;
+ private System.Windows.Forms.TextBox textAddress;
+ private System.Windows.Forms.TextBox textType;
+ private System.Windows.Forms.GroupBox groupReferences;
+ private System.Windows.Forms.Label labelHandles;
+ private System.Windows.Forms.Label labelReferences;
+ private System.Windows.Forms.GroupBox groupQuotaCharges;
+ private System.Windows.Forms.Label labelNonPaged;
+ private System.Windows.Forms.Label labelPaged;
+ private System.Windows.Forms.GroupBox groupObjectInfo;
+ private System.Windows.Forms.Button buttonPermissions;
}
-}
+}
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.cs b/1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.cs
new file mode 100644
index 000000000..d74083378
--- /dev/null
+++ b/1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.cs
@@ -0,0 +1,151 @@
+/*
+ * Process Hacker -
+ * handle properties window
+ *
+ * Copyright (C) 2009 wj32
+ *
+ * This file is part of Process Hacker.
+ *
+ * Process Hacker is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Process Hacker is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Process Hacker. If not, see .
+ */
+
+using System;
+using System.Windows.Forms;
+using ProcessHacker.Native.Api;
+using ProcessHacker.Native.Objects;
+using ProcessHacker.Native.Security.AccessControl;
+
+namespace ProcessHacker.Native.Ui
+{
+ public partial class HandlePropertiesWindow : Form
+ {
+ public delegate void HandlePropertiesDelegate(Control objectGroup, string name, string typeName);
+
+ public event HandlePropertiesDelegate HandlePropertiesCallback;
+
+ private string _name, _typeName;
+ private NativeHandle _objectHandle;
+
+ public HandlePropertiesWindow(SystemHandleEntry handle)
+ {
+ InitializeComponent();
+ this.KeyPreview = true;
+ this.KeyDown += (sender, e) =>
+ {
+ if (e.KeyCode == Keys.Escape)
+ {
+ this.Close();
+ e.Handled = true;
+ }
+ };
+
+ var handleInfo = handle.GetHandleInfo();
+
+ textName.Text = _name = handleInfo.BestName;
+ if (textName.Text == "")
+ textName.Text = "(unnamed object)";
+ textType.Text = _typeName = handleInfo.TypeName;
+ textAddress.Text = "0x" + handle.Object.ToString("x");
+ textGrantedAccess.Text = "0x" + handle.GrantedAccess.ToString("x");
+
+ if (handle.GrantedAccess != 0)
+ {
+ try
+ {
+ Type accessEnumType = NativeTypeFactory.GetAccessType(handleInfo.TypeName);
+
+ textGrantedAccess.Text += " (" +
+ NativeTypeFactory.GetAccessString(accessEnumType, handle.GrantedAccess) +
+ ")";
+ }
+ catch (NotSupportedException)
+ { }
+ }
+
+ var basicInfo = handle.GetBasicInfo();
+
+ labelReferences.Text = "References: " + (basicInfo.PointerCount - 1).ToString();
+ labelHandles.Text = "Handles: " + basicInfo.HandleCount.ToString();
+ labelPaged.Text = "Paged: " + basicInfo.PagedPoolUsage.ToString();
+ labelNonPaged.Text = "Non-Paged: " + basicInfo.NonPagedPoolUsage.ToString();
+ }
+
+ private void HandlePropertiesWindow_Load(object sender, EventArgs e)
+ {
+ if (HandlePropertiesCallback != null)
+ {
+ try
+ {
+ HandlePropertiesCallback(groupObjectInfo, _name, _typeName);
+ }
+ catch
+ { }
+
+ if (groupObjectInfo.Controls.Count == 0)
+ {
+ groupObjectInfo.Visible = false;
+ }
+ else if (groupObjectInfo.Controls.Count == 1)
+ {
+ Control control = groupObjectInfo.Controls[0];
+
+ // If it's a user control, dock it.
+ if (control is UserControl)
+ {
+ control.Dock = DockStyle.Fill;
+ control.Margin = new Padding(3);
+ }
+ else
+ {
+ control.Location = new System.Drawing.Point(10, 20);
+ }
+ }
+ }
+
+ if (this.ObjectHandle == null)
+ buttonPermissions.Visible = false;
+ }
+
+ public NativeHandle ObjectHandle
+ {
+ get { return _objectHandle; }
+ set { _objectHandle = value; }
+ }
+
+ private void buttonClose_Click(object sender, EventArgs e)
+ {
+ this.Close();
+ }
+
+ private void buttonPermissions_Click(object sender, EventArgs e)
+ {
+ if (_objectHandle != null)
+ {
+ try
+ {
+ SecurityEditor.EditSecurity(
+ this,
+ SecurityEditor.GetSecurableWrapper(_objectHandle),
+ _name,
+ NativeTypeFactory.GetAccessEntries(NativeTypeFactory.GetObjectType(_typeName))
+ );
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show("Unable to edit security: " + ex.Message, "Security Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+ }
+ }
+}
diff --git a/1.x/trunk/ProcessHacker/Forms/Ui/HandlePropertiesWindow.resx b/1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.resx
similarity index 95%
rename from 1.x/trunk/ProcessHacker/Forms/Ui/HandlePropertiesWindow.resx
rename to 1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Forms/Ui/HandlePropertiesWindow.resx
+++ b/1.x/trunk/ProcessHacker.Native/Ui/HandlePropertiesWindow.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker.Native/Windows.cs b/1.x/trunk/ProcessHacker.Native/Windows.cs
index edbff97b4..2cdece6a5 100644
--- a/1.x/trunk/ProcessHacker.Native/Windows.cs
+++ b/1.x/trunk/ProcessHacker.Native/Windows.cs
@@ -63,10 +63,10 @@ public static class Windows
[ThreadStatic]
private static MemoryAlloc _servicesBuffer;
- private static int _numberOfProcessors;
- private static int _pageSize;
+ private static int _numberOfProcessors = 0;
+ private static int _pageSize = 0;
private static IntPtr _kernelBase = IntPtr.Zero;
- private static string _kernelFileName;
+ private static string _kernelFileName = null;
///
/// Gets the number of active processors.
@@ -141,12 +141,13 @@ public static int BytesToPages(int bytes)
/// A callback for the enumeration.
public static void EnumKernelModules(EnumKernelModulesDelegate enumCallback)
{
+ NtStatus status;
int retLength;
if (_kernelModulesBuffer == null)
_kernelModulesBuffer = new MemoryAlloc(0x1000);
- NtStatus status = Win32.NtQuerySystemInformation(
+ status = Win32.NtQuerySystemInformation(
SystemInformationClass.SystemModuleInformation,
_kernelModulesBuffer,
_kernelModulesBuffer.Size,
@@ -165,13 +166,14 @@ out retLength
);
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
RtlProcessModules modules = _kernelModulesBuffer.ReadStruct();
for (int i = 0; i < modules.NumberOfModules; i++)
{
- var module = _kernelModulesBuffer.ReadStruct(RtlProcessModules.ModulesOffset, RtlProcessModuleInformation.SizeOf, i);
+ var module = _kernelModulesBuffer.ReadStruct(RtlProcessModules.ModulesOffset, i);
var moduleInfo = new Debugging.ModuleInformation(module);
if (!enumCallback(new KernelModule(
@@ -191,15 +193,17 @@ out retLength
/// A structure containing basic information.
public static SystemBasicInformation GetBasicInformation()
{
+ NtStatus status;
SystemBasicInformation sbi;
int retLength;
- Win32.NtQuerySystemInformation(
+ if ((status = Win32.NtQuerySystemInformation(
SystemInformationClass.SystemBasicInformation,
out sbi,
- SystemBasicInformation.SizeOf,
+ Marshal.SizeOf(typeof(SystemBasicInformation)),
out retLength
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
return sbi;
}
@@ -210,8 +214,8 @@ out retLength
/// An array containing information about the handles.
public static SystemHandleEntry[] GetHandles()
{
- int retLength;
- int handleCount;
+ int retLength = 0;
+ int handleCount = 0;
SystemHandleEntry[] returnHandles;
if (_handlesBuffer == null)
@@ -238,7 +242,8 @@ public static SystemHandleEntry[] GetHandles()
throw new OutOfMemoryException();
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
// The structure of the buffer is the handle count plus an array of SYSTEM_HANDLE_INFORMATION
// structures.
@@ -268,7 +273,7 @@ private static IntPtr GetKernelBase()
{
IntPtr kernelBase = IntPtr.Zero;
- EnumKernelModules(module =>
+ Windows.EnumKernelModules((module) =>
{
kernelBase = module.BaseAddress;
return false;
@@ -285,7 +290,7 @@ private static string GetKernelFileName()
{
string kernelFileName = null;
- EnumKernelModules(module =>
+ EnumKernelModules((module) =>
{
kernelFileName = module.FileName;
return false;
@@ -302,7 +307,7 @@ public static KernelModule[] GetKernelModules()
{
List kernelModules = new List();
- EnumKernelModules(kernelModule =>
+ EnumKernelModules((kernelModule) =>
{
kernelModules.Add(kernelModule);
return true;
@@ -313,49 +318,53 @@ public static KernelModule[] GetKernelModules()
public static SystemLogonSession GetLogonSession(Luid logonId)
{
+ NtStatus status;
IntPtr logonSessionData;
- Win32.LsaGetLogonSessionData(
+ if ((status = Win32.LsaGetLogonSessionData(
ref logonId,
out logonSessionData
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
using (var logonSessionDataAlloc = new LsaMemoryAlloc(logonSessionData, true))
{
var info = logonSessionDataAlloc.ReadStruct();
return new SystemLogonSession(
- info.AuthenticationPackage.Text,
- info.DnsDomainName.Text,
- info.LogonDomain.Text,
+ info.AuthenticationPackage.Read(),
+ info.DnsDomainName.Read(),
+ info.LogonDomain.Read(),
info.LogonId,
- info.LogonServer.Text,
+ info.LogonServer.Read(),
DateTime.FromFileTime(info.LogonTime),
info.LogonType,
info.Session,
new Sid(info.Sid),
- info.Upn.Text,
- info.UserName.Text
+ info.Upn.Read(),
+ info.UserName.Read()
);
}
}
public static Luid[] GetLogonSessions()
{
+ NtStatus status;
int logonSessionCount;
IntPtr logonSessionList;
- Win32.LsaEnumerateLogonSessions(
+ if ((status = Win32.LsaEnumerateLogonSessions(
out logonSessionCount,
out logonSessionList
- ).ThrowIf();
+ )) >= NtStatus.Error)
+ Win32.Throw(status);
Luid[] logonSessions = new Luid[logonSessionCount];
- using (LsaMemoryAlloc logonSessionListAlloc = new LsaMemoryAlloc(logonSessionList, true))
+ using (var logonSessionListAlloc = new LsaMemoryAlloc(logonSessionList, true))
{
for (int i = 0; i < logonSessionCount; i++)
- logonSessions[i] = logonSessionListAlloc.ReadStruct(0, Luid.SizeOf, i);
+ logonSessions[i] = logonSessionListAlloc.ReadStruct(i);
return logonSessions;
}
@@ -368,12 +377,14 @@ out logonSessionList
public static Dictionary> GetNetworkConnections()
{
var retDict = new Dictionary>();
- int length = 0;
+ int length;
// TCP IPv4
+
+ length = 0;
Win32.GetExtendedTcpTable(IntPtr.Zero, ref length, false, AiFamily.INet, TcpTableClass.OwnerPidAll, 0);
- using (MemoryAlloc mem = new MemoryAlloc(length))
+ using (var mem = new MemoryAlloc(length))
{
if (Win32.GetExtendedTcpTable(mem, ref length, false, AiFamily.INet, TcpTableClass.OwnerPidAll, 0) != 0)
Win32.Throw();
@@ -382,12 +393,12 @@ public static Dictionary> GetNetworkConnections()
for (int i = 0; i < count; i++)
{
- MibTcpRowOwnerPid struc = mem.ReadStruct(sizeof(int), MibTcpRowOwnerPid.SizeOf, i);
+ var struc = mem.ReadStruct(sizeof(int), i);
if (!retDict.ContainsKey(struc.OwningProcessId))
retDict.Add(struc.OwningProcessId, new List());
- retDict[struc.OwningProcessId].Add(new NetworkConnection
+ retDict[struc.OwningProcessId].Add(new NetworkConnection()
{
Protocol = NetworkProtocol.Tcp,
Local = new IPEndPoint(struc.LocalAddress, ((ushort)struc.LocalPort).Reverse()),
@@ -403,7 +414,7 @@ public static Dictionary> GetNetworkConnections()
length = 0;
Win32.GetExtendedUdpTable(IntPtr.Zero, ref length, false, AiFamily.INet, UdpTableClass.OwnerPid, 0);
- using (MemoryAlloc mem = new MemoryAlloc(length))
+ using (var mem = new MemoryAlloc(length))
{
if (Win32.GetExtendedUdpTable(mem, ref length, false, AiFamily.INet, UdpTableClass.OwnerPid, 0) != 0)
Win32.Throw();
@@ -412,17 +423,18 @@ public static Dictionary> GetNetworkConnections()
for (int i = 0; i < count; i++)
{
- MibUdpRowOwnerPid struc = mem.ReadStruct(sizeof(int), MibUdpRowOwnerPid.SizeOf, i);
+ var struc = mem.ReadStruct(sizeof(int), i);
if (!retDict.ContainsKey(struc.OwningProcessId))
retDict.Add(struc.OwningProcessId, new List());
- retDict[struc.OwningProcessId].Add(new NetworkConnection
- {
- Protocol = NetworkProtocol.Udp,
- Local = new IPEndPoint(struc.LocalAddress, ((ushort)struc.LocalPort).Reverse()),
- Pid = struc.OwningProcessId
- });
+ retDict[struc.OwningProcessId].Add(
+ new NetworkConnection()
+ {
+ Protocol = NetworkProtocol.Udp,
+ Local = new IPEndPoint(struc.LocalAddress, ((ushort)struc.LocalPort).Reverse()),
+ Pid = struc.OwningProcessId
+ });
}
}
@@ -431,7 +443,7 @@ public static Dictionary> GetNetworkConnections()
length = 0;
Win32.GetExtendedTcpTable(IntPtr.Zero, ref length, false, AiFamily.INet6, TcpTableClass.OwnerPidAll, 0);
- using (MemoryAlloc mem = new MemoryAlloc(length))
+ using (var mem = new MemoryAlloc(length))
{
if (Win32.GetExtendedTcpTable(mem, ref length, false, AiFamily.INet6, TcpTableClass.OwnerPidAll, 0) == 0)
{
@@ -439,12 +451,12 @@ public static Dictionary> GetNetworkConnections()
for (int i = 0; i < count; i++)
{
- MibTcp6RowOwnerPid struc = mem.ReadStruct(sizeof(int), MibTcp6RowOwnerPid.SizeOf, i);
+ var struc = mem.ReadStruct(sizeof(int), i);
if (!retDict.ContainsKey(struc.OwningProcessId))
retDict.Add(struc.OwningProcessId, new List());
- retDict[struc.OwningProcessId].Add(new NetworkConnection
+ retDict[struc.OwningProcessId].Add(new NetworkConnection()
{
Protocol = NetworkProtocol.Tcp6,
Local = new IPEndPoint(new IPAddress(struc.LocalAddress, struc.LocalScopeId), ((ushort)struc.LocalPort).Reverse()),
@@ -461,7 +473,7 @@ public static Dictionary> GetNetworkConnections()
length = 0;
Win32.GetExtendedUdpTable(IntPtr.Zero, ref length, false, AiFamily.INet6, UdpTableClass.OwnerPid, 0);
- using (MemoryAlloc mem = new MemoryAlloc(length))
+ using (var mem = new MemoryAlloc(length))
{
if (Win32.GetExtendedUdpTable(mem, ref length, false, AiFamily.INet6, UdpTableClass.OwnerPid, 0) == 0)
{
@@ -469,17 +481,18 @@ public static Dictionary> GetNetworkConnections()
for (int i = 0; i < count; i++)
{
- MibUdp6RowOwnerPid struc = mem.ReadStruct(sizeof(int), MibUdp6RowOwnerPid.SizeOf, i);
+ var struc = mem.ReadStruct(sizeof(int), i);
if (!retDict.ContainsKey(struc.OwningProcessId))
retDict.Add(struc.OwningProcessId, new List());
- retDict[struc.OwningProcessId].Add(new NetworkConnection
- {
- Protocol = NetworkProtocol.Udp6,
- Local = new IPEndPoint(new IPAddress(struc.LocalAddress, struc.LocalScopeId), ((ushort)struc.LocalPort).Reverse()),
- Pid = struc.OwningProcessId
- });
+ retDict[struc.OwningProcessId].Add(
+ new NetworkConnection()
+ {
+ Protocol = NetworkProtocol.Udp6,
+ Local = new IPEndPoint(new IPAddress(struc.LocalAddress, struc.LocalScopeId), ((ushort)struc.LocalPort).Reverse()),
+ Pid = struc.OwningProcessId
+ });
}
}
}
@@ -494,6 +507,7 @@ public static Dictionary> GetNetworkConnections()
public static SystemPagefile[] GetPagefiles()
{
int retLength;
+ List pagefiles = new List();
using (MemoryAlloc data = new MemoryAlloc(0x200))
{
@@ -513,22 +527,23 @@ public static SystemPagefile[] GetPagefiles()
throw new OutOfMemoryException();
}
- status.ThrowIf();
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
- List pagefiles = new List(2);
+ pagefiles = new List(2);
int i = 0;
SystemPagefileInformation currentPagefile;
do
{
- currentPagefile = data.ReadStruct(i, SystemPagefileInformation.SizeOf, 0);
+ currentPagefile = data.ReadStruct(i, 0);
pagefiles.Add(new SystemPagefile(
currentPagefile.TotalSize,
currentPagefile.TotalInUse,
currentPagefile.PeakUsage,
- FileUtils.GetFileName(currentPagefile.PageFileName.Text)
+ FileUtils.GetFileName(currentPagefile.PageFileName.Read())
));
i += currentPagefile.NextEntryOffset;
@@ -555,6 +570,7 @@ public static Dictionary GetProcesses()
public static Dictionary GetProcesses(bool getThreads)
{
int retLength;
+ Dictionary returnProcesses;
if (_processesBuffer == null)
_processesBuffer = new MemoryAlloc(0x10000);
@@ -573,7 +589,7 @@ public static Dictionary GetProcesses(bool getThreads)
data,
data.Size,
out retLength
- )).IsError())
+ )) >= NtStatus.Error)
{
if (attempts > 3)
Win32.Throw(status);
@@ -586,7 +602,7 @@ out retLength
}
}
- Dictionary returnProcesses = new Dictionary(32);
+ returnProcesses = new Dictionary(32); // 32 processes on a computer?
int i = 0;
SystemProcess currentProcess = new SystemProcess();
@@ -599,15 +615,17 @@ out retLength
currentProcess.Process = *(SystemProcessInformation*)((byte*)data.Memory + i);
}
- currentProcess.Name = currentProcess.Process.ImageName.Text;
+ currentProcess.Name = currentProcess.Process.ImageName.Read();
- if (getThreads && currentProcess.Process.ProcessId != 0)
+ if (getThreads &&
+ currentProcess.Process.ProcessId != 0)
{
currentProcess.Threads = new Dictionary();
for (int j = 0; j < currentProcess.Process.NumberOfThreads; j++)
{
- var thread = data.ReadStruct(i + SystemProcessInformation.SizeOf, SystemThreadInformation.SizeOf, j);
+ var thread = data.ReadStruct(i +
+ Marshal.SizeOf(typeof(SystemProcessInformation)), j);
currentProcess.Threads.Add(thread.ClientId.ThreadId, thread);
}
@@ -642,12 +660,8 @@ public static Dictionary GetProcessThreads(int pid
{
attempts++;
- if ((status = Win32.NtQuerySystemInformation(
- SystemInformationClass.SystemProcessInformation,
- data.Memory,
- data.Size,
- out retLength)
- ).IsError())
+ if ((status = Win32.NtQuerySystemInformation(SystemInformationClass.SystemProcessInformation, data.Memory,
+ data.Size, out retLength)) >= NtStatus.Error)
{
if (attempts > 3)
Win32.Throw(status);
@@ -673,11 +687,12 @@ public static Dictionary GetProcessThreads(int pid
if (process.ProcessId == pid)
{
- Dictionary threads = new Dictionary();
+ var threads = new Dictionary();
for (int j = 0; j < process.NumberOfThreads; j++)
{
- SystemThreadInformation thread = data.ReadStruct(i + SystemProcessInformation.SizeOf, SystemThreadInformation.SizeOf, j);
+ var thread = data.ReadStruct(i +
+ Marshal.SizeOf(typeof(SystemProcessInformation)), j);
if (pid != 0)
{
@@ -708,7 +723,8 @@ public static Dictionary GetProcessThreads(int pid
/// A dictionary, indexed by service name.
public static Dictionary GetServices()
{
- using (ServiceManagerHandle manager = new ServiceManagerHandle(ScManagerAccess.EnumerateService))
+ using (ServiceManagerHandle manager =
+ new ServiceManagerHandle(ScManagerAccess.EnumerateService))
{
int requiredSize;
int servicesReturned;
@@ -720,21 +736,25 @@ public static Dictionary GetServices()
MemoryAlloc data = _servicesBuffer;
if (!Win32.EnumServicesStatusEx(manager, IntPtr.Zero, ServiceQueryType.Win32 | ServiceQueryType.Driver,
- ServiceQueryState.All, data, data.Size, out requiredSize, out servicesReturned, ref resume, null))
+ ServiceQueryState.All, data,
+ data.Size, out requiredSize, out servicesReturned,
+ ref resume, null))
{
// resize buffer
data.ResizeNew(requiredSize);
if (!Win32.EnumServicesStatusEx(manager, IntPtr.Zero, ServiceQueryType.Win32 | ServiceQueryType.Driver,
- ServiceQueryState.All, data, data.Size, out requiredSize, out servicesReturned, ref resume, null))
+ ServiceQueryState.All, data,
+ data.Size, out requiredSize, out servicesReturned,
+ ref resume, null))
Win32.Throw();
}
- Dictionary dictionary = new Dictionary(servicesReturned);
+ var dictionary = new Dictionary(servicesReturned);
for (int i = 0; i < servicesReturned; i++)
{
- EnumServiceStatusProcess service = data.ReadStruct(0, EnumServiceStatusProcess.SizeOf, i);
+ var service = data.ReadStruct(i);
dictionary.Add(service.ServiceName, service);
}
@@ -750,12 +770,15 @@ public static Dictionary GetServices()
public static long GetTickCount()
{
// Read the tick count multiplier.
- int tickCountMultiplier = Marshal.ReadInt32(Win32.UserSharedData.Increment(KUserSharedData.TickCountMultiplierOffset));
+ int tickCountMultiplier = Marshal.ReadInt32(Win32.UserSharedData.Increment(
+ KUserSharedData.TickCountMultiplierOffset));
// Read the tick count.
- var tickCount = QueryKSystemTime(Win32.UserSharedData.Increment(KUserSharedData.TickCountOffset));
+ var tickCount = QueryKSystemTime(Win32.UserSharedData.Increment(
+ KUserSharedData.TickCountOffset));
- return ((tickCount.LowPart * tickCountMultiplier) >> 24) + (((long)tickCount.HighPart * tickCountMultiplier) << 8);
+ return (((long)tickCount.LowPart * tickCountMultiplier) >> (int)24) +
+ (((long)tickCount.HighPart * tickCountMultiplier) << (int)8);
}
///
@@ -764,15 +787,19 @@ public static long GetTickCount()
/// A time of day structure.
public static SystemTimeOfDayInformation GetTimeOfDay()
{
+ NtStatus status;
SystemTimeOfDayInformation timeOfDay;
int retLength;
- Win32.NtQuerySystemInformation(
+ status = Win32.NtQuerySystemInformation(
SystemInformationClass.SystemTimeOfDayInformation,
out timeOfDay,
- SystemTimeOfDayInformation.SizeOf,
+ Marshal.SizeOf(typeof(SystemTimeOfDayInformation)),
out retLength
- ).ThrowIf();
+ );
+
+ if (status >= NtStatus.Error)
+ Win32.Throw(status);
return timeOfDay;
}
@@ -794,11 +821,15 @@ public static TimeSpan GetUptime()
/// The service name of the driver.
public static void LoadDriver(string serviceName)
{
- UnicodeString str = new UnicodeString("\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" + serviceName);
+ var str = new UnicodeString(
+ "\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" + serviceName);
try
{
- Win32.NtLoadDriver(ref str).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtLoadDriver(ref str)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -811,9 +842,12 @@ public static void LoadDriver(string serviceName)
///
/// A pointer to a KSYSTEM_TIME value.
/// A 64-bit time value.
- private unsafe static LargeInteger QueryKSystemTime(IntPtr time)
+ private static LargeInteger QueryKSystemTime(IntPtr time)
{
- return QueryKSystemTime((KSystemTime*)time);
+ unsafe
+ {
+ return QueryKSystemTime((KSystemTime*)time);
+ }
}
///
@@ -860,11 +894,15 @@ private unsafe static LargeInteger QueryKSystemTime(KSystemTime* time)
/// The service name of the driver.
public static void UnloadDriver(string serviceName)
{
- UnicodeString str = new UnicodeString("\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" + serviceName);
+ var str = new UnicodeString(
+ "\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" + serviceName);
try
{
- Win32.NtUnloadDriver(ref str).ThrowIf();
+ NtStatus status;
+
+ if ((status = Win32.NtUnloadDriver(ref str)) >= NtStatus.Error)
+ Win32.Throw(status);
}
finally
{
@@ -899,7 +937,7 @@ public struct NetworkConnection
public void CloseTcpConnection()
{
- MibTcpRow row = new MibTcpRow
+ MibTcpRow row = new MibTcpRow()
{
State = MibTcpState.DeleteTcb,
LocalAddress = (uint)this.Local.Address.Address,
@@ -907,7 +945,6 @@ public void CloseTcpConnection()
RemoteAddress = this.Remote != null ? (uint)this.Remote.Address.Address : 0,
RemotePort = this.Remote != null ? ((ushort)this.Remote.Port).Reverse() : 0
};
-
int result = Win32.SetTcpEntry(ref row);
if (result != 0)
diff --git a/1.x/trunk/ProcessHacker.Native/WindowsException.cs b/1.x/trunk/ProcessHacker.Native/WindowsException.cs
index 0c196795e..74dd7cfcd 100644
--- a/1.x/trunk/ProcessHacker.Native/WindowsException.cs
+++ b/1.x/trunk/ProcessHacker.Native/WindowsException.cs
@@ -35,10 +35,10 @@ namespace ProcessHacker.Native
///
public class WindowsException : Exception
{
- private readonly bool _isNtStatus;
- private readonly Win32Error _errorCode = 0;
- private readonly NtStatus _status;
- private string _message;
+ private bool _isNtStatus = false;
+ private Win32Error _errorCode = 0;
+ private NtStatus _status;
+ private string _message = null;
///
/// Creates an exception with no error.
@@ -99,7 +99,7 @@ public override string Message
{
// No locking, for performance reasons. Getting the
// message doesn't have any side-effects anyway.
- if (string.IsNullOrEmpty(_message))
+ if (_message == null)
{
// We prefer native status messages because they are usually
// more detailed. However, for some status values we do
@@ -113,7 +113,7 @@ public override string Message
{
string message = _status.GetMessage();
- if (string.IsNullOrEmpty(message))
+ if (message == null)
message = "Could not retrieve the error message (0x" + ((int)_status).ToString("x") + ").";
_message = message;
diff --git a/1.x/trunk/ProcessHacker.Native/app.config b/1.x/trunk/ProcessHacker.Native/app.config
index b4ca687d2..89dc7d426 100644
--- a/1.x/trunk/ProcessHacker.Native/app.config
+++ b/1.x/trunk/ProcessHacker.Native/app.config
@@ -1,3 +1,3 @@
-
+
diff --git a/1.x/trunk/ProcessHacker.sln b/1.x/trunk/ProcessHacker.sln
index b7f653106..fc6e4066e 100644
--- a/1.x/trunk/ProcessHacker.sln
+++ b/1.x/trunk/ProcessHacker.sln
@@ -1,12 +1,14 @@
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 2012
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProcessHacker", "ProcessHacker\ProcessHacker.csproj", "{EEEA1778-1702-4964-8793-A98FE37E4D2B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProcessHacker.Common", "ProcessHacker.Common\ProcessHacker.Common.csproj", "{8E10F5E8-D4FA-4980-BB23-2EDD134AC15E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProcessHacker.Native", "ProcessHacker.Native\ProcessHacker.Native.csproj", "{8A448157-E1A7-4DDF-954E-287F1117832B}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aga.Controls", "TreeViewAdv\Aga.Controls.csproj", "{E73BB233-D88B-44A7-A98F-D71EE158381D}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -25,6 +27,10 @@ Global
{8A448157-E1A7-4DDF-954E-287F1117832B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8A448157-E1A7-4DDF-954E-287F1117832B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8A448157-E1A7-4DDF-954E-287F1117832B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E73BB233-D88B-44A7-A98F-D71EE158381D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E73BB233-D88B-44A7-A98F-D71EE158381D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E73BB233-D88B-44A7-A98F-D71EE158381D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E73BB233-D88B-44A7-A98F-D71EE158381D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/1.x/trunk/ProcessHacker/Common/CircularBuffer.cs b/1.x/trunk/ProcessHacker/Common/CircularBuffer.cs
deleted file mode 100644
index 06e37d491..000000000
--- a/1.x/trunk/ProcessHacker/Common/CircularBuffer.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Collections;
-
-namespace ProcessHacker.Common
-{
- ///
- /// A Less than perfect CircularList.
- ///
- ///
- public class CircularList : IList
- {
- private List data = new List();
- public int Max;
-
- // TODO: rewrite entire class at some stage.
- public CircularList(int max)
- {
- this.Max = max;
- }
-
- public int Count { get { return data.Count; } }
-
- public T this[int index]
- {
- get { return this.data[index]; }
- set { this.data[index] = value; }
- }
-
- public void Add(T item)
- {
- //Less than perfect.
- if (this.data.Count >= this.Max)
- {
- this.data.RemoveRange(0, this.data.Count - this.Max);
-
- for (int i = 0; i <= this.data.Count - 2; i++)
- {
- this.data[i] = this.data[i + 1];
- }
- this.data[this.data.Count - 1] = item;
- }
- else
- {
- this.data.Add(item);
- }
- }
-
- public int IndexOf(T item)
- {
- throw new NotImplementedException();
- }
-
- public void Insert(int index, T item)
- {
- throw new NotImplementedException();
- }
-
- public void RemoveAt(int index)
- {
- throw new NotImplementedException();
- }
-
- public void Clear()
- {
- data.Clear();
- }
-
- public bool Contains(T item)
- {
- return data.Contains(item);
- }
-
- public void CopyTo(T[] array, int arrayIndex)
- {
- throw new NotImplementedException();
- }
-
- public bool IsReadOnly
- {
- get { throw new NotImplementedException(); }
- }
-
- public bool Remove(T item)
- {
- return data.Remove(item);
- }
-
- public IEnumerator GetEnumerator()
- {
- return data.GetEnumerator();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return data.GetEnumerator();
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Common/Extensions.cs b/1.x/trunk/ProcessHacker/Common/Extensions.cs
index caa1ee85c..7368f0440 100644
--- a/1.x/trunk/ProcessHacker/Common/Extensions.cs
+++ b/1.x/trunk/ProcessHacker/Common/Extensions.cs
@@ -22,20 +22,9 @@
using System;
using System.Collections.Generic;
-using System.Drawing;
-using System.Windows.Forms;
-using ProcessHacker.Native.Api;
namespace ProcessHacker.Common
{
- public static class StringExtensions
- {
- public static bool Contains(this string source, string toCheck, StringComparison comp)
- {
- return source.IndexOf(toCheck, comp) >= 0;
- }
- }
-
public static class LongExtensions
{
///
@@ -95,141 +84,4 @@ public static IList Take(this IList source, int count)
return newList;
}
}
-
- ///
- /// MeasureText cache.
- /// Cache the calls to MeasureText as this only needs to be called once.
- ///
- /// Invalidate the cache if UI changes (i.e. DPI)
- public static class TextSizeCache
- {
- private static readonly Dictionary SizeCache = new Dictionary();
-
- public static Size GetCachedSize(this Graphics device, string str, Font font)
- {
- if (SizeCache.ContainsKey(str))
- {
- return SizeCache[str];
- }
-
- // we only need to Measure the string once, so we cache it.
- Size strSize = TextRenderer.MeasureText(device, str, font);
-
- SizeCache.Add(str, strSize);
-
- return strSize;
- }
-
- public static void InvalidateCache()
- {
- SizeCache.Clear();
- }
- }
-
- public static class ControlExtensions
- {
- ///
- /// An application sends the WM_CHANGEUISTATE message to indicate that the UI state should be changed.
- ///
- /// Value: 0x0127
- public const int WM_CHANGEUISTATE = 295;
-
- ///
- /// An application sends the WM_UPDATEUISTATE message to change the UI state for the specified window and all its child windows.
- ///
- /// Value: 0x0128
- public const int WM_UPDATEUISTATE = 296;
-
- public enum UIS_Flags
- {
- ///
- /// The UI state flags specified by the high-order word should be set.
- ///
- UIS_SET = 1,
-
- ///
- /// The UI state flags specified by the high-order word should be cleared.
- ///
- UIS_CLEAR = 2,
-
- ///
- /// The UI state flags specified by the high-order word should be changed based on the last input event. For more information, see Remarks.
- ///
- UIS_INITIALIZE = 3
- }
-
- [Flags]
- public enum UISF_Flags
- {
- UISF_HIDEFOCUS = 0x1,
- UISF_HIDEACCEL = 0x2,
- UISF_ACTIVE = 0x4
- }
-
- public static void MakeAcceleratorsVisible(this Control c)
- {
- Win32.SendMessage(c.Handle, (WindowMessage)WM_CHANGEUISTATE, (IntPtr)MakeLong((int)UIS_Flags.UIS_CLEAR, (int)UISF_Flags.UISF_HIDEACCEL), IntPtr.Zero);
- }
-
- public static void MakeAcceleratorsInvisible(this Control c)
- {
- Win32.SendMessage(c.Handle, (WindowMessage)WM_CHANGEUISTATE, (IntPtr)MakeLong((int)UIS_Flags.UIS_SET, (int)UISF_Flags.UISF_HIDEACCEL), IntPtr.Zero);
- }
-
- public static void MakeFocusVisible(this Control c)
- {
- Win32.SendMessage(c.Handle, (WindowMessage)WM_CHANGEUISTATE, (IntPtr)MakeLong((int)UIS_Flags.UIS_CLEAR, (int)UISF_Flags.UISF_HIDEFOCUS), IntPtr.Zero);
- }
-
- public static void MakeFocusInvisible(this Control c)
- {
- Win32.SendMessage(c.Handle, (WindowMessage)WM_CHANGEUISTATE, (IntPtr)MakeLong((int)UIS_Flags.UIS_SET, (int)UISF_Flags.UISF_HIDEFOCUS), IntPtr.Zero);
- }
-
- public static void MakeActiveVisible(this Control c)
- {
- Win32.SendMessage(c.Handle, (WindowMessage)WM_CHANGEUISTATE, (IntPtr)MakeLong((int)UIS_Flags.UIS_SET, (int)UISF_Flags.UISF_ACTIVE), IntPtr.Zero);
- }
-
- public static void MakeActiveInvisible(this Control c)
- {
- Win32.SendMessage(c.Handle, (WindowMessage)WM_CHANGEUISTATE, (IntPtr)MakeLong((int)UIS_Flags.UIS_CLEAR, (int)UISF_Flags.UISF_ACTIVE), IntPtr.Zero);
- }
-
- private static int MakeLong(int loWord, int hiWord)
- {
- return (hiWord << 16) | (loWord & 0xffff);
- }
-
- public static int LoWord(int number)
- {
- return number & 0xffff;
- }
-
- //private int WM_CHANGEUISTATE = 0x127;
-
- //private enum WM_CHANGEUISTATE_low : short
- //{
- // UIS_CLEAR = 2,
- // UIS_INITIALIZE = 3,
- // UIS_SET = 1
- //}
-
- //private enum WM_CHANGEUISTATE_high : short
- //{
- // UISF_HIDEACCEL = 0x2,
- // UISF_HIDEFOCUS = 0x1,
- // UISF_ACTIVE = 4
- //}
-
- //private enum WM_CHANGEUISTATE : int
- //{
- // UIS_CLEAR = WM_CHANGEUISTATE_low.UIS_CLEAR,
- // UIS_INITIALIZE = WM_CHANGEUISTATE_low.UIS_INITIALIZE,
- // UIS_SET = WM_CHANGEUISTATE_low.UIS_SET,
- // UISF_HIDEACCEL = Convert.ToInt32(WM_CHANGEUISTATE_high.UISF_HIDEACCEL) << 16,
- // UISF_HIDEFOCUS = Convert.ToInt32(WM_CHANGEUISTATE_high.UISF_HIDEFOCUS) << 16,
- // UISF_ACTIVE = Convert.ToInt32(WM_CHANGEUISTATE_high.UISF_ACTIVE) << 16
- //}
- }
}
diff --git a/1.x/trunk/ProcessHacker/Common/PhUtils.cs b/1.x/trunk/ProcessHacker/Common/PhUtils.cs
index 8cf46b47c..f645511b2 100644
--- a/1.x/trunk/ProcessHacker/Common/PhUtils.cs
+++ b/1.x/trunk/ProcessHacker/Common/PhUtils.cs
@@ -31,14 +31,13 @@
using ProcessHacker.Native;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
-using ProcessHacker.Native.Security;
using ProcessHacker.UI;
namespace ProcessHacker.Common
{
public static class PhUtils
{
- public static readonly string[] DangerousNames =
+ public static string[] DangerousNames =
{
"csrss.exe", "dwm.exe", "logonui.exe", "lsass.exe", "lsm.exe", "services.exe",
"smss.exe", "wininit.exe", "winlogon.exe"
@@ -60,27 +59,28 @@ public static void AddShortcuts(this ListView lv)
/// A virtual item handler, if any.
public static void AddShortcuts(this ListView lv, RetrieveVirtualItemEventHandler retrieveVirtualItem)
{
- lv.KeyDown += (sender, e) =>
- {
- if (e.Control && e.KeyCode == Keys.A)
+ lv.KeyDown +=
+ (sender, e) =>
{
- if (retrieveVirtualItem != null)
+ if (e.Control && e.KeyCode == Keys.A)
{
- for (int i = 0; i < lv.VirtualListSize; i++)
- if (!lv.SelectedIndices.Contains(i))
- lv.SelectedIndices.Add(i);
+ if (retrieveVirtualItem != null)
+ {
+ for (int i = 0; i < lv.VirtualListSize; i++)
+ if (!lv.SelectedIndices.Contains(i))
+ lv.SelectedIndices.Add(i);
+ }
+ else
+ {
+ lv.Items.SelectAll();
+ }
}
- else
+
+ if (e.Control && e.KeyCode == Keys.C)
{
- lv.Items.SelectAll();
+ GenericViewMenu.ListViewCopy(lv, -1, retrieveVirtualItem);
}
- }
-
- if (e.Control && e.KeyCode == Keys.C)
- {
- GenericViewMenu.ListViewCopy(lv, -1, retrieveVirtualItem);
- }
- };
+ };
}
///
@@ -95,11 +95,13 @@ public static bool IsDangerousPid(int pid)
try
{
- using (ProcessHandle phandle = new ProcessHandle(pid, OSVersion.MinProcessQueryInfoAccess))
+ using (var phandle = new ProcessHandle(pid, OSVersion.MinProcessQueryInfoAccess))
{
foreach (string s in DangerousNames)
{
- if ((Environment.SystemDirectory + "\\" + s).Equals(FileUtils.GetFileName(FileUtils.GetFileName(phandle.ImageFileName)), StringComparison.OrdinalIgnoreCase))
+ if ((Environment.SystemDirectory + "\\" + s).Equals(
+ FileUtils.GetFileName(FileUtils.GetFileName(phandle.GetImageFileName())),
+ StringComparison.OrdinalIgnoreCase))
{
return true;
}
@@ -123,9 +125,9 @@ public static bool IsDangerousPid(int pid)
private static string FormatException(string operation, Exception ex)
{
if (!string.IsNullOrEmpty(operation))
- return operation + ": " + ex.Message + (ex.InnerException != null ? " (" + ex.InnerException.Message + ")" : string.Empty);
-
- return ex.Message + (ex.InnerException != null ? " (" + ex.InnerException.Message + ")" : string.Empty);
+ return operation + ": " + ex.Message + (ex.InnerException != null ? " (" + ex.InnerException.Message + ")" : "");
+ else
+ return ex.Message + (ex.InnerException != null ? " (" + ex.InnerException.Message + ")" : "");
}
public static string FormatFileInfo(
@@ -183,17 +185,18 @@ public static string FormatPriorityClass(ProcessPriorityClass priorityClass)
return "Normal";
case ProcessPriorityClass.RealTime:
return "Realtime";
+ case ProcessPriorityClass.Unknown:
default:
- return string.Empty;
+ return "";
}
}
public static string GetBestUserName(string userName, bool includeDomain)
{
- if (string.IsNullOrEmpty(userName))
- return string.Empty;
+ if (userName == null)
+ return "";
- if (!userName.Contains("\\", StringComparison.OrdinalIgnoreCase))
+ if (!userName.Contains("\\"))
return userName;
string[] split = userName.Split(new char[] { '\\' }, 2);
@@ -202,8 +205,8 @@ public static string GetBestUserName(string userName, bool includeDomain)
if (includeDomain)
return domain + "\\" + user;
-
- return user;
+ else
+ return user;
}
///
@@ -219,8 +222,8 @@ public static Color GetForeColor(Color backColor)
{
if (backColor.GetBrightness() > 0.4)
return Color.Black;
-
- return Color.White;
+ else
+ return Color.White;
}
public static IWin32Window GetForegroundWindow()
@@ -228,49 +231,40 @@ public static IWin32Window GetForegroundWindow()
var window = WindowHandle.GetForegroundWindow();
// Make sure the foreground window belongs to us.
- if (window.ClientId.ProcessId == ProcessHandle.CurrentId)
+ if (window.GetClientId().ProcessId == ProcessHandle.GetCurrentId())
return window;
-
- return new WindowFromHandle(Program.HackerWindowHandle);
+ else
+ return new WindowFromHandle(Program.HackerWindowHandle);
}
public static string GetIntegrity(this TokenHandle tokenHandle, out int integrityLevel)
{
- var groups = tokenHandle.Groups;
+ var groups = tokenHandle.GetGroups();
string integrity = null;
integrityLevel = 0;
- foreach (Sid t in groups)
+ for (int i = 0; i < groups.Length; i++)
{
- if ((t.Attributes & SidAttributes.IntegrityEnabled) != 0)
+ if ((groups[i].Attributes & SidAttributes.IntegrityEnabled) != 0)
{
- integrity = t.GetFullName(false).Replace(" Mandatory Level", string.Empty);
-
- switch (integrity)
- {
- case "Untrusted":
- integrityLevel = 0;
- break;
- case "Low":
- integrityLevel = 1;
- break;
- case "Medium":
- integrityLevel = 2;
- break;
- case "High":
- integrityLevel = 3;
- break;
- case "System":
- integrityLevel = 4;
- break;
- case "Installer":
- integrityLevel = 5;
- break;
- }
+ integrity = groups[i].GetFullName(false).Replace(" Mandatory Level", "");
+
+ if (integrity == "Untrusted")
+ integrityLevel = 0;
+ else if (integrity == "Low")
+ integrityLevel = 1;
+ else if (integrity == "Medium")
+ integrityLevel = 2;
+ else if (integrity == "High")
+ integrityLevel = 3;
+ else if (integrity == "System")
+ integrityLevel = 4;
+ else if (integrity == "Installer")
+ integrityLevel = 5;
}
- t.Dispose();
+ groups[i].Dispose();
}
return integrity;
@@ -350,7 +344,7 @@ public static bool IsInternetConnected()
{
try
{
- IPHostEntry entry = Dns.GetHostEntry("www.msftncsi.com");
+ System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry("www.msftncsi.com");
return true;
//http://www.msftncsi.com/ncsi.txt
@@ -399,13 +393,13 @@ public static void OpenKeyInRegedit(IWin32Window window, string keyName)
string lastKey = keyName;
// Expand the abbreviations.
- if (lastKey.StartsWith("hkcu", StringComparison.OrdinalIgnoreCase))
+ if (lastKey.ToLowerInvariant().StartsWith("hkcu"))
lastKey = "HKEY_CURRENT_USER" + lastKey.Substring(4);
- else if (lastKey.StartsWith("hku", StringComparison.OrdinalIgnoreCase))
+ else if (lastKey.ToLowerInvariant().StartsWith("hku"))
lastKey = "HKEY_USERS" + lastKey.Substring(3);
- else if (lastKey.StartsWith("hkcr", StringComparison.OrdinalIgnoreCase))
+ else if (lastKey.ToLowerInvariant().StartsWith("hkcr"))
lastKey = "HKEY_CLASSES_ROOT" + lastKey.Substring(4);
- else if (lastKey.StartsWith("hklm", StringComparison.OrdinalIgnoreCase))
+ else if (lastKey.ToLowerInvariant().StartsWith("hklm"))
lastKey = "HKEY_LOCAL_MACHINE" + lastKey.Substring(4);
// Set the last opened key in regedit config. Note that if we are on
@@ -431,7 +425,7 @@ public static void OpenKeyInRegedit(IWin32Window window, string keyName)
{
Program.StartProgramAdmin(
Environment.SystemDirectory + "\\..\\regedit.exe",
- string.Empty,
+ "",
null,
ShowWindowType.Normal,
window != null ? window.Handle : IntPtr.Zero
@@ -459,7 +453,21 @@ public static void SelectAll(this IEnumerable nodes)
/// Whether the shield icon is visible.
public static void SetShieldIcon(this Button button, bool visible)
{
- Win32.SendMessage(button.Handle, WindowMessage.BcmSetShield, IntPtr.Zero, visible ? (IntPtr)1 : IntPtr.Zero);
+ Win32.SendMessage(button.Handle, WindowMessage.BcmSetShield, 0, visible ? 1 : 0);
+ }
+
+ ///
+ /// Sets the theme of a control.
+ ///
+ /// The control to modify.
+ /// A name of a theme.
+ public static void SetTheme(this Control control, string theme)
+ {
+ // Don't set on XP, doesn't look better than without SetWindowTheme.
+ if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
+ {
+ Win32.SetWindowTheme(control.Handle, theme, null);
+ }
}
///
@@ -500,13 +508,11 @@ public static bool ShowConfirmMessage(string verb, string obj, string message, b
if (OSVersion.HasTaskDialogs)
{
- TaskDialog td = new TaskDialog
- {
- WindowTitle = "Process Hacker",
- MainIcon = warning ? TaskDialogIcon.Warning : TaskDialogIcon.None,
- MainInstruction = "Do you want to " + action + "?",
- PositionRelativeToWindow = true
- };
+ TaskDialog td = new TaskDialog();
+
+ td.WindowTitle = "Process Hacker";
+ td.MainIcon = warning ? TaskDialogIcon.Warning : TaskDialogIcon.None;
+ td.MainInstruction = "Do you want to " + action + "?";
if (!string.IsNullOrEmpty(message))
td.Content = message + " Are you sure you want to continue?";
@@ -518,15 +524,17 @@ public static bool ShowConfirmMessage(string verb, string obj, string message, b
};
td.DefaultButton = (int)DialogResult.No;
- return td.Show(GetForegroundWindow()) == (int)DialogResult.Yes;
+ return td.Show(PhUtils.GetForegroundWindow()) == (int)DialogResult.Yes;
+ }
+ else
+ {
+ return MessageBox.Show(
+ message + " Are you sure you want to " + action + "?",
+ "Process Hacker",
+ MessageBoxButtons.YesNo,
+ MessageBoxIcon.Warning
+ ) == DialogResult.Yes;
}
-
- return MessageBox.Show(
- message + " Are you sure you want to " + action + "?",
- "Process Hacker",
- MessageBoxButtons.YesNo,
- MessageBoxIcon.Warning
- ) == DialogResult.Yes;
}
///
@@ -573,7 +581,7 @@ public static void ShowException(string operation, Exception ex)
#else
MessageBox.Show(
PhUtils.GetForegroundWindow(),
- operation + "\n\n" + ex,
+ operation + "\n\n" + ex.ToString(),
"Process Hacker",
MessageBoxButtons.OK,
MessageBoxIcon.Error
diff --git a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DataMap.cs b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DataMap.cs
index 46fc12ef7..f8fbccfcd 100644
--- a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DataMap.cs
+++ b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DataMap.cs
@@ -249,10 +249,10 @@ public IEnumerator GetEnumerator()
#region Enumerator Nested Type
internal class Enumerator : IEnumerator, IDisposable
{
- readonly DataMap _map;
+ DataMap _map;
DataBlock _current;
int _index;
- readonly int _version;
+ int _version;
internal Enumerator(DataMap map)
{
diff --git a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/Design/HexFontEditor.cs b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/Design/HexFontEditor.cs
index cb4312b0e..e7bba5675 100644
--- a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/Design/HexFontEditor.cs
+++ b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/Design/HexFontEditor.cs
@@ -13,7 +13,14 @@ internal class HexFontEditor : FontEditor
{
object value;
- ///
+ ///
+ /// Initializes an instance of HexFontEditor class.
+ ///
+ public HexFontEditor()
+ {
+ }
+
+ ///
/// Edits the value
///
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
@@ -24,18 +31,16 @@ public override object EditValue(System.ComponentModel.ITypeDescriptorContext co
IWindowsFormsEditorService service1 = (IWindowsFormsEditorService) provider.GetService(typeof(IWindowsFormsEditorService));
if (service1 != null)
{
- FontDialog fontDialog = new FontDialog
- {
- ShowApply = false,
- ShowColor = false,
- AllowVerticalFonts = false,
- AllowScriptChange = false,
- FixedPitchOnly = true,
- ShowEffects = false,
- ShowHelp = false
- };
-
- Font font = value as Font;
+ FontDialog fontDialog = new FontDialog();
+ fontDialog.ShowApply = false;
+ fontDialog.ShowColor = false;
+ fontDialog.AllowVerticalFonts = false;
+ fontDialog.AllowScriptChange = false;
+ fontDialog.FixedPitchOnly = true;
+ fontDialog.ShowEffects = false;
+ fontDialog.ShowHelp = false;
+
+ Font font = value as Font;
if(font != null)
{
fontDialog.Font = font;
@@ -52,11 +57,14 @@ public override object EditValue(System.ComponentModel.ITypeDescriptorContext co
value = this.value;
this.value = null;
return value;
+
}
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
+
+
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DynamicByteProvider.cs b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DynamicByteProvider.cs
index 3d79b4ce6..7d09177c0 100644
--- a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DynamicByteProvider.cs
+++ b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/DynamicByteProvider.cs
@@ -14,7 +14,7 @@ public class DynamicByteProvider : IByteProvider
///
/// Contains a byte collection.
///
- readonly ByteCollection _bytes;
+ ByteCollection _bytes;
///
/// Initializes a new instance of the DynamicByteProvider class.
diff --git a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/FileByteProvider.cs b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/FileByteProvider.cs
index e59f0aa67..6ae12babc 100644
--- a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/FileByteProvider.cs
+++ b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/FileByteProvider.cs
@@ -53,7 +53,7 @@ public bool Contains(long index)
///
/// Contains all changes
///
- readonly WriteCollection _writes = new WriteCollection();
+ WriteCollection _writes = new WriteCollection();
///
/// Contains the file name.
@@ -66,7 +66,7 @@ public bool Contains(long index)
///
/// Read-only access.
///
- readonly bool _readOnly;
+ bool _readOnly;
///
/// Initializes a new instance of the FileByteProvider class.
diff --git a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/HexBox.cs b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/HexBox.cs
index 1f2371657..6aa75f59f 100644
--- a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/HexBox.cs
+++ b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/HexBox.cs
@@ -1,11 +1,11 @@
using System;
using System.Drawing;
using System.Windows.Forms;
+using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Security.Permissions;
using System.Windows.Forms.VisualStyles;
using Be.Windows.Forms.Design;
-using ProcessHacker;
namespace Be.Windows.Forms
{
@@ -41,16 +41,12 @@ public BytePositionInfo(long index, int characterPosition)
public int CharacterPosition
{
get { return _characterPosition; }
- }
-
- readonly int _characterPosition;
+ } int _characterPosition;
public long Index
{
get { return _index; }
- }
-
- readonly long _index;
+ } long _index;
}
#endregion
@@ -108,7 +104,7 @@ interface IKeyInterpreter
///
class EmptyKeyInterpreter : IKeyInterpreter
{
- readonly HexBox _hexBox;
+ HexBox _hexBox;
public EmptyKeyInterpreter(HexBox hexBox)
{
@@ -145,12 +141,12 @@ class KeyInterpreter : IKeyInterpreter
///
/// Contains the parent HexBox control
///
- protected readonly HexBox _hexBox;
+ protected HexBox _hexBox;
///
/// Contains True, if shift key is down
///
- bool _shiftDown;
+ protected bool _shiftDown;
///
/// Contains True, if mouse is down
///
@@ -824,9 +820,11 @@ protected bool RaiseKeyPress(char keyChar)
#region PreProcessWmKeyUp methods
public virtual bool PreProcessWmKeyUp(ref Message m)
{
+ System.Diagnostics.Debug.WriteLine("PreProcessWmKeyUp(ref Message m)", "KeyInterpreter");
+
Keys vc = (Keys)m.WParam.ToInt32();
- Keys keyData = vc | ModifierKeys;
+ Keys keyData = vc | Control.ModifierKeys;
switch(keyData)
{
@@ -856,7 +854,7 @@ protected virtual bool PreProcessWmKeyUp_Insert(ref Message m)
return true;
}
- private bool RaiseKeyUp(Keys keyData)
+ protected bool RaiseKeyUp(Keys keyData)
{
KeyEventArgs e = new KeyEventArgs(keyData);
_hexBox.OnKeyUp(e);
@@ -974,12 +972,13 @@ protected virtual bool PerformPosMoveLeftByte()
protected virtual bool PerformPosMoveRightByte()
{
long pos = _hexBox._bytePos;
+ int cp = _hexBox._byteCharacterPos;
- if(pos == _hexBox._byteProvider.Length)
+ if(pos == _hexBox._byteProvider.Length)
return true;
pos = Math.Min(_hexBox._byteProvider.Length, pos+1);
- int cp = 0;
+ cp = 0;
_hexBox.SetPosition(pos, cp);
@@ -1159,7 +1158,7 @@ protected override BytePositionInfo GetBytePositionInfo(Point p)
///
/// Contains string format information for text drawing
///
- readonly StringFormat _stringFormat;
+ StringFormat _stringFormat;
///
/// Contains the width and height of a single char
///
@@ -1193,11 +1192,11 @@ protected override BytePositionInfo GetBytePositionInfo(Point p)
///
/// Contains a vertical scroll
///
- readonly VScrollBar _vScrollBar;
+ VScrollBar _vScrollBar;
///
/// Contains a timer for thumbtrack scrolling
///
- readonly Timer _thumbTrackTimer = new Timer();
+ Timer _thumbTrackTimer = new Timer();
///
/// Contains the thumbtrack scrolling position
///
@@ -1383,22 +1382,22 @@ protected override BytePositionInfo GetBytePositionInfo(Point p)
public HexBox()
{
this._vScrollBar = new VScrollBar();
- this._vScrollBar.Scroll += this._vScrollBar_Scroll;
+ this._vScrollBar.Scroll += new ScrollEventHandler(_vScrollBar_Scroll);
- this.BackColor = Color.White;
- this.Font = Settings.Instance.Font;
+ BackColor = Color.White;
+ Font = new Font("Courier New", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
+ _stringFormat = new StringFormat(StringFormat.GenericTypographic);
+ _stringFormat.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
- this._stringFormat = new StringFormat(StringFormat.GenericTypographic)
- {
- FormatFlags = StringFormatFlags.MeasureTrailingSpaces
- };
-
- this.ActivateEmptyKeyInterpreter();
-
- this.SetStyle(ControlStyles.UserPaint | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
+ ActivateEmptyKeyInterpreter();
+
+ SetStyle(ControlStyles.UserPaint, true);
+ SetStyle(ControlStyles.DoubleBuffer, true);
+ SetStyle(ControlStyles.AllPaintingInWmPaint, true);
+ SetStyle(ControlStyles.ResizeRedraw, true);
- _thumbTrackTimer.Interval = 1000;
- _thumbTrackTimer.Tick += this.PerformScrollThumbTrack;
+ _thumbTrackTimer.Interval = 50;
+ _thumbTrackTimer.Tick += new EventHandler(PerformScrollThumbTrack);
}
#endregion
@@ -1434,7 +1433,7 @@ void _vScrollBar_Scroll(object sender, ScrollEventArgs e)
_thumbTrackTimer.Enabled = false;
// perform scroll immediately only if last refresh is very old
- int currentThumbTrack = Environment.TickCount;
+ int currentThumbTrack = System.Environment.TickCount;
if (currentThumbTrack - _lastThumbtrack > THUMPTRACKDELAY)
{
PerformScrollThumbTrack(null, null);
@@ -1448,6 +1447,8 @@ void _vScrollBar_Scroll(object sender, ScrollEventArgs e)
break;
case ScrollEventType.First:
break;
+ default:
+ break;
}
e.NewValue = ToScrollPos(_scrollVpos);
@@ -1470,7 +1471,7 @@ void UpdateScrollSize()
// calc scroll bar info
if(VScrollBarVisible && _byteProvider != null && _byteProvider.Length > 0 && _iHexMaxHBytes != 0)
{
- long scrollmax = (long)Math.Ceiling(this._byteProvider.Length / (double)_iHexMaxHBytes - this._iHexMaxVBytes);
+ long scrollmax = (long)Math.Ceiling((double)_byteProvider.Length / (double)_iHexMaxHBytes - (double)_iHexMaxVBytes);
scrollmax = Math.Max(0, scrollmax);
long scrollpos = _startByte / _iHexMaxHBytes;
@@ -1533,11 +1534,14 @@ long FromScrollPos(int value)
int max = 65535;
if(_scrollVmax < max)
{
- return value;
+ return (long)value;
+ }
+ else
+ {
+ double valperc = (double)value / (double)max * (double)100;
+ long res = (int)Math.Floor((double)_scrollVmax / (double)100 * valperc);
+ return res;
}
- double valperc = (double)value / (double)max * (double)100;
- long res = (int)Math.Floor((double)this._scrollVmax / (double)100 * valperc);
- return res;
}
int ToScrollMax(long value)
@@ -1545,7 +1549,8 @@ int ToScrollMax(long value)
long max = 65535;
if(value > max)
return (int)max;
- return (int)value;
+ else
+ return (int)value;
}
void PerformScrollToLine(long pos)
@@ -1636,12 +1641,12 @@ public void ScrollByteIntoView(long index)
if(index < _startByte)
{
- long line = (long)Math.Floor(index / (double)_iHexMaxHBytes);
+ long line = (long)Math.Floor((double)index / (double)_iHexMaxHBytes);
PerformScrollThumpPosition(line);
}
else if(index > _endByte)
{
- long line = (long)Math.Floor(index / (double)_iHexMaxHBytes);
+ long line = (long)Math.Floor((double)index / (double)_iHexMaxHBytes);
line -= _iHexMaxVBytes-1;
PerformScrollThumpPosition(line);
}
@@ -1791,8 +1796,8 @@ void SetCaretPosition(Point p)
if(_byteProvider == null || _keyInterpreter == null)
return;
- long pos;
- int cp;
+ long pos = _bytePos;
+ int cp = _byteCharacterPos;
if(_recHex.Contains(p))
{
@@ -2057,16 +2062,16 @@ public void Paste()
if(_selectionLength > 0)
_byteProvider.DeleteBytes(_bytePos, _selectionLength);
- byte[] buffer;
+ byte[] buffer = null;
IDataObject da = Clipboard.GetDataObject();
- if(da != null && da.GetDataPresent("BinaryData"))
+ if(da.GetDataPresent("BinaryData"))
{
System.IO.MemoryStream ms = (System.IO.MemoryStream)da.GetData("BinaryData");
buffer = new byte[ms.Length];
ms.Read(buffer, 0, buffer.Length);
}
- else if(da != null && da.GetDataPresent(typeof(string)))
+ else if(da.GetDataPresent(typeof(string)))
{
string sBuffer = (string)da.GetData(typeof(string));
buffer = System.Text.Encoding.ASCII.GetBytes(sBuffer);
@@ -2102,9 +2107,10 @@ public bool CanPaste()
IDataObject da = Clipboard.GetDataObject();
if(da.GetDataPresent("BinaryData"))
return true;
- if(da.GetDataPresent(typeof(string)))
- return true;
- return false;
+ else if(da.GetDataPresent(typeof(string)))
+ return true;
+ else
+ return false;
}
#endregion
@@ -2405,7 +2411,7 @@ void PaintCurrentBytesSign(Graphics g)
Rectangle betweenLines = new Rectangle(
_recStringView.X,
(int)(startSelPointF.Y+_charSize.Height),
- this._recStringView.Width,
+ (int)(_recStringView.Width),
(int)(_charSize.Height*(multiLine-1)));
if(betweenLines.IntersectsWith(_recStringView))
{
@@ -2527,18 +2533,18 @@ void PaintCurrentByteSign(Graphics g, Rectangle rec)
Color GetDefaultForeColor()
{
- if(Enabled)
+ if(Enabled)
return ForeColor;
- return Color.Gray;
+ else
+ return Color.Gray;
}
-
- void UpdateVisibilityBytes()
+ void UpdateVisibilityBytes()
{
if(_byteProvider == null || _byteProvider.Length == 0)
return;
_startByte = (_scrollVpos+1) * _iHexMaxHBytes - _iHexMaxHBytes;
- _endByte = Math.Min(this._byteProvider.Length - 1, this._startByte + this._iHexMaxBytes);
+ _endByte = (long)Math.Min(_byteProvider.Length - 1, _startByte + _iHexMaxBytes);
}
#endregion
@@ -2847,11 +2853,11 @@ public IByteProvider ByteProvider
ActivateKeyInterpreter();
if(_byteProvider != null)
- _byteProvider.LengthChanged -= this._byteProvider_LengthChanged;
+ _byteProvider.LengthChanged -= new EventHandler(_byteProvider_LengthChanged);
_byteProvider = value;
if(_byteProvider != null)
- _byteProvider.LengthChanged += this._byteProvider_LengthChanged;
+ _byteProvider.LengthChanged += new EventHandler(_byteProvider_LengthChanged);
OnByteProviderChanged(EventArgs.Empty);
@@ -2967,13 +2973,14 @@ public bool StringViewVisible
[DefaultValue(typeof(HexCasing), "Upper"), Category("Hex"), Description("Gets or sets whether the HexBox control displays the hex characters in upper or lower case.")]
public HexCasing HexCasing
{
- get
- {
- if(_hexStringFormat == "X")
+ get
+ {
+ if(_hexStringFormat == "X")
return HexCasing.Upper;
- return HexCasing.Lower;
+ else
+ return HexCasing.Lower;
}
- set
+ set
{
string format;
if(value == HexCasing.Upper)
@@ -3181,7 +3188,7 @@ void SetVerticalByteCount(int value)
void CheckCurrentLineChanged()
{
- long currentLine = (long)Math.Floor(this._bytePos / (double)_iHexMaxHBytes) + 1;
+ long currentLine = (long)Math.Floor((double)_bytePos / (double)_iHexMaxHBytes) + 1;
if(_byteProvider == null && _currentLine != 0)
{
diff --git a/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/HexBox.snk b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/HexBox.snk
new file mode 100644
index 000000000..8c596985e
Binary files /dev/null and b/1.x/trunk/ProcessHacker/Components/Be.Windows.Forms.HexBox/HexBox.snk differ
diff --git a/1.x/trunk/ProcessHacker/Components/ColorModifier.Designer.cs b/1.x/trunk/ProcessHacker/Components/ColorModifier.Designer.cs
index 0be86b651..e88d39489 100644
--- a/1.x/trunk/ProcessHacker/Components/ColorModifier.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/ColorModifier.Designer.cs
@@ -39,15 +39,14 @@ private void InitializeComponent()
this.panelColor.Name = "panelColor";
this.panelColor.Size = new System.Drawing.Size(40, 20);
this.panelColor.TabIndex = 0;
+ this.panelColor.MouseLeave += new System.EventHandler(this.panelColor_MouseLeave);
this.panelColor.Click += new System.EventHandler(this.panelColor_Click);
this.panelColor.MouseEnter += new System.EventHandler(this.panelColor_MouseEnter);
- this.panelColor.MouseLeave += new System.EventHandler(this.panelColor_MouseLeave);
//
// ColorModifier
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.panelColor);
this.Name = "ColorModifier";
this.Size = new System.Drawing.Size(40, 20);
diff --git a/1.x/trunk/ProcessHacker/Components/ColorModifier.cs b/1.x/trunk/ProcessHacker/Components/ColorModifier.cs
index 4e6927682..ee93afa12 100644
--- a/1.x/trunk/ProcessHacker/Components/ColorModifier.cs
+++ b/1.x/trunk/ProcessHacker/Components/ColorModifier.cs
@@ -21,7 +21,10 @@
*/
using System;
+using System.Collections.Generic;
+using System.ComponentModel;
using System.Drawing;
+using System.Text;
using System.Windows.Forms;
namespace ProcessHacker.Components
@@ -39,20 +42,18 @@ public ColorModifier()
private void panelColor_Click(object sender, EventArgs e)
{
- using (ColorDialog cd = new ColorDialog
- {
- Color = this.panelColor.BackColor,
- FullOpen = true
- })
+ ColorDialog cd = new ColorDialog();
+
+ cd.Color = panelColor.BackColor;
+ cd.FullOpen = true;
+
+ if (cd.ShowDialog() == DialogResult.OK)
{
- if (cd.ShowDialog() == DialogResult.OK)
- {
- _color = cd.Color;
- panelColor.BackColor = cd.Color;
+ _color = cd.Color;
+ panelColor.BackColor = cd.Color;
- if (this.ColorChanged != null)
- this.ColorChanged(this, new EventArgs());
- }
+ if (this.ColorChanged != null)
+ this.ColorChanged(this, new EventArgs());
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/ColorModifier.resx b/1.x/trunk/ProcessHacker/Components/ColorModifier.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/ColorModifier.resx
+++ b/1.x/trunk/ProcessHacker/Components/ColorModifier.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/DotNetCounters.Designer.cs b/1.x/trunk/ProcessHacker/Components/DotNetCounters.Designer.cs
index 69f9ea0de..5e04438ee 100644
--- a/1.x/trunk/ProcessHacker/Components/DotNetCounters.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/DotNetCounters.Designer.cs
@@ -29,12 +29,12 @@ protected override void Dispose(bool disposing)
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
- this.listAppDomains = new ProcessHacker.Components.ExtendedListView();
+ this.listAppDomains = new System.Windows.Forms.ListView();
this.label2 = new System.Windows.Forms.Label();
this.comboCategories = new System.Windows.Forms.ComboBox();
- this.listValues = new ProcessHacker.Components.ExtendedListView();
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnValue = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.listValues = new System.Windows.Forms.ListView();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnValue = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// label1
@@ -48,9 +48,8 @@ private void InitializeComponent()
//
// listAppDomains
//
- this.listAppDomains.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.listAppDomains.DoubleClickChecks = true;
+ this.listAppDomains.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.listAppDomains.FullRowSelect = true;
this.listAppDomains.HideSelection = false;
this.listAppDomains.Location = new System.Drawing.Point(9, 19);
@@ -73,8 +72,8 @@ private void InitializeComponent()
//
// comboCategories
//
- this.comboCategories.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.comboCategories.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.comboCategories.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboCategories.FormattingEnabled = true;
this.comboCategories.Location = new System.Drawing.Point(72, 105);
@@ -85,13 +84,12 @@ private void InitializeComponent()
//
// listValues
//
- this.listValues.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.listValues.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.listValues.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnName,
this.columnValue});
- this.listValues.DoubleClickChecks = true;
this.listValues.FullRowSelect = true;
this.listValues.HideSelection = false;
this.listValues.Location = new System.Drawing.Point(9, 132);
@@ -116,7 +114,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listValues);
this.Controls.Add(this.comboCategories);
this.Controls.Add(this.label2);
@@ -133,10 +130,10 @@ private void InitializeComponent()
#endregion
private System.Windows.Forms.Label label1;
- private ExtendedListView listAppDomains;
+ private System.Windows.Forms.ListView listAppDomains;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox comboCategories;
- private ExtendedListView listValues;
+ private System.Windows.Forms.ListView listValues;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ColumnHeader columnValue;
}
diff --git a/1.x/trunk/ProcessHacker/Components/DotNetCounters.cs b/1.x/trunk/ProcessHacker/Components/DotNetCounters.cs
index ceaa7ef47..18ae62db3 100644
--- a/1.x/trunk/ProcessHacker/Components/DotNetCounters.cs
+++ b/1.x/trunk/ProcessHacker/Components/DotNetCounters.cs
@@ -32,9 +32,9 @@ namespace ProcessHacker.Components
{
public partial class DotNetCounters : UserControl
{
- private readonly int _pid;
- private bool _initialized;
- private readonly string _name;
+ private int _pid;
+ private bool _initialized = false;
+ private string _name;
private string _instanceName;
private string _categoryName;
private PerformanceCounter[] _counters;
@@ -43,6 +43,10 @@ public DotNetCounters(int pid, string name)
{
InitializeComponent();
+ listAppDomains.SetTheme("explorer");
+
+ listValues.SetDoubleBuffered(true);
+ listValues.SetTheme("explorer");
listValues.ContextMenu = listValues.GetCopyMenu();
listValues.AddShortcuts();
@@ -121,7 +125,7 @@ public void Initialize()
foreach (var category in categories)
{
- if (category.CategoryName.StartsWith(".NET CLR", StringComparison.OrdinalIgnoreCase))
+ if (category.CategoryName.StartsWith(".NET CLR"))
names.Add(category.CategoryName);
}
@@ -157,19 +161,22 @@ private void UpdateCounters()
return;
}
- foreach (PerformanceCounter t in this._counters)
+ for (int i = 0; i < _counters.Length; i++)
{
+ var counter = _counters[i];
+
if (
- (t.CounterType == PerformanceCounterType.NumberOfItems32 ||
- t.CounterType == PerformanceCounterType.NumberOfItems64 ||
- t.CounterType == PerformanceCounterType.RawFraction) &&
- t.CounterName != "Not Displayed"
+ (counter.CounterType == PerformanceCounterType.NumberOfItems32 ||
+ counter.CounterType == PerformanceCounterType.NumberOfItems64 ||
+ counter.CounterType == PerformanceCounterType.RawFraction) &&
+ counter.CounterName != "Not Displayed"
)
{
- this.listValues.Items.Add(new ListViewItem(new string[]
+ listValues.Items.Add(new ListViewItem(
+ new string[]
{
- t.CounterName,
- string.Empty
+ _counters[i].CounterName,
+ ""
}));
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/DotNetCounters.resx b/1.x/trunk/ProcessHacker/Components/DotNetCounters.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/DotNetCounters.resx
+++ b/1.x/trunk/ProcessHacker/Components/DotNetCounters.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/EventPairProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/EventPairProperties.Designer.cs
index 51ccce3c6..b553dbdec 100644
--- a/1.x/trunk/ProcessHacker/Components/EventPairProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/EventPairProperties.Designer.cs
@@ -61,7 +61,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.buttonSetLow);
this.Controls.Add(this.buttonSetHigh);
this.Name = "EventPairProperties";
diff --git a/1.x/trunk/ProcessHacker/Components/EventPairProperties.cs b/1.x/trunk/ProcessHacker/Components/EventPairProperties.cs
index e01514a8e..e704736ca 100644
--- a/1.x/trunk/ProcessHacker/Components/EventPairProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/EventPairProperties.cs
@@ -7,7 +7,7 @@ namespace ProcessHacker.Components
{
public partial class EventPairProperties : UserControl
{
- private readonly EventPairHandle _eventPairHandle;
+ private EventPairHandle _eventPairHandle;
public EventPairProperties(EventPairHandle eventPairHandle)
{
diff --git a/1.x/trunk/ProcessHacker/Components/EventPairProperties.resx b/1.x/trunk/ProcessHacker/Components/EventPairProperties.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/EventPairProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/EventPairProperties.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/EventProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/EventProperties.Designer.cs
index 820b08667..5d06e00bb 100644
--- a/1.x/trunk/ProcessHacker/Components/EventProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/EventProperties.Designer.cs
@@ -125,7 +125,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.White;
this.Controls.Add(this.buttonReset);
this.Controls.Add(this.buttonPulse);
this.Controls.Add(this.buttonSet);
diff --git a/1.x/trunk/ProcessHacker/Components/EventProperties.cs b/1.x/trunk/ProcessHacker/Components/EventProperties.cs
index 8a3529caa..3b57c78bf 100644
--- a/1.x/trunk/ProcessHacker/Components/EventProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/EventProperties.cs
@@ -1,7 +1,6 @@
using System;
using System.Windows.Forms;
using ProcessHacker.Common;
-using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
@@ -9,7 +8,7 @@ namespace ProcessHacker.Components
{
public partial class EventProperties : UserControl
{
- private readonly EventHandle _eventHandle;
+ private EventHandle _eventHandle;
public EventProperties(EventHandle eventHandle)
{
@@ -22,7 +21,7 @@ public EventProperties(EventHandle eventHandle)
private void UpdateInfo()
{
- EventBasicInformation basicInfo = _eventHandle.BasicInformation;
+ var basicInfo = _eventHandle.GetBasicInformation();
labelType.Text = basicInfo.EventType.ToString();
labelSignaled.Text = (basicInfo.EventState != 0).ToString();
@@ -43,11 +42,11 @@ private void TryExecute(MethodInvoker action)
private void UpgradeExecute(MethodInvoker action)
{
this.TryExecute(() =>
- {
- _eventHandle.ChangeAccess(EventAccess.QueryState | EventAccess.ModifyState);
+ {
+ _eventHandle.ChangeAccess(EventAccess.QueryState | EventAccess.ModifyState);
- action();
- });
+ action();
+ });
}
private void buttonSet_Click(object sender, EventArgs e)
@@ -64,7 +63,7 @@ private void buttonPulse_Click(object sender, EventArgs e)
private void buttonClear_Click(object sender, EventArgs e)
{
- this.UpgradeExecute(_eventHandle.Clear);
+ this.UpgradeExecute(() => _eventHandle.Clear());
this.UpdateInfo();
}
diff --git a/1.x/trunk/ProcessHacker/Components/EventProperties.resx b/1.x/trunk/ProcessHacker/Components/EventProperties.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/EventProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/EventProperties.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/ExtendedListView.cs b/1.x/trunk/ProcessHacker/Components/ExtendedListView.cs
index 23871072a..26b4f9c19 100644
--- a/1.x/trunk/ProcessHacker/Components/ExtendedListView.cs
+++ b/1.x/trunk/ProcessHacker/Components/ExtendedListView.cs
@@ -31,7 +31,6 @@
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
-using ProcessHacker.Common;
using ProcessHacker.Native;
using ProcessHacker.Native.Api;
@@ -41,7 +40,7 @@ namespace ProcessHacker.Components
public sealed class LinkClickedEventArgs : EventArgs
{
- private readonly ListViewGroup _group;
+ private ListViewGroup _group;
public LinkClickedEventArgs(ListViewGroup group)
{
@@ -54,7 +53,7 @@ public ListViewGroup Group
}
}
- public sealed class ExtendedListView : ListView
+ public class ExtendedListView : ListView
{
#region Control Variables
@@ -85,17 +84,6 @@ public ExtendedListView()
// Windows messages before they get to the form's WndProc.
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
- protected override void OnHandleCreated(EventArgs e)
- {
- base.OnHandleCreated(e);
-
- if (OSVersion.IsAbove(WindowsVersion.XP))
- {
- Win32.SetWindowTheme(this.Handle, "Explorer", null);
- }
-
- this.MakeFocusInvisible();
- }
public bool DoubleClickChecks
{
@@ -126,9 +114,7 @@ private ListViewGroup FindGroup(int id)
{
foreach (ListViewGroup group in this.Groups)
{
- int? groupId = GetGroupID(group);
-
- if (groupId != null && groupId.Value == id)
+ if (GetGroupID(group).Value == id)
return group;
}
@@ -139,17 +125,18 @@ private ListViewGroup FindGroup(int id)
{
int? grpId = null;
Type grpType = lvGroup.GetType();
-
- PropertyInfo pInfo = grpType.GetProperty("ID", BindingFlags.NonPublic | BindingFlags.Instance);
- if (pInfo != null)
+ if (grpType != null)
{
- object tmprtnval = pInfo.GetValue(lvGroup, null);
- if (tmprtnval != null)
+ PropertyInfo pInfo = grpType.GetProperty("ID", BindingFlags.NonPublic | BindingFlags.Instance);
+ if (pInfo != null)
{
- grpId = tmprtnval as int?;
+ object tmprtnval = pInfo.GetValue(lvGroup, null);
+ if (tmprtnval != null)
+ {
+ grpId = tmprtnval as int?;
+ }
}
}
-
return grpId;
}
@@ -160,13 +147,13 @@ private void SetGrpState(ListViewGroup lvGroup, ListViewGroupState grpState, str
if (lvGroup == null || lvGroup.ListView == null)
return;
if (lvGroup.ListView.InvokeRequired)
- lvGroup.ListView.BeginInvoke(new CallBackSetGroupState(SetGrpState), lvGroup, grpState, task);
+ lvGroup.ListView.Invoke(new CallBackSetGroupState(SetGrpState), lvGroup, grpState, task);
else
{
int? GrpId = GetGroupID(lvGroup);
int gIndex = lvGroup.ListView.Groups.IndexOf(lvGroup);
LVGroup group = new LVGroup();
- group.CbSize = LVGroup.SizeOf;
+ group.CbSize = Marshal.SizeOf(group);
if (!string.IsNullOrEmpty(task))
{
@@ -188,12 +175,12 @@ private void SetGrpState(ListViewGroup lvGroup, ListViewGroupState grpState, str
if (GrpId != null)
{
group.GroupId = GrpId.Value;
- SendMessage(this.Handle, LVM_SetGroupInfo, GrpId.Value, ref group);
+ SendMessage(base.Handle, LVM_SetGroupInfo, GrpId.Value, ref group);
}
else
{
group.GroupId = gIndex;
- SendMessage(this.Handle, LVM_SetGroupInfo, gIndex, ref group);
+ SendMessage(base.Handle, LVM_SetGroupInfo, gIndex, ref group);
}
lvGroup.ListView.Refresh();
@@ -281,15 +268,8 @@ protected override void WndProc(ref Message m)
/// Used to set and retrieve groups.
///
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
- public struct LVGroup
+ private struct LVGroup
{
- public static readonly int SizeOf;
-
- static LVGroup()
- {
- SizeOf = Marshal.SizeOf(typeof(LVGroup));
- }
-
///
/// Size of this structure, in bytes.
///
@@ -417,12 +397,12 @@ static LVGroup()
///
public uint CchSubsetTitle;
}
-
+
///
/// WM_NOTIFY notificaiton message header.
///
[StructLayout(LayoutKind.Sequential)]
- public struct NMHDR
+ private struct NMHDR
{
///
/// Window handle to the control sending a message.
@@ -442,7 +422,7 @@ public struct NMHDR
/// Used to set and retrieve information about a link item.
///
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- public struct LITEM
+ private struct LITEM
{
///
/// Combination of one or more of the LIF flags
@@ -477,7 +457,7 @@ public struct LITEM
/// Contains information about an LVN_LINKCLICK notification.
///
[StructLayout(LayoutKind.Sequential)]
- public struct NMLVLINK
+ private struct NMLVLINK
{
///
/// NMHDR structure that contains basic
diff --git a/1.x/trunk/ProcessHacker/Components/ExtendedTreeView.cs b/1.x/trunk/ProcessHacker/Components/ExtendedTreeView.cs
index 9fc67b2d3..0c1e49458 100644
--- a/1.x/trunk/ProcessHacker/Components/ExtendedTreeView.cs
+++ b/1.x/trunk/ProcessHacker/Components/ExtendedTreeView.cs
@@ -22,6 +22,7 @@
*/
using System;
+using System.Runtime.InteropServices;
using ProcessHacker.Native;
using ProcessHacker.Native.Api;
@@ -41,8 +42,8 @@ protected override void OnHandleCreated(System.EventArgs e)
{
if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
{
- Win32.SendMessage(this.Handle, (WindowMessage)TVM_SETEXTENDEDSTYLE, IntPtr.Zero, (IntPtr)TVS_EX_FADEINOUTEXPANDOS);
- Win32.SetWindowTheme(this.Handle, "Explorer", null);
+ Win32.SendMessage(this.Handle, (WindowMessage)TVM_SETEXTENDEDSTYLE, 0, TVS_EX_FADEINOUTEXPANDOS);
+ ProcessHacker.Common.PhUtils.SetTheme(this, "explorer");
}
base.OnHandleCreated(e);
diff --git a/1.x/trunk/ProcessHacker/Components/FileNameBox.Designer.cs b/1.x/trunk/ProcessHacker/Components/FileNameBox.Designer.cs
index ef1316274..0b69e8137 100644
--- a/1.x/trunk/ProcessHacker/Components/FileNameBox.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/FileNameBox.Designer.cs
@@ -37,9 +37,9 @@ private void InitializeComponent()
//
// textFileName
//
- this.textFileName.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textFileName.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textFileName.Location = new System.Drawing.Point(0, 2);
this.textFileName.Name = "textFileName";
this.textFileName.Size = new System.Drawing.Size(277, 20);
@@ -48,8 +48,8 @@ private void InitializeComponent()
//
// buttonProperties
//
- this.buttonProperties.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonProperties.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.buttonProperties.Image = global::ProcessHacker.Properties.Resources.application_form_magnify;
this.buttonProperties.Location = new System.Drawing.Point(279, 0);
this.buttonProperties.Name = "buttonProperties";
@@ -61,8 +61,8 @@ private void InitializeComponent()
//
// buttonExplore
//
- this.buttonExplore.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonExplore.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.buttonExplore.Image = global::ProcessHacker.Properties.Resources.folder_explore;
this.buttonExplore.Location = new System.Drawing.Point(304, 0);
this.buttonExplore.Name = "buttonExplore";
@@ -76,7 +76,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.buttonExplore);
this.Controls.Add(this.buttonProperties);
this.Controls.Add(this.textFileName);
diff --git a/1.x/trunk/ProcessHacker/Components/FileNameBox.resx b/1.x/trunk/ProcessHacker/Components/FileNameBox.resx
index 026c576b4..a5979aadf 100644
--- a/1.x/trunk/ProcessHacker/Components/FileNameBox.resx
+++ b/1.x/trunk/ProcessHacker/Components/FileNameBox.resx
@@ -112,12 +112,12 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/HandleDetails.cs b/1.x/trunk/ProcessHacker/Components/HandleDetails.cs
deleted file mode 100644
index 4abc1a39d..000000000
--- a/1.x/trunk/ProcessHacker/Components/HandleDetails.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Process Hacker -
- * .NET counters control
- *
- * Copyright (C) 2009-2010 wj32
- *
- * This file is part of Process Hacker.
- *
- * Process Hacker is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * Process Hacker is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Process Hacker. If not, see .
- */
-
-using System;
-using System.Windows.Forms;
-using ProcessHacker.Api;
-using ProcessHacker.Native;
-using ProcessHacker.Native.Api;
-
-namespace ProcessHacker.Components
-{
- public partial class HandleDetails : ProcessPropertySheetPage
- {
- public delegate void HandlePropertiesDelegate(Control objectGroup, string name, string typeName);
-
- public event HandlePropertiesDelegate HandlePropertiesCallback;
- public string _name;
- public string _typeName;
-
- public SystemHandleEntry ObjectHandle { get; set; }
-
- public void Init()
- {
- try
- {
- ObjectInformation handleInfo = ObjectHandle.GetHandleInfo();
-
- _name = textName.Text = handleInfo.BestName;
-
- if (string.IsNullOrEmpty(textName.Text))
- textName.Text = "(unnamed object)";
-
- _typeName = textType.Text = handleInfo.TypeName;
- textAddress.Text = "0x" + ObjectHandle.Object.ToString("x");
- textGrantedAccess.Text = "0x" + ObjectHandle.GrantedAccess.ToString("x");
-
- if (ObjectHandle.GrantedAccess != 0)
- {
- try
- {
- Type accessEnumType = NativeTypeFactory.GetAccessType(handleInfo.TypeName);
- textGrantedAccess.Text += " (" + NativeTypeFactory.GetAccessString(accessEnumType, ObjectHandle.GrantedAccess) + ")";
- }
- catch (NotSupportedException)
- {
- }
- }
-
- ObjectBasicInformation basicInfo = ObjectHandle.GetBasicInfo();
-
- labelReferences.Text = "References: " + (basicInfo.PointerCount - 1);
- labelHandles.Text = "Handles: " + basicInfo.HandleCount.ToString();
- labelPaged.Text = "Paged: " + basicInfo.PagedPoolUsage.ToString();
- labelNonPaged.Text = "Non-Paged: " + basicInfo.NonPagedPoolUsage.ToString();
-
- if (HandlePropertiesCallback != null)
- {
- try
- {
- HandlePropertiesCallback(groupObjectInfo, _name, _typeName);
- }
- catch
- {
- }
-
- if (groupObjectInfo.Controls.Count == 0)
- {
- groupObjectInfo.Visible = false;
- }
- else if (groupObjectInfo.Controls.Count == 1)
- {
- Control control = groupObjectInfo.Controls[0];
-
- // If it's a user control, dock it.
- if (control is UserControl)
- {
- control.Dock = DockStyle.Fill;
- control.Margin = new Padding(3);
- }
- else
- {
- control.Location = new System.Drawing.Point(10, 20);
- }
- }
- }
- }
- catch (Exception)
- { }
-
- this.ActiveControl = this.label1;
- }
-
- public HandleDetails()
- {
- InitializeComponent();
-
- this.ActiveControl = this.label1;
-
- this.label1.Refresh();
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/HandleDetails.resx b/1.x/trunk/ProcessHacker/Components/HandleDetails.resx
deleted file mode 100644
index c7e0d4bdf..000000000
--- a/1.x/trunk/ProcessHacker/Components/HandleDetails.resx
+++ /dev/null
@@ -1,120 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- text/microsoft-resx
-
-
- 2.0
-
-
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/HandleList.Designer.cs b/1.x/trunk/ProcessHacker/Components/HandleList.Designer.cs
index 3289805b5..e1aecfac9 100644
--- a/1.x/trunk/ProcessHacker/Components/HandleList.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/HandleList.Designer.cs
@@ -32,10 +32,12 @@ protected override void Dispose(bool disposing)
///
private void InitializeComponent()
{
- this.listHandles = new ProcessHacker.Components.ExtendedListView();
- this.columnType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnHandle = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.components = new System.ComponentModel.Container();
+ this.listHandles = new System.Windows.Forms.ListView();
+ this.columnType = new System.Windows.Forms.ColumnHeader();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnHandle = new System.Windows.Forms.ColumnHeader();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
this.closeHandleMenuItem = new System.Windows.Forms.MenuItem();
this.copyHandleMenuItem = new System.Windows.Forms.MenuItem();
this.menuHandle = new System.Windows.Forms.ContextMenu();
@@ -43,6 +45,7 @@ private void InitializeComponent()
this.inheritMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem11 = new System.Windows.Forms.MenuItem();
this.propertiesHandleMenuItem = new System.Windows.Forms.MenuItem();
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
// listHandles
@@ -53,7 +56,6 @@ private void InitializeComponent()
this.columnName,
this.columnHandle});
this.listHandles.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listHandles.DoubleClickChecks = true;
this.listHandles.FullRowSelect = true;
this.listHandles.HideSelection = false;
this.listHandles.Location = new System.Drawing.Point(0, 0);
@@ -79,14 +81,21 @@ private void InitializeComponent()
//
this.columnHandle.Text = "Handle";
//
+ // vistaMenu
+ //
+ this.vistaMenu.ContainerControl = this;
+ this.vistaMenu.DelaySetImageCalls = false;
+ //
// closeHandleMenuItem
//
+ this.vistaMenu.SetImage(this.closeHandleMenuItem, global::ProcessHacker.Properties.Resources.cross);
this.closeHandleMenuItem.Index = 0;
this.closeHandleMenuItem.Text = "Close";
this.closeHandleMenuItem.Click += new System.EventHandler(this.closeHandleMenuItem_Click);
//
// copyHandleMenuItem
//
+ this.vistaMenu.SetImage(this.copyHandleMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyHandleMenuItem.Index = 4;
this.copyHandleMenuItem.Text = "&Copy";
//
@@ -128,20 +137,22 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listHandles);
+ this.DoubleBuffered = true;
this.Name = "HandleList";
this.Size = new System.Drawing.Size(450, 472);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
}
#endregion
- private ExtendedListView listHandles;
+ private System.Windows.Forms.ListView listHandles;
private System.Windows.Forms.ColumnHeader columnType;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ColumnHeader columnHandle;
+ private wyDay.Controls.VistaMenu vistaMenu;
private System.Windows.Forms.ContextMenu menuHandle;
private System.Windows.Forms.MenuItem closeHandleMenuItem;
private System.Windows.Forms.MenuItem copyHandleMenuItem;
diff --git a/1.x/trunk/ProcessHacker/Components/HandleList.cs b/1.x/trunk/ProcessHacker/Components/HandleList.cs
index 77c4a4807..895967535 100644
--- a/1.x/trunk/ProcessHacker/Components/HandleList.cs
+++ b/1.x/trunk/ProcessHacker/Components/HandleList.cs
@@ -23,22 +23,20 @@
using System;
using System.Collections.Generic;
using System.Drawing;
-using System.Runtime.InteropServices;
+using System.Reflection;
using System.Windows.Forms;
-using ProcessHacker.Api;
using ProcessHacker.Common;
using ProcessHacker.Common.Ui;
using ProcessHacker.Native;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
-using ProcessHacker.Native.Security.AccessControl;
using ProcessHacker.Native.Ui;
using ProcessHacker.UI;
namespace ProcessHacker.Components
{
- public partial class HandleList : ProcessPropertySheetPage
+ public partial class HandleList : UserControl
{
public static bool ConfirmHandleClose()
{
@@ -51,37 +49,22 @@ public static bool ConfirmHandleClose()
false
);
}
- return true;
+ else
+ {
+ return true;
+ }
}
public static void ShowHandleProperties(SystemHandleEntry handleInfo)
{
try
{
+ HandlePropertiesWindow window = new HandlePropertiesWindow(handleInfo);
IntPtr handle = new IntPtr(handleInfo.Handle);
ProcessHandle phandle = new ProcessHandle(handleInfo.ProcessId, ProcessAccess.DupHandle);
- GenericHandle dupHandle = null;
-
- // Try to get a handle, since we need one for security editing.
- try
- {
- dupHandle = new GenericHandle(phandle, handle, 0);
- }
- catch
- { }
-
- PropSheetHeader64 header = new PropSheetHeader64
- {
- dwSize = (uint)PropSheetHeader64.SizeOf,
- nPages = 2,
- dwFlags = (uint)PropSheetFlags.PSH_DEFAULT,
- pszCaption = "Handle Properties"
- };
+ GenericHandle dupHandle = null;
- using (HandleDetails hw = new HandleDetails())
- {
- hw.ObjectHandle = handleInfo;
- hw.HandlePropertiesCallback += (control, name, typeName) =>
+ window.HandlePropertiesCallback += (control, name, typeName) =>
{
switch (typeName.ToLowerInvariant())
{
@@ -92,65 +75,76 @@ public static void ShowHandleProperties(SystemHandleEntry handleInfo)
case "token":
case "process":
{
- Button b = new Button
- {
- FlatStyle = FlatStyle.System,
- Text = "Properties"
- };
+ Button b = new Button();
+ b.FlatStyle = FlatStyle.System;
+ b.Text = "Properties";
b.Click += (sender, e) =>
- {
- try
{
- switch (typeName.ToLowerInvariant())
+ try
{
- case "file":
- {
- FileUtils.ShowProperties(name);
- }
- break;
- case "job":
- {
- dupHandle = new GenericHandle(phandle, handle, (int)JobObjectAccess.Query);
-
- (new JobWindow(JobObjectHandle.FromHandle(dupHandle))).ShowDialog();
- }
- break;
- case "key":
- {
- try
+ switch (typeName.ToLowerInvariant())
+ {
+ case "file":
+ {
+ FileUtils.ShowProperties(name);
+ }
+ break;
+ case "job":
{
- PhUtils.OpenKeyInRegedit(PhUtils.GetForegroundWindow(), name);
+ dupHandle =
+ new GenericHandle(
+ phandle, handle,
+ (int)JobObjectAccess.Query);
+ (new JobWindow(JobObjectHandle.FromHandle(dupHandle))).ShowDialog();
}
- catch (Exception ex)
+ break;
+ case "key":
{
- PhUtils.ShowException("Unable to open the Registry Editor", ex);
+ try
+ {
+ PhUtils.OpenKeyInRegedit(PhUtils.GetForegroundWindow(), name);
+ }
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to open the Registry Editor", ex);
+ }
}
- }
- break;
- case "token":
- {
- using (TokenWindow twindow = new TokenWindow(new RemoteTokenHandle(phandle, handle)))
+ break;
+ case "token":
{
- twindow.ShowDialog();
+ (new TokenWindow(new RemoteTokenHandle(phandle,
+ handle))).ShowDialog();
}
- }
- break;
- case "process":
- {
- dupHandle = new GenericHandle(phandle, handle, (int)OSVersion.MinProcessQueryInfoAccess);
- int pid = ProcessHandle.FromHandle(dupHandle).ProcessId;
-
- Program.GetProcessWindow(Program.ProcessProvider.Dictionary[pid], Program.FocusWindow);
- }
- break;
+ break;
+ case "process":
+ {
+ int pid;
+
+ if (KProcessHacker.Instance != null)
+ {
+ pid = KProcessHacker.Instance.KphGetProcessId(phandle, handle);
+ }
+ else
+ {
+ dupHandle =
+ new GenericHandle(
+ phandle, handle,
+ (int)OSVersion.MinProcessQueryInfoAccess);
+ pid = ProcessHandle.FromHandle(dupHandle).GetProcessId();
+ }
+
+ Program.GetProcessWindow(Program.ProcessProvider.Dictionary[pid],
+ (f) => Program.FocusWindow(f));
+ }
+ break;
+ }
}
- }
- catch (Exception ex)
- {
- PhUtils.ShowException("Unable to show object properties", ex);
- }
- };
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to show object properties", ex);
+ }
+ };
control.Controls.Add(b);
}
@@ -214,25 +208,19 @@ public static void ShowHandleProperties(SystemHandleEntry handleInfo)
}
};
- hw.Init();
-
- IntPtr[] pages = new IntPtr[2];
- pages[0] = hw.CreatePageHandle();
- pages[1] = CreateSecurityPage(SecurityEditor.EditSecurity2(
- null,
- SecurityEditor.GetSecurableWrapper(dupHandle),
- hw._name,
- NativeTypeFactory.GetAccessEntries(NativeTypeFactory.GetObjectType(hw._typeName))
- ));
+ if (dupHandle == null)
+ {
+ // Try to get a handle, since we need one for security editing.
+ try { dupHandle = new GenericHandle(phandle, handle, 0); }
+ catch { }
+ }
- GCHandle gch = GCHandle.Alloc(pages, GCHandleType.Pinned);
- header.phpage = gch.AddrOfPinnedObject();
+ window.ObjectHandle = dupHandle;
- PropertySheetW(ref header);
+ window.ShowDialog();
- if (dupHandle != null)
- dupHandle.Dispose();
- }
+ if (dupHandle != null)
+ dupHandle.Dispose();
}
catch (Exception ex)
{
@@ -240,84 +228,11 @@ public static void ShowHandleProperties(SystemHandleEntry handleInfo)
}
}
- [DllImport("Comctl32.dll")]
- public static extern IntPtr PropertySheetW([In, MarshalAs(UnmanagedType.Struct)]ref PropSheetHeader64 lppsph);
-
- [DllImport("Aclui.dll")]
- public static extern IntPtr CreateSecurityPage(ISecurityInformation lppsph);
-
- [StructLayout(LayoutKind.Explicit, Pack = 8, CharSet = CharSet.Unicode)]
- public struct PropSheetHeader64
- {
- public static readonly int SizeOf;
-
- static PropSheetHeader64()
- {
- SizeOf = Marshal.SizeOf(typeof(PropSheetHeader64));
- }
-
- [FieldOffset(0)]
- public UInt32 dwSize;
- [FieldOffset(4)]
- public UInt32 dwFlags;
- [FieldOffset(8)]
- public IntPtr hwndParent;
- [FieldOffset(16)]
- public IntPtr hInstance;
- [FieldOffset(24)]
- public IntPtr hIcon;
- [FieldOffset(32)]
- public String pszCaption;
- [FieldOffset(40)]
- public UInt32 nPages;
- [FieldOffset(48)]
- public string pStartPage;
- [FieldOffset(56)]
- public IntPtr phpage;
-
- // following fields all for PROPSHEETHEADER_V2
- [FieldOffset(64)]
- public IntPtr pfnCallback;
- [FieldOffset(72)]
- public IntPtr hbmWatermark;
- [FieldOffset(80)]
- public IntPtr hplWatermark;
- [FieldOffset(88)]
- public IntPtr hbmHeader;
- }
-
- [Flags]
- internal enum PropSheetFlags : uint
- {
- PSH_DEFAULT = 0x00000000,
- PSH_PROPTITLE = 0x00000001,
- PSH_USEHICON = 0x00000002,
- PSH_USEICONID = 0x00000004,
- PSH_PROPSHEETPAGE = 0x00000008,
- PSH_WIZARDHASFINISH = 0x00000010,
- PSH_WIZARD = 0x00000020,
- PSH_USEPSTARTPAGE = 0x00000040,
- PSH_NOAPPLYNOW = 0x00000080,
- PSH_USECALLBACK = 0x00000100,
- PSH_HASHELP = 0x00000200,
- PSH_MODELESS = 0x00000400,
- PSH_RTLREADING = 0x00000800,
- PSH_WIZARDCONTEXTHELP = 0x00001000,
- PSH_WIZARD97 = 0x01000000,
- PSH_WATERMARK = 0x00008000,
- PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark
- PSH_USEHPLWATERMARK = 0x00020000, //
- PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header
- PSH_HEADER = 0x00080000,
- PSH_USEHBMHEADER = 0x00100000,
- PSH_USEPAGELANG = 0x00200000 // use frame dialog template matched to page
- }
-
- private readonly object _listLock = new object();
+ private object _listLock = new object();
private HandleProvider _provider;
- private int _runCount;
- private readonly List _needsAdd = new List();
- private readonly HighlightingContext _highlightingContext;
+ private int _runCount = 0;
+ private List _needsAdd = new List();
+ private HighlightingContext _highlightingContext;
public new event KeyEventHandler KeyDown;
public new event MouseEventHandler MouseDown;
public new event MouseEventHandler MouseUp;
@@ -328,11 +243,11 @@ public HandleList()
InitializeComponent();
_highlightingContext = new HighlightingContext(listHandles);
- listHandles.KeyDown += this.listHandles_KeyDown;
- listHandles.MouseDown += this.listHandles_MouseDown;
- listHandles.MouseUp += this.listHandles_MouseUp;
- listHandles.DoubleClick += this.listHandles_DoubleClick;
- listHandles.SelectedIndexChanged += this.listHandles_SelectedIndexChanged;
+ listHandles.KeyDown += new KeyEventHandler(listHandles_KeyDown);
+ listHandles.MouseDown += new MouseEventHandler(listHandles_MouseDown);
+ listHandles.MouseUp += new MouseEventHandler(listHandles_MouseUp);
+ listHandles.DoubleClick += new EventHandler(listHandles_DoubleClick);
+ listHandles.SelectedIndexChanged += new System.EventHandler(listHandles_SelectedIndexChanged);
var comparer = (SortedListViewComparer)
(listHandles.ListViewItemSorter = new SortedListViewComparer(listHandles));
@@ -345,7 +260,7 @@ public HandleList()
GenericViewMenu.AddMenuItems(copyHandleMenuItem.MenuItems, listHandles, null);
ColumnSettings.LoadSettings(Settings.Instance.HandleListViewColumns, listHandles);
- //if (KProcessHacker.Instance == null)
+ if (KProcessHacker.Instance == null)
{
protectedMenuItem.Visible = false;
inheritMenuItem.Visible = false;
@@ -369,7 +284,7 @@ private void listHandles_MouseDown(object sender, MouseEventArgs e)
this.MouseDown(sender, e);
}
- private void listHandles_SelectedIndexChanged(object sender, EventArgs e)
+ private void listHandles_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (this.SelectedIndexChanged != null)
this.SelectedIndexChanged(sender, e);
@@ -382,23 +297,36 @@ private void listHandles_KeyDown(object sender, KeyEventArgs e)
if (!e.Handled)
{
- switch (e.KeyCode)
+ if (e.KeyCode == Keys.Enter)
{
- case Keys.Enter:
- this.propertiesHandleMenuItem_Click(null, null);
- break;
- case Keys.Delete:
- if (ConfirmHandleClose())
- {
- this.closeHandleMenuItem_Click(null, null);
- }
- break;
+ propertiesHandleMenuItem_Click(null, null);
+ }
+ else if (e.KeyCode == Keys.Delete)
+ {
+ if (ConfirmHandleClose())
+ {
+ closeHandleMenuItem_Click(null, null);
+ }
}
}
}
#region Properties
+ public new bool DoubleBuffered
+ {
+ get
+ {
+ return (bool)typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).GetValue(listHandles, null);
+ }
+ set
+ {
+ typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).SetValue(listHandles, value, null);
+ }
+ }
+
public override bool Focused
{
get
@@ -407,13 +335,19 @@ public override bool Focused
}
}
+ public override ContextMenu ContextMenu
+ {
+ get { return listHandles.ContextMenu; }
+ set { listHandles.ContextMenu = value; }
+ }
+
public override ContextMenuStrip ContextMenuStrip
{
get { return listHandles.ContextMenuStrip; }
set { listHandles.ContextMenuStrip = value; }
}
- public ExtendedListView List
+ public ListView List
{
get { return listHandles; }
}
@@ -506,13 +440,12 @@ private Color GetHandleColor(HandleItem item)
(item.Handle.Flags & HandleFlags.ProtectFromClose) != 0
)
return Settings.Instance.ColorProtectedHandles;
-
- if (Settings.Instance.UseColorInheritHandles &&
+ else if (Settings.Instance.UseColorInheritHandles &&
(item.Handle.Flags & HandleFlags.Inherit) != 0
)
return Settings.Instance.ColorInheritHandles;
-
- return SystemColors.Window;
+ else
+ return SystemColors.Window;
}
public void AddItem(HandleItem item)
@@ -533,12 +466,11 @@ public void DumpDisableEvents()
private void provider_DictionaryAdded(HandleItem item)
{
- HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext, item.RunId > 0 && _runCount > 0)
- {
- Name = item.Handle.Handle.ToString(),
- Text = item.ObjectInfo.TypeName
- };
+ HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext,
+ item.RunId > 0 && _runCount > 0);
+ litem.Name = item.Handle.Handle.ToString();
+ litem.Text = item.ObjectInfo.TypeName;
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.ObjectInfo.BestName));
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, "0x" + item.Handle.Handle.ToString("x")));
litem.Tag = item;
@@ -552,21 +484,22 @@ private void provider_DictionaryAdded(HandleItem item)
private void provider_DictionaryModified(HandleItem oldItem, HandleItem newItem)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- lock (_listLock)
{
- ((HighlightedListViewItem)this.listHandles.Items[newItem.Handle.Handle.ToString()]).NormalColor = this.GetHandleColor(newItem);
- }
- }));
+ lock (_listLock)
+ {
+ (listHandles.Items[newItem.Handle.Handle.ToString()] as
+ HighlightedListViewItem).NormalColor = this.GetHandleColor(newItem);
+ }
+ }));
}
private void provider_DictionaryRemoved(HandleItem item)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- lock (_listLock)
- listHandles.Items[item.Handle.Handle.ToString()].Remove();
- }));
+ {
+ lock (_listLock)
+ listHandles.Items[item.Handle.Handle.ToString()].Remove();
+ }));
}
private int _pid;
@@ -583,7 +516,7 @@ private void menuHandle_Popup(object sender, EventArgs e)
if (listHandles.SelectedItems.Count == 0)
{
- //menuHandle.DisableAll();
+ menuHandle.DisableAll();
}
else if (listHandles.SelectedItems.Count == 1)
{
@@ -653,8 +586,8 @@ private void protectedMenuItem_Click(object sender, EventArgs e)
try
{
- //using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
- //KProcessHacker.Instance.SetHandleAttributes(phandle, new IntPtr(item.Handle.Handle), flags);
+ using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
+ KProcessHacker.Instance.SetHandleAttributes(phandle, new IntPtr(item.Handle.Handle), flags);
}
catch (Exception ex)
{
@@ -674,8 +607,8 @@ private void inheritMenuItem_Click(object sender, EventArgs e)
try
{
- //using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
- //KProcessHacker.Instance.SetHandleAttributes(phandle, new IntPtr(item.Handle.Handle), flags);
+ using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
+ KProcessHacker.Instance.SetHandleAttributes(phandle, new IntPtr(item.Handle.Handle), flags);
}
catch (Exception ex)
{
diff --git a/1.x/trunk/ProcessHacker/Components/HandleList.resx b/1.x/trunk/ProcessHacker/Components/HandleList.resx
index 051a81cde..90ace843e 100644
--- a/1.x/trunk/ProcessHacker/Components/HandleList.resx
+++ b/1.x/trunk/ProcessHacker/Components/HandleList.resx
@@ -112,12 +112,15 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
+ 17, 17
+
+
125, 17
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/Indicator.cs b/1.x/trunk/ProcessHacker/Components/Indicator.cs
index 9248e9362..d4a5a677a 100644
--- a/1.x/trunk/ProcessHacker/Components/Indicator.cs
+++ b/1.x/trunk/ProcessHacker/Components/Indicator.cs
@@ -21,7 +21,11 @@
*/
using System;
+using System.Collections.Generic;
+using System.ComponentModel;
using System.Drawing;
+using System.Data;
+using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
@@ -41,38 +45,40 @@ public Color Color2
get { return _lineColor2; }
set { _lineColor2 = value; }
}
+ private long _data1;
+ public long Data1
+ {
+ get { return _data1; }
+ set { _data1 = value; }
+ }
+ private long _data2;
+ public long Data2
+ {
+ get { return _data2; }
+ set { _data2 = value; }
+ }
- public long Data1 { get; set; }
- public long Data2 { get; set; }
+
public Indicator()
{
InitializeComponent();
-
- this.SetStyle(
- ControlStyles.ResizeRedraw |
- ControlStyles.UserPaint |
- ControlStyles.OptimizedDoubleBuffer |
- ControlStyles.AllPaintingInWmPaint, true);
+ base.SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint |
+ ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
//SolidBrush brush = new SolidBrush(this.ForeColor);
SolidBrush brush1 = new SolidBrush(this.Color1);
SolidBrush brush2 = new SolidBrush(this.Color2);
- int width = this.ClientSize.Width;
- int height = this.ClientSize.Height;
+ int width = base.ClientSize.Width;
+ int height = base.ClientSize.Height;
int num1 = height;
num1 -= this.Font.Height + 4;
- RectangleF layoutRectangle = new RectangleF(0f, num1, width, height);
-
- StringFormat format = new StringFormat(StringFormatFlags.NoWrap)
- {
- Alignment = StringAlignment.Center
- };
-
+ RectangleF layoutRectangle = new RectangleF(0f, (float)num1, (float)width, (float)height);
+ StringFormat format = new StringFormat(StringFormatFlags.NoWrap);
+ format.Alignment = StringAlignment.Center;
e.Graphics.DrawString(this.Text, this.Font, brush1, layoutRectangle, format);
-
int num2 = (((height - 6) - 4) - this.Font.Height) - 4;
num2++;
int num3 = num2 / 3;
@@ -80,24 +86,25 @@ protected override void OnPaint(PaintEventArgs e)
byte green = (byte)(this.ForeColor.G / 2);
byte blue = (byte)(this.ForeColor.B / 2);
- Pen pen = new Pen(Color.FromArgb(red, green, blue))
- {
- DashStyle = DashStyle.Dot
- };
+ Pen pen = new Pen(Color.FromArgb(red, green, blue));
+ pen.DashStyle = DashStyle.Dot;
int num4 = (width - this.GraphWidth) / 2;
int num5 = ((height - 4) - this.Font.Height) - 7;
int num6 = this.GraphWidth / 2;
- int num9 = (int)Math.Ceiling(((this.Data1 - this.Minimum) * 1.0) / ((this.Maximum - (this.Minimum * 1.0)) / num3));
- int num10 = (int)Math.Ceiling(((this.Data1 + this.Data2 - this.Minimum) * 1.0) / ((this.Maximum - (this.Minimum * 1.0)) / num3));
+ int x = num4;
+ int y = 0;
+ int num7 = 0;
+ int num8 = 0;
+ int num9 = (int)Math.Ceiling((double)(((this.Data1 - this.Minimum) * 1.0) / ((this.Maximum - (this.Minimum * 1.0)) / ((double)num3))));
+ int num10 = (int)Math.Ceiling((double)(((this.Data1 + this.Data2 - this.Minimum) * 1.0) / ((this.Maximum - (this.Minimum * 1.0)) / ((double)num3))));
for (int i = 0; i < num3; i++)
{
- int x = num4;
- int y = (num5 - (i * 3)) - 1;
- int num7 = x + num6;
- int num8 = y;
-
+ x = num4;
+ y = (num5 - (i * 3)) - 1;
+ num7 = x + num6;
+ num8 = y;
if (i < num9)
{
e.Graphics.FillRectangle(brush1, x, y, num6, 2);
@@ -132,9 +139,9 @@ protected override CreateParams CreateParams
return createParams;
}
}
- private int _GraphWidth = 0x21;
+ private int _GraphWidth=0x21;
private long _Maximum = long.MaxValue;
- private long _Minimum;
+ private long _Minimum = 0;
public int GraphWidth
{
get
@@ -144,7 +151,7 @@ public int GraphWidth
set
{
this._GraphWidth = value;
- this.Invalidate();
+ base.Invalidate();
}
}
public long Maximum
@@ -162,7 +169,7 @@ public long Maximum
}
this._Maximum = value;
- this.Invalidate();
+ base.Invalidate();
}
}
public long Minimum
@@ -178,7 +185,7 @@ public long Minimum
throw new ArgumentException();
}
this._Minimum = value;
- this.Invalidate();
+ base.Invalidate();
}
}
public string TextValue
@@ -190,7 +197,7 @@ public string TextValue
set
{
base.Text = value;
- this.Invalidate();
+ base.Invalidate();
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/Indicator.resx b/1.x/trunk/ProcessHacker/Components/Indicator.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/Indicator.resx
+++ b/1.x/trunk/ProcessHacker/Components/Indicator.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/JobProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/JobProperties.Designer.cs
index a6ab51d28..dfd7017d7 100644
--- a/1.x/trunk/ProcessHacker/Components/JobProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/JobProperties.Designer.cs
@@ -34,17 +34,16 @@ private void InitializeComponent()
this.components = new System.ComponentModel.Container();
this.tabControl = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
- this.buttonTerminate = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textJobName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
- this.listLimits = new ProcessHacker.Components.ExtendedListView();
- this.columnLimit = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnValue = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.listProcesses = new ProcessHacker.Components.ExtendedListView();
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnPid = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.listLimits = new System.Windows.Forms.ListView();
+ this.columnLimit = new System.Windows.Forms.ColumnHeader();
+ this.columnValue = new System.Windows.Forms.ColumnHeader();
+ this.listProcesses = new System.Windows.Forms.ListView();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnPid = new System.Windows.Forms.ColumnHeader();
this.tabStatistics = new System.Windows.Forms.TabPage();
this.flowStatistics = new System.Windows.Forms.FlowLayoutPanel();
this.groupGeneral = new System.Windows.Forms.GroupBox();
@@ -88,6 +87,7 @@ private void InitializeComponent()
this.labelIOOther = new System.Windows.Forms.Label();
this.labelIOOtherBytes = new System.Windows.Forms.Label();
this.timerUpdate = new System.Windows.Forms.Timer(this.components);
+ this.buttonTerminate = new System.Windows.Forms.Button();
this.tabControl.SuspendLayout();
this.tabGeneral.SuspendLayout();
this.tabStatistics.SuspendLayout();
@@ -110,7 +110,7 @@ private void InitializeComponent()
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
- this.tabControl.Size = new System.Drawing.Size(456, 434);
+ this.tabControl.Size = new System.Drawing.Size(646, 434);
this.tabControl.TabIndex = 0;
//
// tabGeneral
@@ -125,23 +125,11 @@ private void InitializeComponent()
this.tabGeneral.Location = new System.Drawing.Point(4, 22);
this.tabGeneral.Name = "tabGeneral";
this.tabGeneral.Padding = new System.Windows.Forms.Padding(3);
- this.tabGeneral.Size = new System.Drawing.Size(448, 408);
+ this.tabGeneral.Size = new System.Drawing.Size(638, 408);
this.tabGeneral.TabIndex = 0;
this.tabGeneral.Text = "General";
this.tabGeneral.UseVisualStyleBackColor = true;
//
- // buttonTerminate
- //
- this.buttonTerminate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
- this.buttonTerminate.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.buttonTerminate.Location = new System.Drawing.Point(367, 6);
- this.buttonTerminate.Name = "buttonTerminate";
- this.buttonTerminate.Size = new System.Drawing.Size(75, 23);
- this.buttonTerminate.TabIndex = 5;
- this.buttonTerminate.Text = "Terminate";
- this.buttonTerminate.UseVisualStyleBackColor = true;
- this.buttonTerminate.Click += new System.EventHandler(this.buttonTerminate_Click);
- //
// label3
//
this.label3.AutoSize = true;
@@ -162,12 +150,12 @@ private void InitializeComponent()
//
// textJobName
//
- this.textJobName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textJobName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textJobName.Location = new System.Drawing.Point(50, 6);
this.textJobName.Name = "textJobName";
this.textJobName.ReadOnly = true;
- this.textJobName.Size = new System.Drawing.Size(311, 20);
+ this.textJobName.Size = new System.Drawing.Size(501, 20);
this.textJobName.TabIndex = 2;
//
// label1
@@ -181,20 +169,19 @@ private void InitializeComponent()
//
// listLimits
//
- this.listLimits.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.listLimits.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.listLimits.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnLimit,
this.columnValue});
- this.listLimits.DoubleClickChecks = true;
this.listLimits.FullRowSelect = true;
this.listLimits.HideSelection = false;
this.listLimits.Location = new System.Drawing.Point(6, 165);
this.listLimits.MultiSelect = false;
this.listLimits.Name = "listLimits";
this.listLimits.ShowItemToolTips = true;
- this.listLimits.Size = new System.Drawing.Size(436, 237);
+ this.listLimits.Size = new System.Drawing.Size(626, 237);
this.listLimits.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.listLimits.TabIndex = 0;
this.listLimits.UseCompatibleStateImageBehavior = false;
@@ -212,19 +199,18 @@ private void InitializeComponent()
//
// listProcesses
//
- this.listProcesses.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.listProcesses.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.listProcesses.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnName,
this.columnPid});
- this.listProcesses.DoubleClickChecks = true;
this.listProcesses.FullRowSelect = true;
this.listProcesses.HideSelection = false;
this.listProcesses.Location = new System.Drawing.Point(6, 50);
this.listProcesses.MultiSelect = false;
this.listProcesses.Name = "listProcesses";
this.listProcesses.ShowItemToolTips = true;
- this.listProcesses.Size = new System.Drawing.Size(436, 96);
+ this.listProcesses.Size = new System.Drawing.Size(626, 96);
this.listProcesses.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.listProcesses.TabIndex = 0;
this.listProcesses.UseCompatibleStateImageBehavior = false;
@@ -245,7 +231,7 @@ private void InitializeComponent()
this.tabStatistics.Location = new System.Drawing.Point(4, 22);
this.tabStatistics.Name = "tabStatistics";
this.tabStatistics.Padding = new System.Windows.Forms.Padding(3);
- this.tabStatistics.Size = new System.Drawing.Size(448, 408);
+ this.tabStatistics.Size = new System.Drawing.Size(638, 408);
this.tabStatistics.TabIndex = 2;
this.tabStatistics.Text = "Statistics";
this.tabStatistics.UseVisualStyleBackColor = true;
@@ -260,7 +246,7 @@ private void InitializeComponent()
this.flowStatistics.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowStatistics.Location = new System.Drawing.Point(3, 3);
this.flowStatistics.Name = "flowStatistics";
- this.flowStatistics.Size = new System.Drawing.Size(442, 402);
+ this.flowStatistics.Size = new System.Drawing.Size(632, 402);
this.flowStatistics.TabIndex = 2;
//
// groupGeneral
@@ -726,14 +712,26 @@ private void InitializeComponent()
this.timerUpdate.Interval = 1000;
this.timerUpdate.Tick += new System.EventHandler(this.timerUpdate_Tick);
//
+ // buttonTerminate
+ //
+ this.buttonTerminate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonTerminate.FlatStyle = System.Windows.Forms.FlatStyle.System;
+ this.buttonTerminate.Location = new System.Drawing.Point(557, 6);
+ this.buttonTerminate.Name = "buttonTerminate";
+ this.buttonTerminate.Size = new System.Drawing.Size(75, 23);
+ this.buttonTerminate.TabIndex = 5;
+ this.buttonTerminate.Text = "Terminate";
+ this.buttonTerminate.UseVisualStyleBackColor = true;
+ this.buttonTerminate.Click += new System.EventHandler(this.buttonTerminate_Click);
+ //
// JobProperties
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.tabControl);
+ this.DoubleBuffered = true;
this.Name = "JobProperties";
- this.Size = new System.Drawing.Size(456, 434);
+ this.Size = new System.Drawing.Size(646, 434);
this.tabControl.ResumeLayout(false);
this.tabGeneral.ResumeLayout(false);
this.tabGeneral.PerformLayout();
@@ -763,11 +761,11 @@ private void InitializeComponent()
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textJobName;
private System.Windows.Forms.Label label1;
- private ExtendedListView listProcesses;
+ private System.Windows.Forms.ListView listProcesses;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ColumnHeader columnPid;
private System.Windows.Forms.Label label3;
- private ExtendedListView listLimits;
+ private System.Windows.Forms.ListView listLimits;
private System.Windows.Forms.ColumnHeader columnLimit;
private System.Windows.Forms.ColumnHeader columnValue;
private System.Windows.Forms.GroupBox groupGeneral;
diff --git a/1.x/trunk/ProcessHacker/Components/JobProperties.cs b/1.x/trunk/ProcessHacker/Components/JobProperties.cs
index 5aa5d8e4b..c52274161 100644
--- a/1.x/trunk/ProcessHacker/Components/JobProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/JobProperties.cs
@@ -33,14 +33,17 @@ namespace ProcessHacker.Components
{
public partial class JobProperties : UserControl
{
- private readonly JobObjectHandle _jobObject;
+ private JobObjectHandle _jobObject;
public JobProperties(JobObjectHandle jobObject)
{
InitializeComponent();
+ listProcesses.SetTheme("explorer");
listProcesses.AddShortcuts();
listProcesses.ContextMenu = listProcesses.GetCopyMenu();
+
+ listLimits.SetTheme("explorer");
listLimits.AddShortcuts();
listLimits.ContextMenu = listLimits.GetCopyMenu();
@@ -51,7 +54,7 @@ public JobProperties(JobObjectHandle jobObject)
try
{
- string name = _jobObject.ObjectName;
+ string name = _jobObject.GetObjectName();
if (string.IsNullOrEmpty(name))
textJobName.Text = "(unnamed job)";
@@ -63,7 +66,7 @@ public JobProperties(JobObjectHandle jobObject)
try
{
- foreach (int pid in _jobObject.ProcessIdList)
+ foreach (int pid in _jobObject.GetProcessIdList())
{
ListViewItem item = new ListViewItem();
@@ -82,8 +85,8 @@ public JobProperties(JobObjectHandle jobObject)
try
{
- var extendedLimits = _jobObject.ExtendedLimitInformation;
- var uiRestrictions = _jobObject.BasicUiRestrictions;
+ var extendedLimits = _jobObject.GetExtendedLimitInformation();
+ var uiRestrictions = _jobObject.GetBasicUiRestrictions();
var flags = extendedLimits.BasicLimitInformation.LimitFlags;
if ((flags & JobObjectLimitFlags.ActiveProcess) != 0)
@@ -165,8 +168,8 @@ private void UpdateStatistics()
{
try
{
- JobObjectBasicAndIoAccountingInformation accounting = _jobObject.GetBasicAndIoAccountingInformation();
- JobObjectExtendedLimitInformation limits = _jobObject.ExtendedLimitInformation;
+ var accounting = _jobObject.GetBasicAndIoAccountingInformation();
+ var limits = _jobObject.GetExtendedLimitInformation();
labelGeneralActiveProcesses.Text = accounting.BasicInfo.ActiveProcesses.ToString("N0");
labelGeneralTotalProcesses.Text = accounting.BasicInfo.TotalProcesses.ToString("N0");
@@ -201,27 +204,26 @@ private void buttonTerminate_Click(object sender, EventArgs e)
{
if (OSVersion.HasTaskDialogs)
{
- TaskDialog td = new TaskDialog
+ TaskDialog td = new TaskDialog();
+
+ td.WindowTitle = "Process Hacker";
+ td.MainIcon = TaskDialogIcon.Warning;
+ td.MainInstruction = "Do you want to terminate the job?";
+ td.Content = "Terminating a job will terminate all processes assigned to it. Are you sure " +
+ "you want to continue?";
+ td.Buttons = new TaskDialogButton[]
{
- WindowTitle = "Process Hacker",
- MainInstruction = "Do you want to terminate the job?",
- Content = "Terminating a job will terminate all processes assigned to it. Are you sure " + "you want to continue?",
- MainIcon = TaskDialogIcon.Warning,
- DefaultButton = (int)DialogResult.No,
- Buttons = new TaskDialogButton[]
- {
- new TaskDialogButton((int)DialogResult.Yes, "Terminate"),
- new TaskDialogButton((int)DialogResult.No, "Cancel")
- }
+ new TaskDialogButton((int)DialogResult.Yes, "Terminate"),
+ new TaskDialogButton((int)DialogResult.No, "Cancel")
};
+ td.DefaultButton = (int)DialogResult.No;
if (td.Show(this) == (int)DialogResult.No)
return;
}
else
{
- if (MessageBox.Show(
- "Are you sure you want to terminate the job? This action will " +
+ if (MessageBox.Show("Are you sure you want to terminate the job? This action will " +
"terminate all processes associated with the job.", "Process Hacker",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
return;
@@ -229,7 +231,7 @@ private void buttonTerminate_Click(object sender, EventArgs e)
try
{
- using (NativeHandle jhandle2 = _jobObject.Duplicate(JobObjectAccess.Terminate))
+ using (var jhandle2 = _jobObject.Duplicate(JobObjectAccess.Terminate))
JobObjectHandle.FromHandle(jhandle2).Terminate();
}
catch (Exception ex)
diff --git a/1.x/trunk/ProcessHacker/Components/JobProperties.resx b/1.x/trunk/ProcessHacker/Components/JobProperties.resx
index bfd9c479b..3add4121b 100644
--- a/1.x/trunk/ProcessHacker/Components/JobProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/JobProperties.resx
@@ -112,12 +112,12 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/MemoryList.Designer.cs b/1.x/trunk/ProcessHacker/Components/MemoryList.Designer.cs
index 1cd68ea58..27b8fe625 100644
--- a/1.x/trunk/ProcessHacker/Components/MemoryList.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/MemoryList.Designer.cs
@@ -31,11 +31,13 @@ protected override void Dispose(bool disposing)
///
private void InitializeComponent()
{
- this.listMemory = new ProcessHacker.Components.ExtendedListView();
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnAddress = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnProtection = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.components = new System.ComponentModel.Container();
+ this.listMemory = new System.Windows.Forms.ListView();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnAddress = new System.Windows.Forms.ColumnHeader();
+ this.columnSize = new System.Windows.Forms.ColumnHeader();
+ this.columnProtection = new System.Windows.Forms.ColumnHeader();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
this.changeMemoryProtectionMemoryMenuItem = new System.Windows.Forms.MenuItem();
this.readWriteMemoryMemoryMenuItem = new System.Windows.Forms.MenuItem();
this.readWriteAddressMemoryMenuItem = new System.Windows.Forms.MenuItem();
@@ -46,6 +48,7 @@ private void InitializeComponent()
this.menuMemory = new System.Windows.Forms.ContextMenu();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.selectAllMemoryMenuItem = new System.Windows.Forms.MenuItem();
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
// listMemory
@@ -57,7 +60,6 @@ private void InitializeComponent()
this.columnSize,
this.columnProtection});
this.listMemory.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listMemory.DoubleClickChecks = true;
this.listMemory.FullRowSelect = true;
this.listMemory.HideSelection = false;
this.listMemory.Location = new System.Drawing.Point(0, 0);
@@ -87,8 +89,14 @@ private void InitializeComponent()
//
this.columnProtection.Text = "Protection";
//
+ // vistaMenu
+ //
+ this.vistaMenu.ContainerControl = this;
+ this.vistaMenu.DelaySetImageCalls = false;
+ //
// changeMemoryProtectionMemoryMenuItem
//
+ this.vistaMenu.SetImage(this.changeMemoryProtectionMemoryMenuItem, global::ProcessHacker.Properties.Resources.lock_edit);
this.changeMemoryProtectionMemoryMenuItem.Index = 2;
this.changeMemoryProtectionMemoryMenuItem.Text = "Change &Memory Protection...";
this.changeMemoryProtectionMemoryMenuItem.Click += new System.EventHandler(this.changeMemoryProtectionMemoryMenuItem_Click);
@@ -96,35 +104,41 @@ private void InitializeComponent()
// readWriteMemoryMemoryMenuItem
//
this.readWriteMemoryMemoryMenuItem.DefaultItem = true;
+ this.vistaMenu.SetImage(this.readWriteMemoryMemoryMenuItem, global::ProcessHacker.Properties.Resources.page_edit);
this.readWriteMemoryMemoryMenuItem.Index = 0;
this.readWriteMemoryMemoryMenuItem.Text = "Read/Write Memory";
this.readWriteMemoryMemoryMenuItem.Click += new System.EventHandler(this.readWriteMemoryMemoryMenuItem_Click);
//
// readWriteAddressMemoryMenuItem
//
+ this.vistaMenu.SetImage(this.readWriteAddressMemoryMenuItem, global::ProcessHacker.Properties.Resources.pencil_go);
this.readWriteAddressMemoryMenuItem.Index = 6;
this.readWriteAddressMemoryMenuItem.Text = "Read/Write Address...";
this.readWriteAddressMemoryMenuItem.Click += new System.EventHandler(this.readWriteAddressMemoryMenuItem_Click);
//
// copyMemoryMenuItem
//
+ this.vistaMenu.SetImage(this.copyMemoryMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyMemoryMenuItem.Index = 7;
this.copyMemoryMenuItem.Text = "C&opy";
//
// freeMenuItem
//
+ this.vistaMenu.SetImage(this.freeMenuItem, global::ProcessHacker.Properties.Resources.cross);
this.freeMenuItem.Index = 3;
this.freeMenuItem.Text = "&Free";
this.freeMenuItem.Click += new System.EventHandler(this.freeMenuItem_Click);
//
// decommitMenuItem
//
+ this.vistaMenu.SetImage(this.decommitMenuItem, global::ProcessHacker.Properties.Resources.delete);
this.decommitMenuItem.Index = 4;
this.decommitMenuItem.Text = "&Decommit";
this.decommitMenuItem.Click += new System.EventHandler(this.decommitMenuItem_Click);
//
// dumpMemoryMenuItem
//
+ this.vistaMenu.SetImage(this.dumpMemoryMenuItem, global::ProcessHacker.Properties.Resources.disk);
this.dumpMemoryMenuItem.Index = 1;
this.dumpMemoryMenuItem.Text = "Dump...";
this.dumpMemoryMenuItem.Click += new System.EventHandler(this.dumpMemoryMenuItem_Click);
@@ -158,18 +172,20 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listMemory);
+ this.DoubleBuffered = true;
this.Name = "MemoryList";
this.Size = new System.Drawing.Size(450, 472);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
}
#endregion
- private ExtendedListView listMemory;
+ private System.Windows.Forms.ListView listMemory;
private System.Windows.Forms.ColumnHeader columnName;
+ private wyDay.Controls.VistaMenu vistaMenu;
private System.Windows.Forms.ColumnHeader columnSize;
private System.Windows.Forms.ColumnHeader columnAddress;
private System.Windows.Forms.ColumnHeader columnProtection;
diff --git a/1.x/trunk/ProcessHacker/Components/MemoryList.cs b/1.x/trunk/ProcessHacker/Components/MemoryList.cs
index 601f20f7b..c205cf43d 100644
--- a/1.x/trunk/ProcessHacker/Components/MemoryList.cs
+++ b/1.x/trunk/ProcessHacker/Components/MemoryList.cs
@@ -22,6 +22,7 @@
using System;
using System.Collections.Generic;
+using System.Reflection;
using System.Windows.Forms;
using ProcessHacker.Common;
using ProcessHacker.Common.Ui;
@@ -35,11 +36,12 @@ namespace ProcessHacker.Components
{
public partial class MemoryList : UserControl
{
- private int _runCount;
+ private object _listLock = new object();
+ private int _runCount = 0;
private MemoryProvider _provider;
- private bool _needsSort;
- private readonly List _needsAdd = new List();
- private readonly HighlightingContext _highlightingContext;
+ private bool _needsSort = false;
+ private List _needsAdd = new List();
+ private HighlightingContext _highlightingContext;
public new event KeyEventHandler KeyDown;
public new event MouseEventHandler MouseDown;
public new event MouseEventHandler MouseUp;
@@ -50,27 +52,28 @@ public MemoryList()
InitializeComponent();
_highlightingContext = new HighlightingContext(listMemory);
- listMemory.KeyDown += this.listMemory_KeyDown;
- listMemory.MouseDown += this.listMemory_MouseDown;
- listMemory.MouseUp += this.listMemory_MouseUp;
+ listMemory.KeyDown += new KeyEventHandler(listMemory_KeyDown);
+ listMemory.MouseDown += new MouseEventHandler(listMemory_MouseDown);
+ listMemory.MouseUp += new MouseEventHandler(listMemory_MouseUp);
ColumnSettings.LoadSettings(Settings.Instance.MemoryListViewColumns, listMemory);
listMemory.ContextMenu = menuMemory;
GenericViewMenu.AddMenuItems(copyMemoryMenuItem.MenuItems, listMemory, null);
listMemory.ListViewItemSorter = new SortedListViewComparer(listMemory)
- {
- SortColumn = 1,
- SortOrder = SortOrder.Ascending
- };
+ {
+ SortColumn = 1,
+ SortOrder = SortOrder.Ascending
+ };
- (listMemory.ListViewItemSorter as SortedListViewComparer).CustomSorters.Add(2, (x, y) =>
- {
- MemoryItem ix = (MemoryItem)x.Tag;
- MemoryItem iy = (MemoryItem)y.Tag;
+ (listMemory.ListViewItemSorter as SortedListViewComparer).CustomSorters.Add(2,
+ (x, y) =>
+ {
+ MemoryItem ix = (MemoryItem)x.Tag;
+ MemoryItem iy = (MemoryItem)y.Tag;
- return ix.Size.CompareTo(iy.Size);
- });
+ return ix.Size.CompareTo(iy.Size);
+ });
}
private void listMemory_MouseUp(object sender, MouseEventArgs e)
@@ -92,20 +95,35 @@ private void listMemory_KeyDown(object sender, KeyEventArgs e)
if (!e.Handled)
{
- switch (e.KeyCode)
+ if (e.KeyCode == Keys.Enter)
{
- case Keys.Enter:
- this.readWriteMemoryMemoryMenuItem_Click(null, null);
- break;
+ readWriteMemoryMemoryMenuItem_Click(null, null);
}
}
}
#region Properties
+ public new bool DoubleBuffered
+ {
+ get
+ {
+ return (bool)typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).GetValue(listMemory, null);
+ }
+ set
+ {
+ typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).SetValue(listMemory, value, null);
+ }
+ }
+
public override bool Focused
{
- get { return listMemory.Focused; }
+ get
+ {
+ return listMemory.Focused;
+ }
}
public override ContextMenu ContextMenu
@@ -120,7 +138,7 @@ public override ContextMenuStrip ContextMenuStrip
set { listMemory.ContextMenuStrip = value; }
}
- public ExtendedListView List
+ public ListView List
{
get { return listMemory; }
}
@@ -132,10 +150,10 @@ public MemoryProvider Provider
{
if (_provider != null)
{
- _provider.DictionaryAdded -= this.provider_DictionaryAdded;
- _provider.DictionaryModified -= this.provider_DictionaryModified;
- _provider.DictionaryRemoved -= this.provider_DictionaryRemoved;
- _provider.Updated -= this.provider_Updated;
+ _provider.DictionaryAdded -= new MemoryProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryModified -= new MemoryProvider.ProviderDictionaryModified(provider_DictionaryModified);
+ _provider.DictionaryRemoved -= new MemoryProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated -= new MemoryProvider.ProviderUpdateOnce(provider_Updated);
}
_provider = value;
@@ -145,10 +163,10 @@ public MemoryProvider Provider
if (_provider != null)
{
- _provider.DictionaryAdded += this.provider_DictionaryAdded;
- _provider.DictionaryModified += this.provider_DictionaryModified;
- _provider.DictionaryRemoved += this.provider_DictionaryRemoved;
- _provider.Updated += this.provider_Updated;
+ _provider.DictionaryAdded += new MemoryProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryModified += new MemoryProvider.ProviderDictionaryModified(provider_DictionaryModified);
+ _provider.DictionaryRemoved += new MemoryProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated += new MemoryProvider.ProviderUpdateOnce(provider_Updated);
_pid = _provider.Pid;
foreach (MemoryItem item in _provider.Dictionary.Values)
@@ -190,7 +208,7 @@ private string GetProtectStr(MemoryProtection protect)
string protectStr;
if (protect == MemoryProtection.AccessDenied)
- protectStr = string.Empty;
+ protectStr = "";
else if ((protect & MemoryProtection.Execute) != 0)
protectStr = "X";
else if ((protect & MemoryProtection.ExecuteRead) != 0)
@@ -222,34 +240,28 @@ private string GetProtectStr(MemoryProtection protect)
private string GetStateStr(MemoryState state)
{
- switch (state)
- {
- case MemoryState.Commit:
- return "Commit";
- case MemoryState.Free:
- return "Free";
- case MemoryState.Reserve:
- return "Reserve";
- case MemoryState.Reset:
- return "Reset";
- default:
- return "Unknown";
- }
+ if (state == MemoryState.Commit)
+ return "Commit";
+ else if (state == MemoryState.Free)
+ return "Free";
+ else if (state == MemoryState.Reserve)
+ return "Reserve";
+ else if (state == MemoryState.Reset)
+ return "Reset";
+ else
+ return "Unknown";
}
private string GetTypeStr(MemoryType type)
{
- switch (type)
- {
- case MemoryType.Image:
- return "Image";
- case MemoryType.Mapped:
- return "Mapped";
- case MemoryType.Private:
- return "Private";
- default:
- return "Unknown";
- }
+ if (type == MemoryType.Image)
+ return "Image";
+ else if (type == MemoryType.Mapped)
+ return "Mapped";
+ else if (type == MemoryType.Private)
+ return "Private";
+ else
+ return "Unknown";
}
private void provider_Updated()
@@ -289,27 +301,23 @@ private void provider_Updated()
private void FillMemoryListViewItem(ListViewItem litem, MemoryItem item)
{
- switch (item.State)
+ if (item.State == MemoryState.Free)
{
- case MemoryState.Free:
- litem.Text = "Free";
- break;
- default:
- if (item.Type == MemoryType.Image)
- {
- if (!string.IsNullOrEmpty(item.ModuleName))
- litem.Text = item.ModuleName;
- else
- litem.Text = "Image";
+ litem.Text = "Free";
+ }
+ else if (item.Type == MemoryType.Image)
+ {
+ if (item.ModuleName != null)
+ litem.Text = item.ModuleName;
+ else
+ litem.Text = "Image";
- litem.Text += " (" + this.GetStateStr(item.State) + ")";
- }
- else
- {
- litem.Text = this.GetTypeStr(item.Type);
- litem.Text += " (" + this.GetStateStr(item.State) + ")";
- }
- break;
+ litem.Text += " (" + GetStateStr(item.State) + ")";
+ }
+ else
+ {
+ litem.Text = GetTypeStr(item.Type);
+ litem.Text += " (" + GetStateStr(item.State) + ")";
}
litem.SubItems[1].Text = Utils.FormatAddress(item.Address);
@@ -322,14 +330,14 @@ private void provider_DictionaryAdded(MemoryItem item)
{
this.BeginInvoke(new MethodInvoker(() =>
{
- HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext, item.RunId > 0 && _runCount > 0)
- {
- Name = item.Address.ToString()
- };
+ HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext,
+ item.RunId > 0 && _runCount > 0);
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
+ litem.Name = item.Address.ToString();
+
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
this.FillMemoryListViewItem(litem, item);
@@ -340,34 +348,34 @@ private void provider_DictionaryAdded(MemoryItem item)
private void provider_DictionaryModified(MemoryItem oldItem, MemoryItem newItem)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- lock (listMemory)
{
- ListViewItem litem = listMemory.Items[newItem.Address.ToString()];
+ lock (listMemory)
+ {
+ ListViewItem litem = listMemory.Items[newItem.Address.ToString()];
- if (litem != null)
- this.FillMemoryListViewItem(litem, newItem);
- }
- }));
+ if (litem != null)
+ this.FillMemoryListViewItem(litem, newItem);
+ }
+ }));
}
private void provider_DictionaryRemoved(MemoryItem item)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- lock (listMemory)
{
- // FIXME
- try
- {
- listMemory.Items.RemoveByKey(item.Address.ToString());
- }
- catch (Exception ex)
+ lock (listMemory)
{
- Logging.Log(ex);
+ // FIXME
+ try
+ {
+ listMemory.Items.RemoveByKey(item.Address.ToString());
+ }
+ catch (Exception ex)
+ {
+ Logging.Log(ex);
+ }
}
- }
- }));
+ }));
}
public void SaveSettings()
@@ -397,7 +405,7 @@ private void menuMemory_Popup(object sender, EventArgs e)
}
else
{
- //menuMemory.DisableAll();
+ menuMemory.DisableAll();
dumpMemoryMenuItem.Enabled = true;
readWriteAddressMemoryMenuItem.Enabled = true;
@@ -420,12 +428,10 @@ private void menuMemory_Popup(object sender, EventArgs e)
private void changeMemoryProtectionMemoryMenuItem_Click(object sender, EventArgs e)
{
- MemoryItem item = listMemory.SelectedItems[0].Tag as MemoryItem;
+ MemoryItem item = (MemoryItem)listMemory.SelectedItems[0].Tag;
+ VirtualProtectWindow w = new VirtualProtectWindow(_pid, item.Address, item.Size);
- using (VirtualProtectWindow w = new VirtualProtectWindow(_pid, item.Address, item.Size))
- {
- w.ShowDialog();
- }
+ w.ShowDialog();
}
private void readWriteMemoryMemoryMenuItem_Click(object sender, EventArgs e)
@@ -433,42 +439,48 @@ private void readWriteMemoryMemoryMenuItem_Click(object sender, EventArgs e)
if (listMemory.SelectedIndices.Count != 1)
return;
- MemoryItem item = listMemory.SelectedItems[0].Tag as MemoryItem;
+ MemoryItem item = (MemoryItem)listMemory.SelectedItems[0].Tag;
MemoryEditor.ReadWriteMemory(_pid, item.Address, (int)item.Size, false);
}
private void dumpMemoryMenuItem_Click(object sender, EventArgs e)
{
- using (SaveFileDialog sfd = new SaveFileDialog
- {
- FileName = "Memory.bin",
- Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*"
- })
+ SaveFileDialog sfd = new SaveFileDialog();
+
+ sfd.FileName = "Memory.bin";
+ sfd.Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*";
+
+ if (sfd.ShowDialog() == DialogResult.OK)
{
- if (sfd.ShowDialog() == DialogResult.OK)
+ try
{
- try
+ using (var phandle = new ProcessHandle(_pid, ProcessAccess.VmRead))
+ using (var fhandle = FileHandle.CreateWin32(sfd.FileName, FileAccess.GenericWrite, FileShareMode.Read))
{
- using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.VmRead))
- using (FileHandle fhandle = FileHandle.CreateWin32(sfd.FileName, FileAccess.GenericWrite, FileShareMode.Read))
+ foreach (ListViewItem litem in listMemory.SelectedItems)
{
- foreach (ListViewItem litem in listMemory.SelectedItems)
- {
- MemoryItem item = (MemoryItem)litem.Tag;
+ MemoryItem item = (MemoryItem)litem.Tag;
- using (MemoryAlloc alloc = new MemoryAlloc((int)item.Size))
+ using (MemoryAlloc alloc = new MemoryAlloc((int)item.Size))
+ {
+ try
{
- phandle.ReadMemory(item.Address, (IntPtr)alloc, (int)item.Size);
- fhandle.Write(alloc.Memory, (int)item.Size);
+ unsafe
+ {
+ phandle.ReadMemory(item.Address, (IntPtr)alloc, (int)item.Size);
+ fhandle.Write(alloc.Memory, (int)item.Size);
+ }
}
+ catch (WindowsException)
+ { }
}
}
}
- catch (Exception ex)
- {
- PhUtils.ShowException("Unable to dump the selected memory regions", ex);
- }
+ }
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to dump the selected memory regions", ex);
}
}
}
@@ -538,19 +550,14 @@ private void readWriteAddressMemoryMenuItem_Click(object sender, EventArgs e)
return;
}
- MemoryEditor.ReadWriteMemory(
- _pid,
- regionAddress,
- (int)regionSize,
- false,
- f => f.Select(address.Decrement(regionAddress).ToInt64(), 1)
- );
+ MemoryEditor m_e = MemoryEditor.ReadWriteMemory(_pid, regionAddress, (int)regionSize, false,
+ new Program.MemoryEditorInvokeAction(delegate(MemoryEditor f) { f.Select(address.Decrement(regionAddress).ToInt64(), 1); }));
}
}
private void selectAllMemoryMenuItem_Click(object sender, EventArgs e)
{
- this.listMemory.Items.SelectAll();
+ Utils.SelectAll(listMemory.Items);
}
private void freeMenuItem_Click(object sender, EventArgs e)
@@ -564,9 +571,10 @@ private void freeMenuItem_Click(object sender, EventArgs e)
{
try
{
- using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.VmOperation))
+ using (var phandle =
+ new ProcessHandle(_pid, ProcessAccess.VmOperation))
{
- MemoryItem item = listMemory.SelectedItems[0].Tag as MemoryItem;
+ MemoryItem item = (MemoryItem)listMemory.SelectedItems[0].Tag;
phandle.FreeMemory(item.Address, (int)item.Size, false);
}
@@ -589,9 +597,10 @@ private void decommitMenuItem_Click(object sender, EventArgs e)
{
try
{
- using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.VmOperation))
+ using (ProcessHandle phandle =
+ new ProcessHandle(_pid, ProcessAccess.VmOperation))
{
- MemoryItem item = listMemory.SelectedItems[0].Tag as MemoryItem;
+ MemoryItem item = (MemoryItem)listMemory.SelectedItems[0].Tag;
phandle.FreeMemory(item.Address, (int)item.Size, true);
}
diff --git a/1.x/trunk/ProcessHacker/Components/MemoryList.resx b/1.x/trunk/ProcessHacker/Components/MemoryList.resx
index 5c63cffa4..c7d3b3761 100644
--- a/1.x/trunk/ProcessHacker/Components/MemoryList.resx
+++ b/1.x/trunk/ProcessHacker/Components/MemoryList.resx
@@ -112,12 +112,15 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
+
+ 125, 17
+
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/MenuStripEx.cs b/1.x/trunk/ProcessHacker/Components/MenuStripEx.cs
deleted file mode 100644
index 218221483..000000000
--- a/1.x/trunk/ProcessHacker/Components/MenuStripEx.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Windows.Forms;
-
-namespace System
-{
- ///
- /// This class adds some missing functionality that should have been provided in System.Windows.Forms.MenuStrip.
- ///
- public class MenuStripEx : MenuStrip
- {
- private const uint WM_MOUSEACTIVATE = 0x21;
- private static readonly IntPtr MA_ACTIVATE = new IntPtr(1);
- private static readonly IntPtr MA_ACTIVATEANDEAT = new IntPtr(2);
- private const uint MA_NOACTIVATE = 3;
- private static readonly IntPtr MA_NOACTIVATEANDEAT = new IntPtr(4);
-
- private bool clickThrough = true;
-
- /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus.
- /// Default value is true, which is the same behavior provided by the base ToolStrip class.
- public bool ClickThrough
- {
- get { return this.clickThrough; }
- set { this.clickThrough = value; }
- }
-
- protected override void WndProc(ref Message m)
- {
- base.WndProc(ref m);
-
- if (this.clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == MA_ACTIVATEANDEAT)
- {
- m.Result = MA_ACTIVATE;
- }
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/MessageLabel.Designer.cs b/1.x/trunk/ProcessHacker/Components/MessageLabel.Designer.cs
index 3e7a7c74f..4317ba5ff 100644
--- a/1.x/trunk/ProcessHacker/Components/MessageLabel.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/MessageLabel.Designer.cs
@@ -46,9 +46,9 @@ private void InitializeComponent()
//
// labelText
//
- this.labelText.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.labelText.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.labelText.Location = new System.Drawing.Point(16, 0);
this.labelText.Name = "labelText";
this.labelText.Size = new System.Drawing.Size(170, 17);
@@ -58,7 +58,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.labelText);
this.Controls.Add(this.pictureIcon);
this.Name = "MessageLabel";
diff --git a/1.x/trunk/ProcessHacker/Components/MessageLabel.cs b/1.x/trunk/ProcessHacker/Components/MessageLabel.cs
index 10b29f6de..bd941c4f2 100644
--- a/1.x/trunk/ProcessHacker/Components/MessageLabel.cs
+++ b/1.x/trunk/ProcessHacker/Components/MessageLabel.cs
@@ -1,6 +1,9 @@
using System;
+using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
+using System.Data;
+using System.Text;
using System.Windows.Forms;
using ProcessHacker.Common;
using ProcessHacker.Native.Api;
@@ -27,9 +30,11 @@ public MessageLabelIcon Icon
get { return _icon; }
set
{
+ Image oldImage;
+
_icon = value;
- Image oldImage = this.pictureIcon.Image;
+ oldImage = pictureIcon.Image;
pictureIcon.Image = this.GetBitmap(_icon);
diff --git a/1.x/trunk/ProcessHacker/Components/MessageLabel.resx b/1.x/trunk/ProcessHacker/Components/MessageLabel.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/MessageLabel.resx
+++ b/1.x/trunk/ProcessHacker/Components/MessageLabel.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/ModuleList.Designer.cs b/1.x/trunk/ProcessHacker/Components/ModuleList.Designer.cs
index 3ae00532a..05a595408 100644
--- a/1.x/trunk/ProcessHacker/Components/ModuleList.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/ModuleList.Designer.cs
@@ -32,11 +32,12 @@ protected override void Dispose(bool disposing)
///
private void InitializeComponent()
{
- this.listModules = new ProcessHacker.Components.ExtendedListView();
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnBaseAddress = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnDesc = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.components = new System.ComponentModel.Container();
+ this.listModules = new System.Windows.Forms.ListView();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnBaseAddress = new System.Windows.Forms.ColumnHeader();
+ this.columnSize = new System.Windows.Forms.ColumnHeader();
+ this.columnDesc = new System.Windows.Forms.ColumnHeader();
this.changeMemoryProtectionModuleMenuItem = new System.Windows.Forms.MenuItem();
this.readMemoryModuleMenuItem = new System.Windows.Forms.MenuItem();
this.inspectModuleMenuItem = new System.Windows.Forms.MenuItem();
@@ -51,6 +52,8 @@ private void InitializeComponent()
this.copyFileNameMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.selectAllModuleMenuItem = new System.Windows.Forms.MenuItem();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
// listModules
@@ -62,7 +65,6 @@ private void InitializeComponent()
this.columnSize,
this.columnDesc});
this.listModules.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listModules.DoubleClickChecks = true;
this.listModules.FullRowSelect = true;
this.listModules.HideSelection = false;
this.listModules.Location = new System.Drawing.Point(0, 0);
@@ -96,41 +98,48 @@ private void InitializeComponent()
//
// changeMemoryProtectionModuleMenuItem
//
+ this.vistaMenu.SetImage(this.changeMemoryProtectionModuleMenuItem, global::ProcessHacker.Properties.Resources.lock_edit);
this.changeMemoryProtectionModuleMenuItem.Index = 0;
this.changeMemoryProtectionModuleMenuItem.Text = "Change &Memory Protection...";
this.changeMemoryProtectionModuleMenuItem.Click += new System.EventHandler(this.changeMemoryProtectionModuleMenuItem_Click);
//
// readMemoryModuleMenuItem
//
+ this.vistaMenu.SetImage(this.readMemoryModuleMenuItem, global::ProcessHacker.Properties.Resources.page);
this.readMemoryModuleMenuItem.Index = 2;
this.readMemoryModuleMenuItem.Text = "Read Memory";
this.readMemoryModuleMenuItem.Click += new System.EventHandler(this.readMemoryModuleMenuItem_Click);
//
// inspectModuleMenuItem
//
+ this.vistaMenu.SetImage(this.inspectModuleMenuItem, global::ProcessHacker.Properties.Resources.application_form_magnify);
this.inspectModuleMenuItem.Index = 5;
this.inspectModuleMenuItem.Text = "&Inspect";
this.inspectModuleMenuItem.Click += new System.EventHandler(this.inspectModuleMenuItem_Click);
//
// copyModuleMenuItem
//
+ this.vistaMenu.SetImage(this.copyModuleMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyModuleMenuItem.Index = 8;
this.copyModuleMenuItem.Text = "Copy";
//
// openContainingFolderMenuItem
//
+ this.vistaMenu.SetImage(this.openContainingFolderMenuItem, global::ProcessHacker.Properties.Resources.folder_explore);
this.openContainingFolderMenuItem.Index = 9;
this.openContainingFolderMenuItem.Text = "&Open Containing Folder";
this.openContainingFolderMenuItem.Click += new System.EventHandler(this.openContainingFolderMenuItem_Click);
//
// propertiesMenuItem
//
+ this.vistaMenu.SetImage(this.propertiesMenuItem, global::ProcessHacker.Properties.Resources.application_view_detail);
this.propertiesMenuItem.Index = 10;
this.propertiesMenuItem.Text = "Prope&rties";
this.propertiesMenuItem.Click += new System.EventHandler(this.propertiesMenuItem_Click);
//
// unloadMenuItem
//
+ this.vistaMenu.SetImage(this.unloadMenuItem, global::ProcessHacker.Properties.Resources.cross);
this.unloadMenuItem.Index = 3;
this.unloadMenuItem.Text = "&Unload";
this.unloadMenuItem.Click += new System.EventHandler(this.unloadMenuItem_Click);
@@ -187,24 +196,32 @@ private void InitializeComponent()
this.selectAllModuleMenuItem.Text = "Select &All";
this.selectAllModuleMenuItem.Click += new System.EventHandler(this.selectAllModuleMenuItem_Click);
//
+ // vistaMenu
+ //
+ this.vistaMenu.ContainerControl = this;
+ this.vistaMenu.DelaySetImageCalls = false;
+ //
// ModuleList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listModules);
+ this.DoubleBuffered = true;
this.Name = "ModuleList";
this.Size = new System.Drawing.Size(450, 472);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
+
}
#endregion
- private ExtendedListView listModules;
+ private System.Windows.Forms.ListView listModules;
private System.Windows.Forms.ColumnHeader columnBaseAddress;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ColumnHeader columnSize;
private System.Windows.Forms.ColumnHeader columnDesc;
+ private wyDay.Controls.VistaMenu vistaMenu;
private System.Windows.Forms.ContextMenu menuModule;
private System.Windows.Forms.MenuItem getFuncAddressMenuItem;
private System.Windows.Forms.MenuItem changeMemoryProtectionModuleMenuItem;
diff --git a/1.x/trunk/ProcessHacker/Components/ModuleList.cs b/1.x/trunk/ProcessHacker/Components/ModuleList.cs
index d6a001191..4e4f2d72c 100644
--- a/1.x/trunk/ProcessHacker/Components/ModuleList.cs
+++ b/1.x/trunk/ProcessHacker/Components/ModuleList.cs
@@ -24,6 +24,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
+using System.Reflection;
using System.Windows.Forms;
using Microsoft.Win32;
using ProcessHacker.Common;
@@ -39,9 +40,9 @@ namespace ProcessHacker.Components
public partial class ModuleList : UserControl
{
private ModuleProvider _provider;
- private int _runCount;
- private readonly List _needsAdd = new List();
- private readonly HighlightingContext _highlightingContext;
+ private int _runCount = 0;
+ private List _needsAdd = new List();
+ private HighlightingContext _highlightingContext;
public new event KeyEventHandler KeyDown;
public new event MouseEventHandler MouseDown;
public new event MouseEventHandler MouseUp;
@@ -54,10 +55,10 @@ public ModuleList()
InitializeComponent();
_highlightingContext = new HighlightingContext(listModules);
- listModules.KeyDown += this.ModuleList_KeyDown;
- listModules.MouseDown += this.listModules_MouseDown;
- listModules.MouseUp += this.listModules_MouseUp;
- listModules.DoubleClick += this.listModules_DoubleClick;
+ listModules.KeyDown += new KeyEventHandler(ModuleList_KeyDown);
+ listModules.MouseDown += new MouseEventHandler(listModules_MouseDown);
+ listModules.MouseUp += new MouseEventHandler(listModules_MouseUp);
+ listModules.DoubleClick += new EventHandler(listModules_DoubleClick);
ColumnSettings.LoadSettings(Settings.Instance.ModuleListViewColumns, listModules);
listModules.ContextMenu = menuModule;
@@ -90,6 +91,20 @@ private void ModuleList_KeyDown(object sender, KeyEventArgs e)
#region Properties
+ public new bool DoubleBuffered
+ {
+ get
+ {
+ return (bool)typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).GetValue(listModules, null);
+ }
+ set
+ {
+ typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).SetValue(listModules, value, null);
+ }
+ }
+
public override bool Focused
{
get
@@ -110,7 +125,7 @@ public override ContextMenuStrip ContextMenuStrip
set { listModules.ContextMenuStrip = value; }
}
- public ExtendedListView List
+ public ListView List
{
get { return listModules; }
}
@@ -122,9 +137,9 @@ public ModuleProvider Provider
{
if (_provider != null)
{
- _provider.DictionaryAdded -= this.provider_DictionaryAdded;
- _provider.DictionaryRemoved -= this.provider_DictionaryRemoved;
- _provider.Updated -= this.provider_Updated;
+ _provider.DictionaryAdded -= new ModuleProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryRemoved -= new ModuleProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated -= new ModuleProvider.ProviderUpdateOnce(provider_Updated);
}
_provider = value;
@@ -141,9 +156,9 @@ public ModuleProvider Provider
provider_DictionaryAdded(item);
}
- _provider.DictionaryAdded += this.provider_DictionaryAdded;
- _provider.DictionaryRemoved += this.provider_DictionaryRemoved;
- _provider.Updated += this.provider_Updated;
+ _provider.DictionaryAdded += new ModuleProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryRemoved += new ModuleProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated += new ModuleProvider.ProviderUpdateOnce(provider_Updated);
_pid = _provider.Pid;
try
@@ -154,8 +169,10 @@ public ModuleProvider Provider
}
else
{
- using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights | Program.MinProcessReadMemoryRights))
- _mainModule = FileUtils.GetFileName(phandle.MainModule.FileName);
+ using (var phandle =
+ new ProcessHandle(_pid,
+ Program.MinProcessQueryRights | Program.MinProcessReadMemoryRights))
+ _mainModule = FileUtils.GetFileName(phandle.GetMainModule().FileName);
}
this.SetMainModule(_mainModule);
@@ -246,12 +263,12 @@ private Color GetModuleColor(ModuleItem item)
(item.Flags & LdrpDataTableEntryFlags.CorImage) != 0
)
return Settings.Instance.ColorDotNetProcesses;
- if (Settings.Instance.UseColorRelocatedDlls &&
+ else if (Settings.Instance.UseColorRelocatedDlls &&
(item.Flags & LdrpDataTableEntryFlags.ImageNotAtBase) != 0
)
return Settings.Instance.ColorRelocatedDlls;
-
- return SystemColors.Window;
+ else
+ return SystemColors.Window;
}
public void AddItem(ModuleItem item)
@@ -270,22 +287,22 @@ public void DumpSetMainModule(string mainModule)
}
private void provider_DictionaryAdded(ModuleItem item)
- {
- HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext, item.RunId > 0 && _runCount > 0)
- {
- Name = item.BaseAddress.ToString(),
- Text = item.Name
- };
+ {
+ HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext,
+ item.RunId > 0 && _runCount > 0);
+ litem.Name = item.BaseAddress.ToString();
+ litem.Text = item.Name;
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, Utils.FormatAddress(item.BaseAddress)));
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, Utils.FormatSize(item.Size)));
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.FileDescription));
- litem.ToolTipText = PhUtils.FormatFileInfo(item.FileName, item.FileDescription, item.FileCompanyName, item.FileVersion, 0);
+ litem.ToolTipText = PhUtils.FormatFileInfo(
+ item.FileName, item.FileDescription, item.FileCompanyName, item.FileVersion, 0);
litem.Tag = item;
litem.NormalColor = this.GetModuleColor(item);
if (item.FileName.Equals(_mainModule, StringComparison.OrdinalIgnoreCase))
- litem.Font = new Font(litem.Font, FontStyle.Bold);
+ litem.Font = new System.Drawing.Font(litem.Font, System.Drawing.FontStyle.Bold);
lock (_needsAdd)
_needsAdd.Add(litem);
@@ -293,7 +310,10 @@ private void provider_DictionaryAdded(ModuleItem item)
private void provider_DictionaryRemoved(ModuleItem item)
{
- this.BeginInvoke(new MethodInvoker(() => this.listModules.Items[item.BaseAddress.ToString()].Remove()));
+ this.BeginInvoke(new MethodInvoker(() =>
+ {
+ listModules.Items[item.BaseAddress.ToString()].Remove();
+ }));
}
public void SaveSettings()
@@ -312,9 +332,9 @@ private void menuModule_Popup(object sender, EventArgs e)
{
if (_pid == 4)
{
- //menuModule.DisableAll();
+ menuModule.DisableAll();
- //if (KProcessHacker.Instance != null)
+ if (KProcessHacker.Instance != null)
unloadMenuItem.Enabled = true;
inspectModuleMenuItem.Enabled = true;
@@ -331,7 +351,7 @@ private void menuModule_Popup(object sender, EventArgs e)
}
else
{
- // menuModule.DisableAll();
+ menuModule.DisableAll();
if (listModules.SelectedItems.Count > 1)
{
@@ -365,7 +385,7 @@ private void searchModuleMenuItem_Click(object sender, EventArgs e)
private void copyFileNameMenuItem_Click(object sender, EventArgs e)
{
- string text = string.Empty;
+ string text = "";
for (int i = 0; i < listModules.SelectedItems.Count; i++)
{
@@ -399,14 +419,22 @@ private void inspectModuleMenuItem_Click(object sender, EventArgs e)
{
try
{
- Program.GetPEWindow(this.GetItemFileName(listModules.SelectedItems[0]), f =>
- {
- if (!f.IsDisposed)
+ PEWindow pw = Program.GetPEWindow(this.GetItemFileName(listModules.SelectedItems[0]),
+ new Program.PEWindowInvokeAction(delegate(PEWindow f)
{
- f.Show();
- f.Activate();
- }
- });
+ if (!f.IsDisposed)
+ {
+ try
+ {
+ f.Show();
+ f.Activate();
+ }
+ catch (Exception ex)
+ {
+ Logging.Log(ex);
+ }
+ }
+ }));
}
catch (Exception ex)
{
@@ -416,32 +444,30 @@ private void inspectModuleMenuItem_Click(object sender, EventArgs e)
private void getFuncAddressMenuItem_Click(object sender, EventArgs e)
{
- using (GetProcAddressWindow gpaWindow = new GetProcAddressWindow(this.GetItemFileName(listModules.SelectedItems[0])))
- {
- gpaWindow.ShowDialog();
- }
+ GetProcAddressWindow gpaWindow = new GetProcAddressWindow(
+ this.GetItemFileName(listModules.SelectedItems[0]));
+
+ gpaWindow.ShowDialog();
}
private void changeMemoryProtectionModuleMenuItem_Click(object sender, EventArgs e)
{
- ModuleItem item = this.listModules.SelectedItems[0].Tag as ModuleItem;
-
- using (VirtualProtectWindow w = new VirtualProtectWindow(_pid, item.BaseAddress.ToIntPtr(), item.Size))
- {
- w.ShowDialog();
- }
+ ModuleItem item = (ModuleItem)listModules.SelectedItems[0].Tag;
+ VirtualProtectWindow w = new VirtualProtectWindow(_pid, item.BaseAddress.ToIntPtr(), item.Size);
+
+ w.ShowDialog();
}
private void readMemoryModuleMenuItem_Click(object sender, EventArgs e)
{
- ModuleItem item = this.listModules.SelectedItems[0].Tag as ModuleItem;
+ ModuleItem item = (ModuleItem)listModules.SelectedItems[0].Tag;
MemoryEditor.ReadWriteMemory(_pid, item.BaseAddress.ToIntPtr(), item.Size, true);
}
private void selectAllModuleMenuItem_Click(object sender, EventArgs e)
{
- this.listModules.Items.SelectAll();
+ Utils.SelectAll(listModules.Items);
}
private void unloadMenuItem_Click(object sender, EventArgs e)
@@ -460,23 +486,23 @@ private void unloadMenuItem_Click(object sender, EventArgs e)
{
try
{
- ModuleItem moduleItem = listModules.SelectedItems[0].Tag as ModuleItem;
+ var moduleItem = (ModuleItem)listModules.SelectedItems[0].Tag;
string serviceName = null;
// Try to find the name of the service key for the driver by
// looping through the objects in the Driver directory and
// opening each one.
- using (DirectoryHandle dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query))
+ using (var dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query))
{
- foreach (DirectoryHandle.ObjectEntry obj in dhandle.GetObjects())
+ foreach (var obj in dhandle.GetObjects())
{
try
{
- using (DriverHandle driverHandle = new DriverHandle("\\Driver\\" + obj.Name))
+ using (var driverHandle = new DriverHandle("\\Driver\\" + obj.Name))
{
- if (driverHandle.BasicInformation.DriverStart == moduleItem.BaseAddress.ToIntPtr())
+ if (driverHandle.GetBasicInformation().DriverStart == moduleItem.BaseAddress.ToIntPtr())
{
- serviceName = driverHandle.ServiceKeyName;
+ serviceName = driverHandle.GetServiceKeyName();
break;
}
}
@@ -487,7 +513,7 @@ private void unloadMenuItem_Click(object sender, EventArgs e)
}
// If we didn't find the service name, use the driver base name.
- if (string.IsNullOrEmpty(serviceName))
+ if (serviceName == null)
{
if (moduleItem.Name.EndsWith(".sys", StringComparison.OrdinalIgnoreCase))
serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4);
@@ -495,13 +521,15 @@ private void unloadMenuItem_Click(object sender, EventArgs e)
serviceName = moduleItem.Name;
}
- RegistryKey servicesKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true);
+ RegistryKey servicesKey =
+ Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true);
bool serviceKeyCreated;
RegistryKey serviceKey;
// Check if the service key exists so that we don't delete it
// later if it does.
- if (Array.Exists(servicesKey.GetSubKeyNames(), keyName => string.Compare(keyName, serviceName, true) == 0))
+ if (Array.Exists(servicesKey.GetSubKeyNames(),
+ (keyName) => (string.Compare(keyName, serviceName, true) == 0)))
{
serviceKeyCreated = false;
}
@@ -544,10 +572,11 @@ private void unloadMenuItem_Click(object sender, EventArgs e)
{
try
{
- using (ProcessHandle phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights | ProcessAccess.VmOperation |
+ using (ProcessHandle phandle = new ProcessHandle(_pid,
+ Program.MinProcessQueryRights | ProcessAccess.VmOperation |
ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread))
{
- IntPtr baseAddress = (listModules.SelectedItems[0].Tag as ModuleItem).BaseAddress.ToIntPtr();
+ IntPtr baseAddress = ((ModuleItem)listModules.SelectedItems[0].Tag).BaseAddress.ToIntPtr();
phandle.SetModuleReferenceCount(baseAddress, 1);
@@ -579,11 +608,13 @@ private void unloadMenuItem_Click(object sender, EventArgs e)
{
if (OSVersion.Architecture == OSArch.Amd64)
{
- PhUtils.ShowError("Unable to find the module to unload. This may be caused by an attempt to unload a mapped file or a 32-bit module.");
+ PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
+ "by an attempt to unload a mapped file or a 32-bit module.");
}
else
{
- PhUtils.ShowError("Unable to find the module to unload. This may be caused by an attempt to unload a mapped file.");
+ PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
+ "by an attempt to unload a mapped file.");
}
}
else
@@ -606,7 +637,7 @@ private void unloadMenuItem_Click(object sender, EventArgs e)
public class ModuleListComparer : ISortedListViewComparer
{
- private readonly string _mainModule;
+ private string _mainModule;
public ModuleListComparer(string mainModule)
{
@@ -615,8 +646,8 @@ public ModuleListComparer(string mainModule)
public int Compare(ListViewItem x, ListViewItem y, int column)
{
- ModuleItem mx = x.Tag as ModuleItem;
- ModuleItem my = y.Tag as ModuleItem;
+ ModuleItem mx = (ModuleItem)x.Tag;
+ ModuleItem my = (ModuleItem)y.Tag;
if (mx.FileName.Equals(_mainModule, StringComparison.OrdinalIgnoreCase))
return -1;
diff --git a/1.x/trunk/ProcessHacker/Components/ModuleList.resx b/1.x/trunk/ProcessHacker/Components/ModuleList.resx
index 3863ef654..70244693e 100644
--- a/1.x/trunk/ProcessHacker/Components/ModuleList.resx
+++ b/1.x/trunk/ProcessHacker/Components/ModuleList.resx
@@ -112,12 +112,15 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
+ 17, 17
+
+
120, 20
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/MutantProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/MutantProperties.Designer.cs
index cd693c704..9fccd3850 100644
--- a/1.x/trunk/ProcessHacker/Components/MutantProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/MutantProperties.Designer.cs
@@ -44,7 +44,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 3);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(84, 13);
+ this.label1.Size = new System.Drawing.Size(75, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Current Count:";
//
@@ -53,7 +53,7 @@ private void InitializeComponent()
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 26);
this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(71, 13);
+ this.label3.Size = new System.Drawing.Size(65, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Abandoned:";
//
@@ -71,7 +71,7 @@ private void InitializeComponent()
this.labelAbandoned.AutoSize = true;
this.labelAbandoned.Location = new System.Drawing.Point(102, 26);
this.labelAbandoned.Name = "labelAbandoned";
- this.labelAbandoned.Size = new System.Drawing.Size(33, 13);
+ this.labelAbandoned.Size = new System.Drawing.Size(32, 13);
this.labelAbandoned.TabIndex = 0;
this.labelAbandoned.Text = "False";
//
@@ -80,14 +80,14 @@ private void InitializeComponent()
this.labelLabelOwner.AutoSize = true;
this.labelLabelOwner.Location = new System.Drawing.Point(6, 49);
this.labelLabelOwner.Name = "labelLabelOwner";
- this.labelLabelOwner.Size = new System.Drawing.Size(45, 13);
+ this.labelLabelOwner.Size = new System.Drawing.Size(41, 13);
this.labelLabelOwner.TabIndex = 1;
this.labelLabelOwner.Text = "Owner:";
//
// labelOwner
//
- this.labelOwner.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.labelOwner.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.labelOwner.AutoEllipsis = true;
this.labelOwner.Location = new System.Drawing.Point(102, 49);
this.labelOwner.Name = "labelOwner";
@@ -99,7 +99,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.labelOwner);
this.Controls.Add(this.labelLabelOwner);
this.Controls.Add(this.label3);
diff --git a/1.x/trunk/ProcessHacker/Components/MutantProperties.cs b/1.x/trunk/ProcessHacker/Components/MutantProperties.cs
index b0f1efe57..374225f07 100644
--- a/1.x/trunk/ProcessHacker/Components/MutantProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/MutantProperties.cs
@@ -1,13 +1,12 @@
using System.Windows.Forms;
using ProcessHacker.Native;
-using ProcessHacker.Native.Api;
using ProcessHacker.Native.Objects;
namespace ProcessHacker.Components
{
public partial class MutantProperties : UserControl
{
- private readonly MutantHandle _mutantHandle;
+ private MutantHandle _mutantHandle;
public MutantProperties(MutantHandle mutantHandle)
{
@@ -21,7 +20,7 @@ public MutantProperties(MutantHandle mutantHandle)
private void UpdateInfo()
{
- MutantBasicInformation basicInfo = _mutantHandle.BasicInformation;
+ var basicInfo = _mutantHandle.GetBasicInformation();
labelCurrentCount.Text = basicInfo.CurrentCount.ToString();
labelAbandoned.Text = basicInfo.AbandonedState.ToString();
@@ -29,7 +28,7 @@ private void UpdateInfo()
// Windows Vista and above have owner information.
if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
{
- MutantOwnerInformation ownerInfo = _mutantHandle.OwnerInformation;
+ var ownerInfo = _mutantHandle.GetOwnerInformation();
if (ownerInfo.ClientId.ProcessId != 0)
{
diff --git a/1.x/trunk/ProcessHacker/Components/MutantProperties.resx b/1.x/trunk/ProcessHacker/Components/MutantProperties.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/MutantProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/MutantProperties.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/NetworkList.Designer.cs b/1.x/trunk/ProcessHacker/Components/NetworkList.Designer.cs
index 5226dd496..9d62847ce 100644
--- a/1.x/trunk/ProcessHacker/Components/NetworkList.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/NetworkList.Designer.cs
@@ -34,14 +34,14 @@ private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NetworkList));
- this.listNetwork = new ProcessHacker.Components.ExtendedListView();
- this.columnProcess = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnLocal = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnLocalPort = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnRemote = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnRemotePort = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnProtocol = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnState = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.listNetwork = new System.Windows.Forms.ListView();
+ this.columnProcess = new System.Windows.Forms.ColumnHeader();
+ this.columnLocal = new System.Windows.Forms.ColumnHeader();
+ this.columnLocalPort = new System.Windows.Forms.ColumnHeader();
+ this.columnRemote = new System.Windows.Forms.ColumnHeader();
+ this.columnRemotePort = new System.Windows.Forms.ColumnHeader();
+ this.columnProtocol = new System.Windows.Forms.ColumnHeader();
+ this.columnState = new System.Windows.Forms.ColumnHeader();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
@@ -57,7 +57,6 @@ private void InitializeComponent()
this.columnProtocol,
this.columnState});
this.listNetwork.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listNetwork.DoubleClickChecks = true;
this.listNetwork.FullRowSelect = true;
this.listNetwork.HideSelection = false;
this.listNetwork.Location = new System.Drawing.Point(0, 0);
@@ -115,8 +114,8 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listNetwork);
+ this.DoubleBuffered = true;
this.Name = "NetworkList";
this.Size = new System.Drawing.Size(685, 472);
this.ResumeLayout(false);
@@ -125,7 +124,7 @@ private void InitializeComponent()
#endregion
- private ExtendedListView listNetwork;
+ private System.Windows.Forms.ListView listNetwork;
private System.Windows.Forms.ColumnHeader columnLocal;
private System.Windows.Forms.ColumnHeader columnRemote;
private System.Windows.Forms.ColumnHeader columnRemotePort;
diff --git a/1.x/trunk/ProcessHacker/Components/NetworkList.cs b/1.x/trunk/ProcessHacker/Components/NetworkList.cs
index 73c67c7e0..5e69f9658 100644
--- a/1.x/trunk/ProcessHacker/Components/NetworkList.cs
+++ b/1.x/trunk/ProcessHacker/Components/NetworkList.cs
@@ -23,6 +23,7 @@
using System;
using System.Collections.Generic;
using System.Drawing;
+using System.Reflection;
using System.Windows.Forms;
using ProcessHacker.Common;
using ProcessHacker.Common.Ui;
@@ -33,11 +34,11 @@ namespace ProcessHacker.Components
public partial class NetworkList : UserControl
{
private NetworkProvider _provider;
- private int _runCount;
- private readonly List _needsAdd = new List();
- private readonly HighlightingContext _highlightingContext;
- private bool _needsSort;
- private bool _needsImageKeyReset;
+ private int _runCount = 0;
+ private List _needsAdd = new List();
+ private HighlightingContext _highlightingContext;
+ private bool _needsSort = false;
+ private bool _needsImageKeyReset = false;
public new event KeyEventHandler KeyDown;
public new event MouseEventHandler MouseDown;
public new event MouseEventHandler MouseMove;
@@ -50,14 +51,14 @@ public NetworkList()
InitializeComponent();
_highlightingContext = new HighlightingContext(listNetwork);
-
+ listNetwork.SetTheme("explorer");
listNetwork.ListViewItemSorter = new SortedListViewComparer(listNetwork);
- listNetwork.KeyDown += this.NetworkList_KeyDown;
- listNetwork.MouseDown += this.listNetwork_MouseDown;
- listNetwork.MouseMove += this.listNetwork_MouseMove;
- listNetwork.MouseUp += this.listNetwork_MouseUp;
- listNetwork.DoubleClick += this.listNetwork_DoubleClick;
- listNetwork.SelectedIndexChanged += this.listNetwork_SelectedIndexChanged;
+ listNetwork.KeyDown += new KeyEventHandler(NetworkList_KeyDown);
+ listNetwork.MouseDown += new MouseEventHandler(listNetwork_MouseDown);
+ listNetwork.MouseMove += new MouseEventHandler(listNetwork_MouseMove);
+ listNetwork.MouseUp += new MouseEventHandler(listNetwork_MouseUp);
+ listNetwork.DoubleClick += new EventHandler(listNetwork_DoubleClick);
+ listNetwork.SelectedIndexChanged += new System.EventHandler(listNetwork_SelectedIndexChanged);
}
private void listNetwork_DoubleClick(object sender, EventArgs e)
@@ -95,7 +96,7 @@ private void listNetwork_MouseMove(object sender, MouseEventArgs e)
}
}
- private void listNetwork_SelectedIndexChanged(object sender, EventArgs e)
+ private void listNetwork_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (this.SelectedIndexChanged != null)
this.SelectedIndexChanged(sender, e);
@@ -109,6 +110,20 @@ private void NetworkList_KeyDown(object sender, KeyEventArgs e)
#region Properties
+ public new bool DoubleBuffered
+ {
+ get
+ {
+ return (bool)typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).GetValue(listNetwork, null);
+ }
+ set
+ {
+ typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).SetValue(listNetwork, value, null);
+ }
+ }
+
public override bool Focused
{
get
@@ -161,10 +176,10 @@ public NetworkProvider Provider
provider_DictionaryAdded(item);
}
- _provider.DictionaryAdded += this.provider_DictionaryAdded;
- _provider.DictionaryModified += this.provider_DictionaryModified;
- _provider.DictionaryRemoved += this.provider_DictionaryRemoved;
- _provider.Updated += this.provider_Updated;
+ _provider.DictionaryAdded += new NetworkProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryModified += new NetworkProvider.ProviderDictionaryModified(provider_DictionaryModified);
+ _provider.DictionaryRemoved += new NetworkProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated += new NetworkProvider.ProviderUpdateOnce(provider_Updated);
}
}
}
@@ -222,7 +237,7 @@ private void ResetImageKeys()
{
string t = lvItem.ImageKey;
- lvItem.ImageKey = string.Empty;
+ lvItem.ImageKey = "";
lvItem.ImageKey = t;
}
}
@@ -342,11 +357,10 @@ private void FillNetworkItemAddresses(ListViewItem litem, NetworkItem item)
private void provider_DictionaryAdded(NetworkItem item)
{
- HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext, item.Tag > 0 && _runCount > 0)
- {
- Name = item.Id,
- Tag = item
- };
+ HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext, (int)item.Tag > 0 && _runCount > 0);
+
+ litem.Name = item.Id;
+ litem.Tag = item;
Icon icon = null;
@@ -394,8 +408,8 @@ private void provider_DictionaryAdded(NetworkItem item)
}
else
{
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
}
if (item.Connection.Remote != null && !item.Connection.Remote.IsEmpty())
@@ -405,14 +419,14 @@ private void provider_DictionaryAdded(NetworkItem item)
}
else
{
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
}
this.FillNetworkItemAddresses(litem, item);
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Connection.Protocol.ToString().ToUpper()));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Connection.State != 0 ? item.Connection.State.ToString() : string.Empty));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Connection.State != 0 ? item.Connection.State.ToString() : ""));
lock (_needsAdd)
_needsAdd.Add(litem);
@@ -432,7 +446,7 @@ private void provider_DictionaryModified(NetworkItem oldItem, NetworkItem newIte
this.FillNetworkItemAddresses(litem, newItem);
- litem.SubItems[6].Text = newItem.Connection.State != 0 ? newItem.Connection.State.ToString() : string.Empty;
+ litem.SubItems[6].Text = newItem.Connection.State != 0 ? newItem.Connection.State.ToString() : "";
_needsSort = true;
}
}));
diff --git a/1.x/trunk/ProcessHacker/Components/NetworkList.resx b/1.x/trunk/ProcessHacker/Components/NetworkList.resx
index 253cdb668..c680ceefe 100644
--- a/1.x/trunk/ProcessHacker/Components/NetworkList.resx
+++ b/1.x/trunk/ProcessHacker/Components/NetworkList.resx
@@ -112,40 +112,40 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
- AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w
+ AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w
LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZTeXN0
ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMAAACc
- BQAAAk1TRnQBSQFMAwEBAAEkAQABJAEAARABAAEQAQAE/wEhAQAI/wFCAU0BNgcAATYDAAEoAwABQAMA
+ BQAAAk1TRnQBSQFMAwEBAAEcAQABHAEAARABAAEQAQAE/wEhAQAI/wFCAU0BNgcAATYDAAEoAwABQAMA
ARADAAEBAQABIAYAARD/AP8AFAABlwGSAY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGSAY8B/wGXAZIBjwH/
AZcBkgGPAf8BlwGSAY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGSAY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGS
AY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGSAY8B/8AAAZcBkgGPCf8D/gH/A/wB/wP6Af8D+AH/A/UB/wPz
Af8D8QH/A+4B/wPsAf8D6QH/A+gB/wPmAf8BlwGSAY8B/8AAAZcBkgGPCf8D/gH/A/wB/wP6Af8D+AH/
- A/UB/wP1Af8D8wH/A/AB/wPuAf8D6wH/A+kB/wPnAf8BlwGSAY8B/8AAAZcBkgGPBf8BhwGdAU0B/wGC
- AaIBUQH/AXUBqAFVAf8BbwGtAVkB/wFrAbEBXQH/A/cB/wHNAcwBygH/Ac0BzAHKAf8BzQHMAcoB/wHN
- AcwBygH/A+0B/wPrAf8D6AH/AZcBkgGPAf/AAAGXAZIBjwX/AY0BlAFHAf8BiQGaAUsB/wGEAaABTwH/
- AXcBpQFTAf8BcgGqAVcB/wP5Af8D9gH/A/QB/wP0Af8D8QH/A+8B/wPsAf8D6gH/AZcBkgGPAf/AAAGX
- AZIBjwX/AZMBiQFCAf8BjwGQAUUB/wGLAZcBSQH/AYcBnQFNAf8BggGiAVEB/wP7Af8BzQHMAcoB/wHN
- AcwBygH/Ac0BzAHKAf8BzQHMAcoB/wPxAf8BcwGpAVYB/wPsAf8BlwGSAY8B/8AAAZcBkgGPBf8BmAF0
- ATwB/wGVAYQBQAH/AZEBjAFDAf8BjQGUAUcB/wGJAZoBSwH/A/wB/wP6Af8D+AH/A/gB/wP1Af8D8wH/
- AYsBlwFJAf8D7gH/AZcBkgGPAf/AAAGXAZIBjwX/AZ0BagE3Af8BmgFxAToB/wGWAYABPgH/AZMBiQFC
- Af8BjwGQAUUB/wP9Af8BzQHMAcoB/wHNAcwBygH/Ac0BzAHKAf8BzQHMAcoB/wP1Af8BlwF2AT0B/wPv
- Af8BlwGSAY8B/8AAAZcBkgGPBf8BoAFiATQB/wGeAWcBNgH/AZsBbQE5Af8BmAF0ATwB/wGVAYQBQAH/
- A/4B/wP+Af8D/QH/A/sB/wP5Af8D9gH/AaABYgE0Af8D8QH/AZcBkgGPAf/AAAGXAZIBjxn/A/4B/wP+
+ A/UB/wP1Af8D8wH/A/AB/wPuAf8D6wH/A+kB/wPnAf8BlwGSAY8B/8AAAZcBkgGPBf8BhwGdAU4B/wGC
+ AaIBUgH/AXYBqAFWAf8BcAGtAVoB/wFsAbEBXgH/A/cB/wHNAcwBygH/Ac0BzAHKAf8BzQHMAcoB/wHN
+ AcwBygH/A+0B/wPrAf8D6AH/AZcBkgGPAf/AAAGXAZIBjwX/AY0BlAFIAf8BiQGaAUwB/wGEAaABUAH/
+ AXgBpQFUAf8BcwGqAVgB/wP5Af8D9gH/A/QB/wP0Af8D8QH/A+8B/wPsAf8D6gH/AZcBkgGPAf/AAAGX
+ AZIBjwX/AZMBiQFDAf8BjwGQAUYB/wGLAZcBSgH/AYcBnQFOAf8BggGiAVIB/wP7Af8BzQHMAcoB/wHN
+ AcwBygH/Ac0BzAHKAf8BzQHMAcoB/wPxAf8BdAGpAVcB/wPsAf8BlwGSAY8B/8AAAZcBkgGPBf8BmAF1
+ AT0B/wGVAYQBQQH/AZEBjAFEAf8BjQGUAUgB/wGJAZoBTAH/A/wB/wP6Af8D+AH/A/gB/wP1Af8D8wH/
+ AYsBlwFKAf8D7gH/AZcBkgGPAf/AAAGXAZIBjwX/AZ0BawE4Af8BmgFyATsB/wGWAYABPwH/AZMBiQFD
+ Af8BjwGQAUYB/wP9Af8BzQHMAcoB/wHNAcwBygH/Ac0BzAHKAf8BzQHMAcoB/wP1Af8BlwF3AT4B/wPv
+ Af8BlwGSAY8B/8AAAZcBkgGPBf8BoAFjATUB/wGeAWgBNwH/AZsBbgE6Af8BmAF1AT0B/wGVAYQBQQH/
+ A/4B/wP+Af8D/QH/A/sB/wP5Af8D9gH/AaABYwE1Af8D8QH/AZcBkgGPAf/AAAGXAZIBjxn/A/4B/wP+
Af8D/QH/A/sB/wP5Af8D9gH/A/QB/wPxAf8BlwGSAY8B/8AAAZcBkgGPAf8BzQHMAcoB/wHNAcwBygH/
Ac0BzAHKAf8BzQHMAcoB/wHNAcwBygH/Ac0BzAHKAf8BzQHMAcoB/wHNAcwBygH/Ac0BzAHKAf8BzQHM
AcoB/wHNAcwBygH/Ac0BzAHKAf8BzQHMAcoB/wHNAcwBygH/AZcBkgGPAf/AAAGXAZIBjwH/AeAB2QHT
Af8B4AHZAdMB/wHgAdkB0wH/AeAB2QHTAf8B4AHZAdMB/wHgAdkB0wH/AeAB2QHTAf8B4AHZAdMB/wHg
- AdkB0wH/AZEBcQFgAf8B4AHZAdMB/wGRAXEBYAH/AeAB2QHTAf8BkQFxAWAB/wGXAZIBjwH/wAABlwGS
+ AdkB0wH/AZEBcgFhAf8B4AHZAdMB/wGRAXIBYQH/AeAB2QHTAf8BkQFyAWEB/wGXAZIBjwH/wAABlwGS
AY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGSAY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGSAY8B/wGXAZIBjwH/
AZcBkgGPAf8BlwGSAY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGSAY8B/wGXAZIBjwH/AZcBkgGPAf8BlwGS
AY8B//8AwQABQgFNAT4HAAE+AwABKAMAAUADAAEQAwABAQEAAQEFAAGAFwAD/wEAAv8GAAL/bgAC/wYA
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/NodePlotter.cs b/1.x/trunk/ProcessHacker/Components/NodePlotter.cs
similarity index 90%
rename from 1.x/trunk/ProcessHacker/Components/TreeViewAdv/NodePlotter.cs
rename to 1.x/trunk/ProcessHacker/Components/NodePlotter.cs
index 52dbff182..0a14d66eb 100644
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/NodePlotter.cs
+++ b/1.x/trunk/ProcessHacker/Components/NodePlotter.cs
@@ -57,12 +57,10 @@ public override void Draw(TreeNodeAdv node, DrawContext context)
if (_plotter == null)
{
- _plotter = new Plotter
- {
- BackColor = Color.Black,
- ShowGrid = false,
- OverlaySecondLine = false
- };
+ _plotter = new Plotter();
+ _plotter.BackColor = Color.Black;
+ _plotter.ShowGrid = false;
+ _plotter.OverlaySecondLine = false;
}
if (info.UseLongData)
@@ -93,7 +91,6 @@ public override void Draw(TreeNodeAdv node, DrawContext context)
using (Bitmap b = new Bitmap(_plotter.Width, _plotter.Height))
{
_plotter.DrawToBitmap(b, new Rectangle(0, 0, b.Width, b.Height));
-
context.Graphics.DrawImage(b, context.Bounds.Location);
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/Plotter.Designer.cs b/1.x/trunk/ProcessHacker/Components/Plotter.Designer.cs
index 8fb94fae8..9350da62c 100644
--- a/1.x/trunk/ProcessHacker/Components/Plotter.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/Plotter.Designer.cs
@@ -45,14 +45,13 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Name = "Plotter";
this.Size = new System.Drawing.Size(150, 163);
- this.Paint += new System.Windows.Forms.PaintEventHandler(this.Plotter_Paint);
- this.MouseEnter += new System.EventHandler(this.Plotter_MouseEnter);
this.MouseLeave += new System.EventHandler(this.Plotter_MouseLeave);
+ this.Paint += new System.Windows.Forms.PaintEventHandler(this.Plotter_Paint);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Plotter_MouseMove);
this.Resize += new System.EventHandler(this.Plotter_Resize);
+ this.MouseEnter += new System.EventHandler(this.Plotter_MouseEnter);
this.ResumeLayout(false);
}
diff --git a/1.x/trunk/ProcessHacker/Components/Plotter.cs b/1.x/trunk/ProcessHacker/Components/Plotter.cs
index 79aaf14b0..95e339cf9 100644
--- a/1.x/trunk/ProcessHacker/Components/Plotter.cs
+++ b/1.x/trunk/ProcessHacker/Components/Plotter.cs
@@ -65,11 +65,18 @@ public Plotter()
public GetToolTipDelegate GetToolTip;
- private int _gridStartPos;
+ private int _gridStartPos = 0;
private void Plotter_Paint(object sender, PaintEventArgs e)
{
- this.Render(e.Graphics);
+ try
+ {
+ this.Render(e.Graphics);
+ }
+ catch (Exception ex)
+ {
+ Logging.Log(ex);
+ }
}
public void Render(Graphics g)
@@ -148,11 +155,10 @@ public void Draw(Graphics g)
int hPre = (int)(tHeight - (tHeight * fPre));
// Fill in the area below the line.
- g.FillPolygon(new SolidBrush(Color.FromArgb(100, _lineColor1)),new Point[]
- {
- new Point(px, h), new Point(px + moveStep, hPre),
- new Point(px + moveStep, tHeight), new Point(px, tHeight)
- });
+
+ g.FillPolygon(new SolidBrush(Color.FromArgb(100, _lineColor1)),
+ new Point[] { new Point(px, h), new Point(px + moveStep, hPre),
+ new Point(px + moveStep, tHeight), new Point(px, tHeight) });
g.DrawLine(lGrid1, px, h, px + moveStep, hPre);
if (this.UseSecondLine)
@@ -175,25 +181,20 @@ public void Draw(Graphics g)
hPre = (int)(tHeight - (tHeight * fPre));
// Draw the second line.
+
if (this.OverlaySecondLine)
{
- g.FillPolygon(new SolidBrush(Color.FromArgb(100, _lineColor2)), new Point[]
- {
- new Point(px, h), new Point(px + moveStep, hPre),
- new Point(px + moveStep, tHeight), new Point(px, tHeight)
- });
-
+ g.FillPolygon(new SolidBrush(Color.FromArgb(100, _lineColor2)),
+ new Point[] { new Point(px, h), new Point(px + moveStep, hPre),
+ new Point(px + moveStep, tHeight), new Point(px, tHeight) });
g.DrawLine(lGrid2, px, h, px + moveStep, hPre);
}
else
{
- g.FillPolygon(new SolidBrush(Color.FromArgb(100, _lineColor2)), new Point[]
- {
- new Point(px, h), new Point(px + moveStep, hPre),
+ g.FillPolygon(new SolidBrush(Color.FromArgb(100, _lineColor2)),
+ new Point[] { new Point(px, h), new Point(px + moveStep, hPre),
new Point(px + moveStep, tHeight - (int)(tHeight * _data1[start])),
- new Point(px, tHeight - (int)(tHeight * _data1[start + 1]))
- });
-
+ new Point(px, tHeight - (int)(tHeight * _data1[start + 1])) });
g.DrawLine(lGrid2, px, h, px + moveStep, hPre);
}
}
@@ -219,7 +220,12 @@ public void Draw(Graphics g)
}
}
- private void ShowToolTip(bool force = false)
+ private void ShowToolTip()
+ {
+ this.ShowToolTip(false);
+ }
+
+ private void ShowToolTip(bool force)
{
if (this.GetToolTip != null)
{
@@ -335,7 +341,7 @@ public override string Text
{
base.Text = _text = value;
- _textSize = this.CreateGraphics().GetCachedSize(this.Text, this.Font);
+ _textSize = TextRenderer.MeasureText(this.Text, this.Font);
_boxSize = new Size(
_textSize.Width + _textPadding.Left + _textPadding.Right,
_textSize.Height + _textPadding.Top + _textPadding.Bottom);
diff --git a/1.x/trunk/ProcessHacker/Components/Plotter.resx b/1.x/trunk/ProcessHacker/Components/Plotter.resx
index 026c576b4..a5979aadf 100644
--- a/1.x/trunk/ProcessHacker/Components/Plotter.resx
+++ b/1.x/trunk/ProcessHacker/Components/Plotter.resx
@@ -112,12 +112,12 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessStatistics.Designer.cs b/1.x/trunk/ProcessHacker/Components/ProcessStatistics.Designer.cs
index 9285e96ad..429319c24 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessStatistics.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/ProcessStatistics.Designer.cs
@@ -136,7 +136,7 @@ private void InitializeComponent()
this.tableLayoutPanel1.Controls.Add(this.labelCPUCyclesText, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelCPUCycles, 1, 1);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 18);
+ this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 5;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
@@ -144,7 +144,7 @@ private void InitializeComponent()
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
- this.tableLayoutPanel1.Size = new System.Drawing.Size(189, 87);
+ this.tableLayoutPanel1.Size = new System.Drawing.Size(189, 89);
this.tableLayoutPanel1.TabIndex = 1;
//
// label6
@@ -153,7 +153,7 @@ private void InitializeComponent()
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(3, 2);
this.label6.Name = "label6";
- this.label6.Size = new System.Drawing.Size(43, 13);
+ this.label6.Size = new System.Drawing.Size(38, 13);
this.label6.TabIndex = 1;
this.label6.Text = "Priority";
//
@@ -163,7 +163,7 @@ private void InitializeComponent()
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(3, 36);
this.label8.Name = "label8";
- this.label8.Size = new System.Drawing.Size(65, 13);
+ this.label8.Size = new System.Drawing.Size(63, 13);
this.label8.TabIndex = 1;
this.label8.Text = "Kernel Time";
//
@@ -173,7 +173,7 @@ private void InitializeComponent()
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(3, 53);
this.label9.Name = "label9";
- this.label9.Size = new System.Drawing.Size(56, 13);
+ this.label9.Size = new System.Drawing.Size(55, 13);
this.label9.TabIndex = 1;
this.label9.Text = "User Time";
//
@@ -181,9 +181,9 @@ private void InitializeComponent()
//
this.label10.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label10.AutoSize = true;
- this.label10.Location = new System.Drawing.Point(3, 71);
+ this.label10.Location = new System.Drawing.Point(3, 72);
this.label10.Name = "label10";
- this.label10.Size = new System.Drawing.Size(58, 13);
+ this.label10.Size = new System.Drawing.Size(57, 13);
this.label10.TabIndex = 1;
this.label10.Text = "Total Time";
//
@@ -191,9 +191,9 @@ private void InitializeComponent()
//
this.labelCPUPriority.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelCPUPriority.AutoSize = true;
- this.labelCPUPriority.Location = new System.Drawing.Point(152, 2);
+ this.labelCPUPriority.Location = new System.Drawing.Point(153, 2);
this.labelCPUPriority.Name = "labelCPUPriority";
- this.labelCPUPriority.Size = new System.Drawing.Size(34, 13);
+ this.labelCPUPriority.Size = new System.Drawing.Size(33, 13);
this.labelCPUPriority.TabIndex = 1;
this.labelCPUPriority.Text = "value";
//
@@ -201,9 +201,9 @@ private void InitializeComponent()
//
this.labelCPUKernelTime.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelCPUKernelTime.AutoSize = true;
- this.labelCPUKernelTime.Location = new System.Drawing.Point(152, 36);
+ this.labelCPUKernelTime.Location = new System.Drawing.Point(153, 36);
this.labelCPUKernelTime.Name = "labelCPUKernelTime";
- this.labelCPUKernelTime.Size = new System.Drawing.Size(34, 13);
+ this.labelCPUKernelTime.Size = new System.Drawing.Size(33, 13);
this.labelCPUKernelTime.TabIndex = 1;
this.labelCPUKernelTime.Text = "value";
//
@@ -211,9 +211,9 @@ private void InitializeComponent()
//
this.labelCPUUserTime.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelCPUUserTime.AutoSize = true;
- this.labelCPUUserTime.Location = new System.Drawing.Point(152, 53);
+ this.labelCPUUserTime.Location = new System.Drawing.Point(153, 53);
this.labelCPUUserTime.Name = "labelCPUUserTime";
- this.labelCPUUserTime.Size = new System.Drawing.Size(34, 13);
+ this.labelCPUUserTime.Size = new System.Drawing.Size(33, 13);
this.labelCPUUserTime.TabIndex = 1;
this.labelCPUUserTime.Text = "value";
//
@@ -221,9 +221,9 @@ private void InitializeComponent()
//
this.labelCPUTotalTime.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelCPUTotalTime.AutoSize = true;
- this.labelCPUTotalTime.Location = new System.Drawing.Point(152, 71);
+ this.labelCPUTotalTime.Location = new System.Drawing.Point(153, 72);
this.labelCPUTotalTime.Name = "labelCPUTotalTime";
- this.labelCPUTotalTime.Size = new System.Drawing.Size(34, 13);
+ this.labelCPUTotalTime.Size = new System.Drawing.Size(33, 13);
this.labelCPUTotalTime.TabIndex = 1;
this.labelCPUTotalTime.Text = "value";
//
@@ -241,9 +241,9 @@ private void InitializeComponent()
//
this.labelCPUCycles.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelCPUCycles.AutoSize = true;
- this.labelCPUCycles.Location = new System.Drawing.Point(152, 19);
+ this.labelCPUCycles.Location = new System.Drawing.Point(153, 19);
this.labelCPUCycles.Name = "labelCPUCycles";
- this.labelCPUCycles.Size = new System.Drawing.Size(34, 13);
+ this.labelCPUCycles.Size = new System.Drawing.Size(33, 13);
this.labelCPUCycles.TabIndex = 1;
this.labelCPUCycles.Text = "value";
//
@@ -281,7 +281,7 @@ private void InitializeComponent()
this.tableLayoutPanel2.Controls.Add(this.label30, 0, 8);
this.tableLayoutPanel2.Controls.Add(this.labelMemoryPP, 1, 8);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
- this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 18);
+ this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 9;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 11.11111F));
@@ -293,7 +293,7 @@ private void InitializeComponent()
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 11.11111F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 11.11111F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 11.11111F));
- this.tableLayoutPanel2.Size = new System.Drawing.Size(189, 173);
+ this.tableLayoutPanel2.Size = new System.Drawing.Size(189, 175);
this.tableLayoutPanel2.TabIndex = 1;
//
// label24
@@ -302,7 +302,7 @@ private void InitializeComponent()
this.label24.AutoSize = true;
this.label24.Location = new System.Drawing.Point(3, 117);
this.label24.Name = "label24";
- this.label24.Size = new System.Drawing.Size(110, 13);
+ this.label24.Size = new System.Drawing.Size(107, 13);
this.label24.TabIndex = 7;
this.label24.Text = "Peak Pagefile Usage";
//
@@ -312,7 +312,7 @@ private void InitializeComponent()
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point(3, 98);
this.label22.Name = "label22";
- this.label22.Size = new System.Drawing.Size(83, 13);
+ this.label22.Size = new System.Drawing.Size(79, 13);
this.label22.TabIndex = 5;
this.label22.Text = "Pagefile Usage";
//
@@ -322,7 +322,7 @@ private void InitializeComponent()
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(3, 79);
this.label20.Name = "label20";
- this.label20.Size = new System.Drawing.Size(91, 13);
+ this.label20.Size = new System.Drawing.Size(87, 13);
this.label20.TabIndex = 3;
this.label20.Text = "Peak Virtual Size";
//
@@ -332,7 +332,7 @@ private void InitializeComponent()
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(3, 3);
this.label11.Name = "label11";
- this.label11.Size = new System.Drawing.Size(71, 13);
+ this.label11.Size = new System.Drawing.Size(69, 13);
this.label11.TabIndex = 1;
this.label11.Text = "Private Bytes";
//
@@ -342,7 +342,7 @@ private void InitializeComponent()
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(3, 22);
this.label12.Name = "label12";
- this.label12.Size = new System.Drawing.Size(71, 13);
+ this.label12.Size = new System.Drawing.Size(66, 13);
this.label12.TabIndex = 1;
this.label12.Text = "Working Set";
//
@@ -352,7 +352,7 @@ private void InitializeComponent()
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(3, 41);
this.label13.Name = "label13";
- this.label13.Size = new System.Drawing.Size(98, 13);
+ this.label13.Size = new System.Drawing.Size(94, 13);
this.label13.TabIndex = 1;
this.label13.Text = "Peak Working Set";
//
@@ -362,7 +362,7 @@ private void InitializeComponent()
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(3, 60);
this.label14.Name = "label14";
- this.label14.Size = new System.Drawing.Size(64, 13);
+ this.label14.Size = new System.Drawing.Size(59, 13);
this.label14.TabIndex = 1;
this.label14.Text = "Virtual Size";
//
@@ -370,9 +370,9 @@ private void InitializeComponent()
//
this.labelMemoryPB.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryPB.AutoSize = true;
- this.labelMemoryPB.Location = new System.Drawing.Point(152, 3);
+ this.labelMemoryPB.Location = new System.Drawing.Point(153, 3);
this.labelMemoryPB.Name = "labelMemoryPB";
- this.labelMemoryPB.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryPB.Size = new System.Drawing.Size(33, 13);
this.labelMemoryPB.TabIndex = 1;
this.labelMemoryPB.Text = "value";
//
@@ -380,9 +380,9 @@ private void InitializeComponent()
//
this.labelMemoryWS.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryWS.AutoSize = true;
- this.labelMemoryWS.Location = new System.Drawing.Point(152, 22);
+ this.labelMemoryWS.Location = new System.Drawing.Point(153, 22);
this.labelMemoryWS.Name = "labelMemoryWS";
- this.labelMemoryWS.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryWS.Size = new System.Drawing.Size(33, 13);
this.labelMemoryWS.TabIndex = 1;
this.labelMemoryWS.Text = "value";
//
@@ -390,9 +390,9 @@ private void InitializeComponent()
//
this.labelMemoryPWS.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryPWS.AutoSize = true;
- this.labelMemoryPWS.Location = new System.Drawing.Point(152, 41);
+ this.labelMemoryPWS.Location = new System.Drawing.Point(153, 41);
this.labelMemoryPWS.Name = "labelMemoryPWS";
- this.labelMemoryPWS.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryPWS.Size = new System.Drawing.Size(33, 13);
this.labelMemoryPWS.TabIndex = 1;
this.labelMemoryPWS.Text = "value";
//
@@ -400,9 +400,9 @@ private void InitializeComponent()
//
this.labelMemoryVS.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryVS.AutoSize = true;
- this.labelMemoryVS.Location = new System.Drawing.Point(152, 60);
+ this.labelMemoryVS.Location = new System.Drawing.Point(153, 60);
this.labelMemoryVS.Name = "labelMemoryVS";
- this.labelMemoryVS.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryVS.Size = new System.Drawing.Size(33, 13);
this.labelMemoryVS.TabIndex = 1;
this.labelMemoryVS.Text = "value";
//
@@ -410,9 +410,9 @@ private void InitializeComponent()
//
this.labelMemoryPVS.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryPVS.AutoSize = true;
- this.labelMemoryPVS.Location = new System.Drawing.Point(152, 79);
+ this.labelMemoryPVS.Location = new System.Drawing.Point(153, 79);
this.labelMemoryPVS.Name = "labelMemoryPVS";
- this.labelMemoryPVS.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryPVS.Size = new System.Drawing.Size(33, 13);
this.labelMemoryPVS.TabIndex = 1;
this.labelMemoryPVS.Text = "value";
//
@@ -420,9 +420,9 @@ private void InitializeComponent()
//
this.labelMemoryPU.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryPU.AutoSize = true;
- this.labelMemoryPU.Location = new System.Drawing.Point(152, 98);
+ this.labelMemoryPU.Location = new System.Drawing.Point(153, 98);
this.labelMemoryPU.Name = "labelMemoryPU";
- this.labelMemoryPU.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryPU.Size = new System.Drawing.Size(33, 13);
this.labelMemoryPU.TabIndex = 1;
this.labelMemoryPU.Text = "value";
//
@@ -430,9 +430,9 @@ private void InitializeComponent()
//
this.labelMemoryPPU.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryPPU.AutoSize = true;
- this.labelMemoryPPU.Location = new System.Drawing.Point(152, 117);
+ this.labelMemoryPPU.Location = new System.Drawing.Point(153, 117);
this.labelMemoryPPU.Name = "labelMemoryPPU";
- this.labelMemoryPPU.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryPPU.Size = new System.Drawing.Size(33, 13);
this.labelMemoryPPU.TabIndex = 1;
this.labelMemoryPPU.Text = "value";
//
@@ -442,7 +442,7 @@ private void InitializeComponent()
this.label25.AutoSize = true;
this.label25.Location = new System.Drawing.Point(3, 136);
this.label25.Name = "label25";
- this.label25.Size = new System.Drawing.Size(66, 13);
+ this.label25.Size = new System.Drawing.Size(63, 13);
this.label25.TabIndex = 7;
this.label25.Text = "Page Faults";
//
@@ -450,9 +450,9 @@ private void InitializeComponent()
//
this.labelMemoryPF.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryPF.AutoSize = true;
- this.labelMemoryPF.Location = new System.Drawing.Point(152, 136);
+ this.labelMemoryPF.Location = new System.Drawing.Point(153, 136);
this.labelMemoryPF.Name = "labelMemoryPF";
- this.labelMemoryPF.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryPF.Size = new System.Drawing.Size(33, 13);
this.labelMemoryPF.TabIndex = 1;
this.labelMemoryPF.Text = "value";
//
@@ -460,9 +460,9 @@ private void InitializeComponent()
//
this.label30.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label30.AutoSize = true;
- this.label30.Location = new System.Drawing.Point(3, 156);
+ this.label30.Location = new System.Drawing.Point(3, 157);
this.label30.Name = "label30";
- this.label30.Size = new System.Drawing.Size(71, 13);
+ this.label30.Size = new System.Drawing.Size(66, 13);
this.label30.TabIndex = 7;
this.label30.Text = "Page Priority";
//
@@ -470,9 +470,9 @@ private void InitializeComponent()
//
this.labelMemoryPP.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelMemoryPP.AutoSize = true;
- this.labelMemoryPP.Location = new System.Drawing.Point(152, 156);
+ this.labelMemoryPP.Location = new System.Drawing.Point(153, 157);
this.labelMemoryPP.Name = "labelMemoryPP";
- this.labelMemoryPP.Size = new System.Drawing.Size(34, 13);
+ this.labelMemoryPP.Size = new System.Drawing.Size(33, 13);
this.labelMemoryPP.TabIndex = 1;
this.labelMemoryPP.Text = "value";
//
@@ -506,7 +506,7 @@ private void InitializeComponent()
this.tableLayoutPanel3.Controls.Add(this.label31, 0, 6);
this.tableLayoutPanel3.Controls.Add(this.labelIOPriority, 1, 6);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
- this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 18);
+ this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 7;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 14.28571F));
@@ -516,7 +516,7 @@ private void InitializeComponent()
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 14.28571F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 14.28571F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 14.28571F));
- this.tableLayoutPanel3.Size = new System.Drawing.Size(189, 127);
+ this.tableLayoutPanel3.Size = new System.Drawing.Size(189, 129);
this.tableLayoutPanel3.TabIndex = 1;
//
// label16
@@ -525,7 +525,7 @@ private void InitializeComponent()
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(3, 92);
this.label16.Name = "label16";
- this.label16.Size = new System.Drawing.Size(67, 13);
+ this.label16.Size = new System.Drawing.Size(62, 13);
this.label16.TabIndex = 5;
this.label16.Text = "Other Bytes";
//
@@ -535,7 +535,7 @@ private void InitializeComponent()
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(3, 74);
this.label17.Name = "label17";
- this.label17.Size = new System.Drawing.Size(37, 13);
+ this.label17.Size = new System.Drawing.Size(33, 13);
this.label17.TabIndex = 3;
this.label17.Text = "Other";
//
@@ -555,7 +555,7 @@ private void InitializeComponent()
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(3, 20);
this.label19.Name = "label19";
- this.label19.Size = new System.Drawing.Size(63, 13);
+ this.label19.Size = new System.Drawing.Size(62, 13);
this.label19.TabIndex = 1;
this.label19.Text = "Read Bytes";
//
@@ -565,7 +565,7 @@ private void InitializeComponent()
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(3, 38);
this.label21.Name = "label21";
- this.label21.Size = new System.Drawing.Size(40, 13);
+ this.label21.Size = new System.Drawing.Size(37, 13);
this.label21.TabIndex = 1;
this.label21.Text = "Writes";
//
@@ -575,7 +575,7 @@ private void InitializeComponent()
this.label23.AutoSize = true;
this.label23.Location = new System.Drawing.Point(3, 56);
this.label23.Name = "label23";
- this.label23.Size = new System.Drawing.Size(65, 13);
+ this.label23.Size = new System.Drawing.Size(61, 13);
this.label23.TabIndex = 1;
this.label23.Text = "Write Bytes";
//
@@ -583,9 +583,9 @@ private void InitializeComponent()
//
this.labelIOReads.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelIOReads.AutoSize = true;
- this.labelIOReads.Location = new System.Drawing.Point(152, 2);
+ this.labelIOReads.Location = new System.Drawing.Point(153, 2);
this.labelIOReads.Name = "labelIOReads";
- this.labelIOReads.Size = new System.Drawing.Size(34, 13);
+ this.labelIOReads.Size = new System.Drawing.Size(33, 13);
this.labelIOReads.TabIndex = 1;
this.labelIOReads.Text = "value";
//
@@ -593,9 +593,9 @@ private void InitializeComponent()
//
this.labelIOReadBytes.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelIOReadBytes.AutoSize = true;
- this.labelIOReadBytes.Location = new System.Drawing.Point(152, 20);
+ this.labelIOReadBytes.Location = new System.Drawing.Point(153, 20);
this.labelIOReadBytes.Name = "labelIOReadBytes";
- this.labelIOReadBytes.Size = new System.Drawing.Size(34, 13);
+ this.labelIOReadBytes.Size = new System.Drawing.Size(33, 13);
this.labelIOReadBytes.TabIndex = 1;
this.labelIOReadBytes.Text = "value";
//
@@ -603,9 +603,9 @@ private void InitializeComponent()
//
this.labelIOWrites.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelIOWrites.AutoSize = true;
- this.labelIOWrites.Location = new System.Drawing.Point(152, 38);
+ this.labelIOWrites.Location = new System.Drawing.Point(153, 38);
this.labelIOWrites.Name = "labelIOWrites";
- this.labelIOWrites.Size = new System.Drawing.Size(34, 13);
+ this.labelIOWrites.Size = new System.Drawing.Size(33, 13);
this.labelIOWrites.TabIndex = 1;
this.labelIOWrites.Text = "value";
//
@@ -613,9 +613,9 @@ private void InitializeComponent()
//
this.labelIOWriteBytes.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelIOWriteBytes.AutoSize = true;
- this.labelIOWriteBytes.Location = new System.Drawing.Point(152, 56);
+ this.labelIOWriteBytes.Location = new System.Drawing.Point(153, 56);
this.labelIOWriteBytes.Name = "labelIOWriteBytes";
- this.labelIOWriteBytes.Size = new System.Drawing.Size(34, 13);
+ this.labelIOWriteBytes.Size = new System.Drawing.Size(33, 13);
this.labelIOWriteBytes.TabIndex = 1;
this.labelIOWriteBytes.Text = "value";
//
@@ -623,9 +623,9 @@ private void InitializeComponent()
//
this.labelIOOther.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelIOOther.AutoSize = true;
- this.labelIOOther.Location = new System.Drawing.Point(152, 74);
+ this.labelIOOther.Location = new System.Drawing.Point(153, 74);
this.labelIOOther.Name = "labelIOOther";
- this.labelIOOther.Size = new System.Drawing.Size(34, 13);
+ this.labelIOOther.Size = new System.Drawing.Size(33, 13);
this.labelIOOther.TabIndex = 1;
this.labelIOOther.Text = "value";
//
@@ -633,9 +633,9 @@ private void InitializeComponent()
//
this.labelIOOtherBytes.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelIOOtherBytes.AutoSize = true;
- this.labelIOOtherBytes.Location = new System.Drawing.Point(152, 92);
+ this.labelIOOtherBytes.Location = new System.Drawing.Point(153, 92);
this.labelIOOtherBytes.Name = "labelIOOtherBytes";
- this.labelIOOtherBytes.Size = new System.Drawing.Size(34, 13);
+ this.labelIOOtherBytes.Size = new System.Drawing.Size(33, 13);
this.labelIOOtherBytes.TabIndex = 1;
this.labelIOOtherBytes.Text = "value";
//
@@ -643,9 +643,9 @@ private void InitializeComponent()
//
this.label31.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label31.AutoSize = true;
- this.label31.Location = new System.Drawing.Point(3, 111);
+ this.label31.Location = new System.Drawing.Point(3, 112);
this.label31.Name = "label31";
- this.label31.Size = new System.Drawing.Size(62, 13);
+ this.label31.Size = new System.Drawing.Size(57, 13);
this.label31.TabIndex = 5;
this.label31.Text = "I/O Priority";
//
@@ -653,9 +653,9 @@ private void InitializeComponent()
//
this.labelIOPriority.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelIOPriority.AutoSize = true;
- this.labelIOPriority.Location = new System.Drawing.Point(152, 111);
+ this.labelIOPriority.Location = new System.Drawing.Point(153, 112);
this.labelIOPriority.Name = "labelIOPriority";
- this.labelIOPriority.Size = new System.Drawing.Size(34, 13);
+ this.labelIOPriority.Size = new System.Drawing.Size(33, 13);
this.labelIOPriority.TabIndex = 1;
this.labelIOPriority.Text = "value";
//
@@ -682,23 +682,23 @@ private void InitializeComponent()
this.tableLayoutPanel4.Controls.Add(this.labelOtherUSERHandles, 1, 2);
this.tableLayoutPanel4.Controls.Add(this.buttonHandleDetails, 1, 3);
this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill;
- this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 18);
+ this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
this.tableLayoutPanel4.RowCount = 4;
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33334F));
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33334F));
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 27F));
- this.tableLayoutPanel4.Size = new System.Drawing.Size(189, 78);
+ this.tableLayoutPanel4.Size = new System.Drawing.Size(189, 80);
this.tableLayoutPanel4.TabIndex = 1;
//
// label27
//
this.label27.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label27.AutoSize = true;
- this.label27.Location = new System.Drawing.Point(3, 1);
+ this.label27.Location = new System.Drawing.Point(3, 2);
this.label27.Name = "label27";
- this.label27.Size = new System.Drawing.Size(49, 13);
+ this.label27.Size = new System.Drawing.Size(46, 13);
this.label27.TabIndex = 1;
this.label27.Text = "Handles";
//
@@ -706,9 +706,9 @@ private void InitializeComponent()
//
this.labelOtherHandles.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelOtherHandles.AutoSize = true;
- this.labelOtherHandles.Location = new System.Drawing.Point(152, 1);
+ this.labelOtherHandles.Location = new System.Drawing.Point(153, 2);
this.labelOtherHandles.Name = "labelOtherHandles";
- this.labelOtherHandles.Size = new System.Drawing.Size(34, 13);
+ this.labelOtherHandles.Size = new System.Drawing.Size(33, 13);
this.labelOtherHandles.TabIndex = 1;
this.labelOtherHandles.Text = "value";
//
@@ -716,9 +716,9 @@ private void InitializeComponent()
//
this.label28.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label28.AutoSize = true;
- this.label28.Location = new System.Drawing.Point(3, 18);
+ this.label28.Location = new System.Drawing.Point(3, 19);
this.label28.Name = "label28";
- this.label28.Size = new System.Drawing.Size(71, 13);
+ this.label28.Size = new System.Drawing.Size(68, 13);
this.label28.TabIndex = 1;
this.label28.Text = "GDI Handles";
//
@@ -726,7 +726,7 @@ private void InitializeComponent()
//
this.label29.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.label29.AutoSize = true;
- this.label29.Location = new System.Drawing.Point(3, 35);
+ this.label29.Location = new System.Drawing.Point(3, 36);
this.label29.Name = "label29";
this.label29.Size = new System.Drawing.Size(79, 13);
this.label29.TabIndex = 1;
@@ -736,9 +736,9 @@ private void InitializeComponent()
//
this.labelOtherGDIHandles.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelOtherGDIHandles.AutoSize = true;
- this.labelOtherGDIHandles.Location = new System.Drawing.Point(152, 18);
+ this.labelOtherGDIHandles.Location = new System.Drawing.Point(153, 19);
this.labelOtherGDIHandles.Name = "labelOtherGDIHandles";
- this.labelOtherGDIHandles.Size = new System.Drawing.Size(34, 13);
+ this.labelOtherGDIHandles.Size = new System.Drawing.Size(33, 13);
this.labelOtherGDIHandles.TabIndex = 1;
this.labelOtherGDIHandles.Text = "value";
//
@@ -746,9 +746,9 @@ private void InitializeComponent()
//
this.labelOtherUSERHandles.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelOtherUSERHandles.AutoSize = true;
- this.labelOtherUSERHandles.Location = new System.Drawing.Point(152, 35);
+ this.labelOtherUSERHandles.Location = new System.Drawing.Point(153, 36);
this.labelOtherUSERHandles.Name = "labelOtherUSERHandles";
- this.labelOtherUSERHandles.Size = new System.Drawing.Size(34, 13);
+ this.labelOtherUSERHandles.Size = new System.Drawing.Size(33, 13);
this.labelOtherUSERHandles.TabIndex = 1;
this.labelOtherUSERHandles.Text = "value";
//
@@ -756,9 +756,9 @@ private void InitializeComponent()
//
this.buttonHandleDetails.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.buttonHandleDetails.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.buttonHandleDetails.Location = new System.Drawing.Point(112, 53);
+ this.buttonHandleDetails.Location = new System.Drawing.Point(112, 54);
this.buttonHandleDetails.Name = "buttonHandleDetails";
- this.buttonHandleDetails.Size = new System.Drawing.Size(74, 22);
+ this.buttonHandleDetails.Size = new System.Drawing.Size(74, 23);
this.buttonHandleDetails.TabIndex = 2;
this.buttonHandleDetails.Text = "Details...";
this.buttonHandleDetails.UseVisualStyleBackColor = true;
@@ -768,7 +768,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.White;
this.Controls.Add(this.flowStats);
this.Name = "ProcessStatistics";
this.Size = new System.Drawing.Size(433, 374);
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessStatistics.cs b/1.x/trunk/ProcessHacker/Components/ProcessStatistics.cs
index dad9f635c..10632d2d4 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessStatistics.cs
+++ b/1.x/trunk/ProcessHacker/Components/ProcessStatistics.cs
@@ -24,12 +24,13 @@
using System.Windows.Forms;
using ProcessHacker.Common;
using ProcessHacker.Native;
+using ProcessHacker.Native.Objects;
namespace ProcessHacker.Components
{
public partial class ProcessStatistics : UserControl
{
- private readonly int _pid;
+ private int _pid;
public ProcessStatistics(int pid)
{
@@ -45,37 +46,49 @@ public ProcessStatistics(int pid)
{
labelCPUCyclesText.Text = "N/A";
}
+
+ _dontCalculate = false;
+ }
+
+ private bool _dontCalculate = true;
+
+ protected override void OnResize(EventArgs e)
+ {
+ if (_dontCalculate)
+ return;
+
+ base.OnResize(e);
}
public void ClearStatistics()
{
- labelCPUPriority.Text = string.Empty;
- labelCPUCycles.Text = string.Empty;
- labelCPUKernelTime.Text = string.Empty;
- labelCPUUserTime.Text = string.Empty;
- labelCPUTotalTime.Text = string.Empty;
-
- labelMemoryPB.Text = string.Empty;
- labelMemoryWS.Text = string.Empty;
- labelMemoryPWS.Text = string.Empty;
- labelMemoryVS.Text = string.Empty;
- labelMemoryPVS.Text = string.Empty;
- labelMemoryPU.Text = string.Empty;
- labelMemoryPPU.Text = string.Empty;
- labelMemoryPF.Text = string.Empty;
- labelMemoryPP.Text = string.Empty;
-
- labelIOReads.Text = string.Empty;
- labelIOReadBytes.Text = string.Empty;
- labelIOWrites.Text = string.Empty;
- labelIOWriteBytes.Text = string.Empty;
- labelIOOther.Text = string.Empty;
- labelIOOtherBytes.Text = string.Empty;
- labelIOPriority.Text = string.Empty;
-
- labelOtherHandles.Text = string.Empty;
- labelOtherGDIHandles.Text = string.Empty;
- labelOtherUSERHandles.Text = string.Empty;
+ labelCPUPriority.Text = "";
+ labelCPUCycles.Text = "";
+ labelCPUKernelTime.Text = "";
+ labelCPUUserTime.Text = "";
+ labelCPUTotalTime.Text = "";
+
+ labelMemoryPB.Text = "";
+ labelMemoryWS.Text = "";
+ labelMemoryPWS.Text = "";
+ labelMemoryVS.Text = "";
+ labelMemoryPVS.Text = "";
+ labelMemoryPU.Text = "";
+ labelMemoryPPU.Text = "";
+ labelMemoryPF.Text = "";
+ labelMemoryPP.Text = "";
+
+ labelIOReads.Text = "";
+ labelIOReadBytes.Text = "";
+ labelIOWrites.Text = "";
+ labelIOWriteBytes.Text = "";
+ labelIOOther.Text = "";
+ labelIOOtherBytes.Text = "";
+ labelIOPriority.Text = "";
+
+ labelOtherHandles.Text = "";
+ labelOtherGDIHandles.Text = "";
+ labelOtherUSERHandles.Text = "";
}
public void UpdateStatistics()
@@ -99,31 +112,34 @@ public void UpdateStatistics()
labelMemoryPPU.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.PeakPagefileUsage);
labelMemoryPF.Text = ((ulong)item.Process.VirtualMemoryCounters.PageFaultCount).ToString("N0");
- labelIOReads.Text = item.Process.IoCounters.ReadOperationCount.ToString("N0");
+ labelIOReads.Text = ((ulong)item.Process.IoCounters.ReadOperationCount).ToString("N0");
labelIOReadBytes.Text = Utils.FormatSize(item.Process.IoCounters.ReadTransferCount);
- labelIOWrites.Text = item.Process.IoCounters.WriteOperationCount.ToString("N0");
+ labelIOWrites.Text = ((ulong)item.Process.IoCounters.WriteOperationCount).ToString("N0");
labelIOWriteBytes.Text = Utils.FormatSize(item.Process.IoCounters.WriteTransferCount);
- labelIOOther.Text = item.Process.IoCounters.OtherOperationCount.ToString("N0");
+ labelIOOther.Text = ((ulong)item.Process.IoCounters.OtherOperationCount).ToString("N0");
labelIOOtherBytes.Text = Utils.FormatSize(item.Process.IoCounters.OtherTransferCount);
labelOtherHandles.Text = ((ulong)item.Process.HandleCount).ToString("N0");
-
+
if (_pid > 0)
{
try
{
- labelOtherGDIHandles.Text = item.ProcessQueryHandle.GetGuiResources(false).ToString("N0");
- labelOtherUSERHandles.Text = item.ProcessQueryHandle.GetGuiResources(true).ToString("N0");
-
- if (OSVersion.HasCycleTime)
- labelCPUCycles.Text = item.ProcessQueryHandle.GetCycleTime().ToString("N0");
- else
- labelCPUCycles.Text = "N/A";
-
- if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
+ using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
{
- labelMemoryPP.Text = item.ProcessQueryHandle.PagePriority.ToString();
- labelIOPriority.Text = item.ProcessQueryHandle.IoPriority.ToString();
+ labelOtherGDIHandles.Text = phandle.GetGuiResources(false).ToString("N0");
+ labelOtherUSERHandles.Text = phandle.GetGuiResources(true).ToString("N0");
+
+ if (OSVersion.HasCycleTime)
+ labelCPUCycles.Text = phandle.GetCycleTime().ToString("N0");
+ else
+ labelCPUCycles.Text = "N/A";
+
+ if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
+ {
+ labelMemoryPP.Text = phandle.GetPagePriority().ToString();
+ labelIOPriority.Text = phandle.GetIoPriority().ToString();
+ }
}
}
catch
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessStatistics.resx b/1.x/trunk/ProcessHacker/Components/ProcessStatistics.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessStatistics.resx
+++ b/1.x/trunk/ProcessHacker/Components/ProcessStatistics.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessNode.cs b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessNode.cs
index 092c99a3d..3547d33e2 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessNode.cs
+++ b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessNode.cs
@@ -38,16 +38,16 @@ public class ProcessNode : Node, IDisposable
private static ProcessNode[] _processNodeTreePathBuffer;
private const int _processNodeTreePathMaxDepth = 512;
- private ProcessNode _parent;
- private readonly List _children = new List();
- private TreePath _treePath;
+ private ProcessNode _parent = null;
+ private List _children = new List();
+ private TreePath _treePath = null;
private ProcessItem _pitem;
- private bool _wasNoIcon;
+ private bool _wasNoIcon = false;
private Bitmap _icon;
private string _tooltipText;
- private int _lastTooltipTickCount;
+ private int _lastTooltipTickCount = 0;
public ProcessNode(ProcessItem pitem)
{
@@ -57,7 +57,7 @@ public ProcessNode(ProcessItem pitem)
if (_pitem.Icon == null)
{
_wasNoIcon = true;
- _icon = Properties.Resources.Process_small.ToBitmap();
+ _icon = global::ProcessHacker.Properties.Resources.Process_small.ToBitmap();
}
else
{
@@ -68,7 +68,7 @@ public ProcessNode(ProcessItem pitem)
catch
{
_wasNoIcon = true;
- _icon = Properties.Resources.Process_small.ToBitmap();
+ _icon = global::ProcessHacker.Properties.Resources.Process_small.ToBitmap();
}
}
}
@@ -161,7 +161,9 @@ public TreePath RefreshTreePath()
currentNode = currentNode.Parent;
}
- ProcessNode[] path = new ProcessNode[_processNodeTreePathMaxDepth - i];
+ ProcessNode[] path;
+
+ path = new ProcessNode[_processNodeTreePathMaxDepth - i];
Array.Copy(_processNodeTreePathBuffer, i, path, 0, _processNodeTreePathMaxDepth - i);
_treePath = new TreePath(path);
@@ -181,7 +183,7 @@ public ProcessHacker.Components.NodePlotter.PlotterInfo CpuHistory
{
get
{
- return new ProcessHacker.Components.NodePlotter.PlotterInfo
+ return new ProcessHacker.Components.NodePlotter.PlotterInfo()
{
UseSecondLine = true,
OverlaySecondLine = false,
@@ -198,7 +200,7 @@ public ProcessHacker.Components.NodePlotter.PlotterInfo IoHistory
{
get
{
- return new ProcessHacker.Components.NodePlotter.PlotterInfo
+ return new ProcessHacker.Components.NodePlotter.PlotterInfo()
{
UseSecondLine = true,
OverlaySecondLine = true,
@@ -213,7 +215,7 @@ public ProcessHacker.Components.NodePlotter.PlotterInfo IoHistory
public string Name
{
- get { return _pitem.Name ?? string.Empty; }
+ get { return _pitem.Name ?? ""; }
}
public string DisplayPid
@@ -222,8 +224,8 @@ public string DisplayPid
{
if (_pitem.Pid >= 0)
return _pitem.Pid.ToString();
-
- return string.Empty;
+ else
+ return "";
}
}
@@ -234,13 +236,7 @@ public int Pid
public int PPid
{
- get
- {
- if (_pitem.Pid == _pitem.ParentPid)
- return -1;
-
- return this._pitem.ParentPid;
- }
+ get { if (_pitem.Pid == _pitem.ParentPid) return -1; else return _pitem.ParentPid; }
}
public string PvtMemory
@@ -263,16 +259,19 @@ public string PeakWorkingSet
private int GetWorkingSetNumber(NProcessHacker.WsInformationClass WsInformationClass)
{
- if (_pitem.ProcessQueryHandle == null)
- return 0;
-
+ NtStatus status;
int wsInfo;
int retLen;
try
{
- if (NProcessHacker.PhQueryProcessWs(_pitem.ProcessQueryHandle, WsInformationClass, out wsInfo, 4, out retLen) < NtStatus.Error)
- return wsInfo * Program.ProcessProvider.System.PageSize;
+ using (var phandle = new ProcessHandle(_pitem.Pid,
+ ProcessAccess.QueryInformation | ProcessAccess.VmRead))
+ {
+ if ((status = NProcessHacker.PhQueryProcessWs(phandle, WsInformationClass, out wsInfo,
+ 4, out retLen)) < NtStatus.Error)
+ return wsInfo * Program.ProcessProvider.System.PageSize;
+ }
}
catch
{ }
@@ -345,9 +344,9 @@ public string Cpu
get
{
if (_pitem.CpuUsage == 0)
- return string.Empty;
-
- return this._pitem.CpuUsage.ToString("F2");
+ return "";
+ else
+ return _pitem.CpuUsage.ToString("F2");
}
}
@@ -361,9 +360,9 @@ public string SessionId
get
{
if (Pid < 4)
- return string.Empty;
-
- return this._pitem.SessionId.ToString();
+ return "";
+ else
+ return _pitem.SessionId.ToString();
}
}
@@ -371,16 +370,14 @@ public string PriorityClass
{
get
{
- if (_pitem.ProcessQueryHandle == null)
- return string.Empty;
-
try
{
- return PhUtils.FormatPriorityClass(_pitem.ProcessQueryHandle.PriorityClass);
+ using (var phandle = new ProcessHandle(Pid, Program.MinProcessQueryRights))
+ return PhUtils.FormatPriorityClass(phandle.GetPriorityClass());
}
catch
{
- return string.Empty;
+ return "";
}
}
}
@@ -390,9 +387,9 @@ public string BasePriority
get
{
if (Pid < 4)
- return string.Empty;
-
- return this._pitem.Process.BasePriority.ToString();
+ return "";
+ else
+ return _pitem.Process.BasePriority.ToString();
}
}
@@ -400,22 +397,16 @@ public string Description
{
get
{
- switch (this.Pid)
- {
- case 0:
- return "System Idle Process";
- case -2:
- return "Deferred Procedure Calls";
- case -3:
- return "Interrupts";
- default:
- {
- if (this._pitem.VersionInfo != null && !string.IsNullOrEmpty(this._pitem.VersionInfo.FileDescription))
- return this._pitem.VersionInfo.FileDescription;
-
- return string.Empty;
- }
- }
+ if (Pid == 0)
+ return "System Idle Process";
+ else if (Pid == -2)
+ return "Deferred Procedure Calls";
+ else if (Pid == -3)
+ return "Interrupts";
+ else if (_pitem.VersionInfo != null && _pitem.VersionInfo.FileDescription != null)
+ return _pitem.VersionInfo.FileDescription;
+ else
+ return "";
}
}
@@ -423,10 +414,10 @@ public string Company
{
get
{
- if (_pitem.VersionInfo != null && !string.IsNullOrEmpty(_pitem.VersionInfo.CompanyName))
+ if (_pitem.VersionInfo != null && _pitem.VersionInfo.CompanyName != null)
return _pitem.VersionInfo.CompanyName;
-
- return string.Empty;
+ else
+ return "";
}
}
@@ -434,10 +425,10 @@ public string FileName
{
get
{
- if (string.IsNullOrEmpty(_pitem.FileName))
- return string.Empty;
-
- return this._pitem.FileName;
+ if (_pitem.FileName == null)
+ return "";
+ else
+ return _pitem.FileName;
}
}
@@ -445,10 +436,10 @@ public string CommandLine
{
get
{
- if (string.IsNullOrEmpty(_pitem.CmdLine))
- return string.Empty;
-
- return this._pitem.CmdLine;//.Replace("\0", string.Empty);
+ if (_pitem.CmdLine == null)
+ return "";
+ else
+ return _pitem.CmdLine.Replace("\0", "");
}
}
@@ -457,9 +448,9 @@ public string Threads
get
{
if (Pid < 4)
- return string.Empty;
-
- return this._pitem.Process.NumberOfThreads.ToString();
+ return "";
+ else
+ return _pitem.Process.NumberOfThreads.ToString();
}
}
@@ -468,9 +459,9 @@ public string Handles
get
{
if (Pid < 4)
- return string.Empty;
-
- return this._pitem.Process.HandleCount.ToString();
+ return "";
+ else
+ return _pitem.Process.HandleCount.ToString();
}
}
@@ -478,12 +469,10 @@ public int GdiHandlesNumber
{
get
{
- if (_pitem.ProcessQueryHandle == null)
- return 0;
-
try
{
- return _pitem.ProcessQueryHandle.GetGuiResources(false);
+ using (var phandle = new ProcessHandle(Pid, ProcessAccess.QueryInformation))
+ return phandle.GetGuiResources(false);
}
catch
{
@@ -497,14 +486,16 @@ public string GdiHandles
get
{
if (Pid < 4)
- return string.Empty;
-
- int number = this.GdiHandlesNumber;
+ return "";
+ else
+ {
+ int number = this.GdiHandlesNumber;
- if (number == 0)
- return string.Empty;
-
- return number.ToString();
+ if (number == 0)
+ return "";
+ else
+ return number.ToString();
+ }
}
}
@@ -512,12 +503,10 @@ public int UserHandlesNumber
{
get
{
- if (_pitem.ProcessQueryHandle == null)
- return 0;
-
try
{
- return _pitem.ProcessQueryHandle.GetGuiResources(true);
+ using (var phandle = new ProcessHandle(Pid, ProcessAccess.QueryInformation))
+ return phandle.GetGuiResources(true);
}
catch
{
@@ -531,20 +520,26 @@ public string UserHandles
get
{
if (Pid < 4)
- return string.Empty;
-
- int number = this.UserHandlesNumber;
+ return "";
+ else
+ {
+ int number = this.UserHandlesNumber;
- if (number == 0)
- return string.Empty;
-
- return number.ToString();
+ if (number == 0)
+ return "";
+ else
+ return number.ToString();
+ }
}
}
public long IoTotalNumber
{
- get { return (_pitem.IoReadDelta.Delta + _pitem.IoWriteDelta.Delta + _pitem.IoOtherDelta.Delta) * 1000 / Settings.Instance.RefreshInterval; }
+ get
+ {
+ return (_pitem.IoReadDelta.Delta + _pitem.IoWriteDelta.Delta +
+ _pitem.IoOtherDelta.Delta) * 1000 / Settings.Instance.RefreshInterval;
+ }
}
public string IoTotal
@@ -552,9 +547,9 @@ public string IoTotal
get
{
if (this.IoTotalNumber == 0)
- return string.Empty;
-
- return Utils.FormatSize(this.IoTotalNumber) + "/s";
+ return "";
+ else
+ return Utils.FormatSize(this.IoTotalNumber) + "/s";
}
}
@@ -562,7 +557,8 @@ public long IoReadOtherNumber
{
get
{
- return (_pitem.IoReadDelta.Delta + _pitem.IoOtherDelta.Delta) * 1000 / Settings.Instance.RefreshInterval;
+ return (_pitem.IoReadDelta.Delta + _pitem.IoOtherDelta.Delta) * 1000 /
+ Settings.Instance.RefreshInterval;
}
}
@@ -571,15 +567,19 @@ public string IoReadOther
get
{
if (this.IoReadOtherNumber == 0)
- return string.Empty;
-
- return Utils.FormatSize(this.IoReadOtherNumber) + "/s";
+ return "";
+ else
+ return Utils.FormatSize(this.IoReadOtherNumber) + "/s";
}
}
public long IoWriteNumber
{
- get { return _pitem.IoWriteDelta.Delta * 1000 / Settings.Instance.RefreshInterval; }
+ get
+ {
+ return _pitem.IoWriteDelta.Delta * 1000 /
+ Settings.Instance.RefreshInterval;
+ }
}
public string IoWrite
@@ -587,9 +587,9 @@ public string IoWrite
get
{
if (this.IoWriteNumber == 0)
- return string.Empty;
-
- return Utils.FormatSize(this.IoWriteNumber) + "/s";
+ return "";
+ else
+ return Utils.FormatSize(this.IoWriteNumber) + "/s";
}
}
@@ -607,12 +607,9 @@ public int IoPriority
{
get
{
- if (_pitem.ProcessQueryHandle == null)
- return 0;
-
try
{
- return _pitem.ProcessQueryHandle.IoPriority;
+ return _pitem.ProcessQueryHandle.GetIoPriority();
}
catch
{
@@ -625,12 +622,9 @@ public int PagePriority
{
get
{
- if (_pitem.ProcessQueryHandle == null)
- return 0;
-
try
{
- return _pitem.ProcessQueryHandle.PagePriority;
+ return _pitem.ProcessQueryHandle.GetPagePriority();
}
catch
{
@@ -649,9 +643,9 @@ public string StartTime
get
{
if (Pid < 4 || _pitem.CreateTime.Year == 1)
- return string.Empty;
-
- return this._pitem.CreateTime.ToString();
+ return "";
+ else
+ return _pitem.CreateTime.ToString();
}
}
@@ -660,9 +654,9 @@ public string RelativeStartTime
get
{
if (Pid < 4 || _pitem.CreateTime.Year == 1)
- return string.Empty;
-
- return Utils.FormatRelativeDateTime(this._pitem.CreateTime);
+ return "";
+ else
+ return Utils.FormatRelativeDateTime(_pitem.CreateTime);
}
}
@@ -683,12 +677,12 @@ public string UserCpuTime
public string VerificationStatus
{
- get { return _pitem.VerifyResult == VerifyResult.Trusted ? "Verified" : string.Empty; }
+ get { return _pitem.VerifyResult == VerifyResult.Trusted ? "Verified" : ""; }
}
public string VerifiedSigner
{
- get { return _pitem.VerifyResult == VerifyResult.Trusted ? _pitem.VerifySignerName : string.Empty; }
+ get { return _pitem.VerifyResult == VerifyResult.Trusted ? _pitem.VerifySignerName : ""; }
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessToolTipProvider.cs b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessToolTipProvider.cs
index 3cfd34fe2..9046d6086 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessToolTipProvider.cs
+++ b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessToolTipProvider.cs
@@ -24,7 +24,6 @@
using System.Collections.Generic;
using System.Diagnostics;
using Aga.Controls.Tree;
-using Microsoft.Win32;
using ProcessHacker.Common;
using ProcessHacker.Native;
using ProcessHacker.Native.Api;
@@ -33,7 +32,7 @@ namespace ProcessHacker
{
public class ProcessToolTipProvider : IToolTipProvider
{
- private readonly ProcessTree _tree;
+ private ProcessTree _tree;
public ProcessToolTipProvider(ProcessTree owner)
{
@@ -47,18 +46,18 @@ public string GetToolTip(TreeNodeAdv node, Aga.Controls.Tree.NodeControls.NodeCo
// Use the process node's tooltip mechanism to allow caching.
if (pNode != null)
return pNode.GetTooltipText(this);
-
- return string.Empty;
+ else
+ return "";
}
public string GetToolTip(ProcessNode pNode)
{
try
{
- string cmdText = (!string.IsNullOrEmpty(pNode.ProcessItem.CmdLine) ?
- (Utils.CreateEllipsis(pNode.ProcessItem.CmdLine.Replace("\0", string.Empty), 100) + "\n") : string.Empty);
+ string cmdText = (pNode.ProcessItem.CmdLine != null ?
+ (Utils.CreateEllipsis(pNode.ProcessItem.CmdLine.Replace("\0", ""), 100) + "\n") : "");
- string fileText = string.Empty;
+ string fileText = "";
try
{
@@ -66,21 +65,22 @@ public string GetToolTip(ProcessNode pNode)
{
var info = pNode.ProcessItem.VersionInfo;
- fileText = "File:\n" + PhUtils.FormatFileInfo(info.FileName, info.FileDescription, info.CompanyName, info.FileVersion, 4);
+ fileText = "File:\n" + PhUtils.FormatFileInfo(
+ info.FileName, info.FileDescription, info.CompanyName, info.FileVersion, 4);
}
}
catch
{
- if (!string.IsNullOrEmpty(pNode.ProcessItem.FileName))
+ if (pNode.ProcessItem.FileName != null)
fileText = "File:\n " + pNode.ProcessItem.FileName;
}
- string runDllText = string.Empty;
+ string runDllText = "";
- if (!string.IsNullOrEmpty(pNode.ProcessItem.FileName) &&
+ if (pNode.ProcessItem.FileName != null &&
pNode.ProcessItem.FileName.EndsWith("\\rundll32.exe",
StringComparison.InvariantCultureIgnoreCase) &&
- !string.IsNullOrEmpty(pNode.ProcessItem.CmdLine))
+ pNode.ProcessItem.CmdLine != null)
{
try
{
@@ -88,7 +88,7 @@ public string GetToolTip(ProcessNode pNode)
string targetFile = pNode.ProcessItem.CmdLine.Split(new char[] { ' ' }, 2)[1].Split(',')[0];
// if it doesn't specify an absolute path, assume it's in system32.
- if (!targetFile.Contains(":", StringComparison.OrdinalIgnoreCase))
+ if (!targetFile.Contains(":"))
targetFile = Environment.SystemDirectory + "\\" + targetFile;
FileVersionInfo info = FileVersionInfo.GetVersionInfo(targetFile);
@@ -103,32 +103,31 @@ public string GetToolTip(ProcessNode pNode)
}
}
- string dllhostText = string.Empty;
+ string dllhostText = "";
- if (!string.IsNullOrEmpty(pNode.ProcessItem.FileName) &&
- pNode.ProcessItem.FileName.EndsWith("\\dllhost.exe", StringComparison.InvariantCultureIgnoreCase) &&
- !string.IsNullOrEmpty(pNode.ProcessItem.CmdLine))
+ if (pNode.ProcessItem.FileName != null &&
+ pNode.ProcessItem.FileName.EndsWith("\\dllhost.exe",
+ StringComparison.InvariantCultureIgnoreCase) &&
+ pNode.ProcessItem.CmdLine != null)
{
try
{
- string clsid = pNode.ProcessItem.CmdLine.ToLowerInvariant().Split(new[]
- {
- "/processid:"
- }, StringSplitOptions.None)[1].Split(' ')[0];
-
- using (RegistryKey key = Registry.ClassesRoot.OpenSubKey("CLSID\\" + clsid))
- using (RegistryKey inprocServer32 = key.OpenSubKey("InprocServer32"))
+ string clsid = pNode.ProcessItem.CmdLine.ToLowerInvariant().Split(
+ new string[] { "/processid:" }, StringSplitOptions.None)[1].Split(' ')[0];
+ using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\" + clsid))
{
- string name = key.GetValue(string.Empty) as string;
- string fileName = inprocServer32.GetValue(string.Empty) as string;
+ using (var inprocServer32 = key.OpenSubKey("InprocServer32"))
+ {
+ string name = key.GetValue("") as string;
+ string fileName = inprocServer32.GetValue("") as string;
- FileVersionInfo info = FileVersionInfo.GetVersionInfo(Environment.ExpandEnvironmentVariables(fileName));
+ FileVersionInfo info = FileVersionInfo.GetVersionInfo(Environment.ExpandEnvironmentVariables(fileName));
- dllhostText = "\nCOM Target:\n " + name + " (" + clsid.ToUpper() + ")\n " +
- info.FileName + "\n " +
- info.FileDescription + " " + info.FileVersion + "\n " + info.CompanyName;
+ dllhostText = "\nCOM Target:\n " + name + " (" + clsid.ToUpper() + ")\n " +
+ info.FileName + "\n " +
+ info.FileDescription + " " + info.FileVersion + "\n " + info.CompanyName;
+ }
}
-
}
catch (Exception ex)
{
@@ -136,7 +135,7 @@ public string GetToolTip(ProcessNode pNode)
}
}
- string servicesText = string.Empty;
+ string servicesText = "";
try
{
@@ -160,8 +159,9 @@ public string GetToolTip(ProcessNode pNode)
{
if (services.ContainsKey(service))
{
- if (string.IsNullOrEmpty(services[service].Status.DisplayName))
- servicesText += " " + service + " (" + services[service].Status.DisplayName + ")\n";
+ if (services[service].Status.DisplayName != "")
+ servicesText += " " + service + " (" +
+ services[service].Status.DisplayName + ")\n";
else
servicesText += " " + service + "\n";
}
@@ -179,7 +179,7 @@ public string GetToolTip(ProcessNode pNode)
Logging.Log(ex);
}
- string otherNotes = string.Empty;
+ string otherNotes = "";
try
{
@@ -202,7 +202,7 @@ public string GetToolTip(ProcessNode pNode)
else if (pNode.ProcessItem.VerifyResult == VerifyResult.Unknown &&
!Settings.Instance.VerifySignatures)
{
- otherNotes += string.Empty;
+ otherNotes += "";
}
else if (pNode.ProcessItem.VerifyResult == VerifyResult.Unknown &&
Settings.Instance.VerifySignatures && !_tree.DumpMode)
@@ -231,7 +231,7 @@ public string GetToolTip(ProcessNode pNode)
if (pNode.ProcessItem.IsWow64)
otherNotes += "\n Process is 32-bit (running under WOW64).";
- if (otherNotes != string.Empty)
+ if (otherNotes != "")
otherNotes = "\nNotes:" + otherNotes;
}
catch (Exception ex)
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.Designer.cs b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.Designer.cs
index c7108c9c5..4726cdc9a 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.Designer.cs
@@ -112,6 +112,7 @@ private void InitializeComponent()
//
// treeProcesses
//
+ this.treeProcesses.AllowColumnReorder = true;
this.treeProcesses.BackColor = System.Drawing.SystemColors.Window;
this.treeProcesses.Columns.Add(this.columnName);
this.treeProcesses.Columns.Add(this.columnPID);
@@ -153,7 +154,10 @@ private void InitializeComponent()
this.treeProcesses.Columns.Add(this.columnVerificationStatus);
this.treeProcesses.Columns.Add(this.columnVerifiedSigner);
this.treeProcesses.DefaultToolTipProvider = null;
+ this.treeProcesses.DisplayDraggingNodes = true;
this.treeProcesses.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.treeProcesses.DragDropMarkColor = System.Drawing.Color.Black;
+ this.treeProcesses.FullRowSelect = true;
this.treeProcesses.LineColor = System.Drawing.SystemColors.ControlDark;
this.treeProcesses.Location = new System.Drawing.Point(0, 0);
this.treeProcesses.Model = null;
@@ -203,6 +207,7 @@ private void InitializeComponent()
this.treeProcesses.ShowNodeToolTips = true;
this.treeProcesses.Size = new System.Drawing.Size(808, 472);
this.treeProcesses.TabIndex = 2;
+ this.treeProcesses.UseColumns = true;
this.treeProcesses.NodeMouseDoubleClick += new System.EventHandler(this.treeProcesses_NodeMouseDoubleClick);
this.treeProcesses.SelectionChanged += new System.EventHandler(this.treeProcesses_SelectionChanged);
this.treeProcesses.ColumnClicked += new System.EventHandler(this.treeProcesses_ColumnClicked);
@@ -961,6 +966,7 @@ private void InitializeComponent()
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.treeProcesses);
+ this.DoubleBuffered = true;
this.Name = "ProcessTree";
this.Size = new System.Drawing.Size(808, 472);
this.ResumeLayout(false);
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.cs b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.cs
index 414f3cd81..21783eca3 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.cs
+++ b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTree.cs
@@ -35,51 +35,47 @@ public partial class ProcessTree : UserControl
{
private ProcessSystemProvider _provider;
private ProcessTreeModel _treeModel;
- private readonly ProcessToolTipProvider _tooltipProvider;
- private int _runCount;
+ private ProcessToolTipProvider _tooltipProvider;
+ private int _runCount = 0;
public new event KeyEventHandler KeyDown;
public new event MouseEventHandler MouseDown;
public new event MouseEventHandler MouseUp;
public new event EventHandler DoubleClick;
public event EventHandler SelectionChanged;
public event EventHandler NodeMouseDoubleClick;
- private readonly object _listLock = new object();
+ private object _listLock = new object();
private bool _draw = true;
- private bool _dumpMode;
+ private bool _dumpMode = false;
public ProcessTree()
{
InitializeComponent();
- TreeColumn column = new TreeColumn("CPU History", 60)
- {
- IsVisible = false,
- MinColumnWidth = 10
- };
+ var column = new TreeColumn("CPU History", 60);
+ column.IsVisible = false;
+ column.MinColumnWidth = 10;
treeProcesses.Columns.Add(column);
- treeProcesses.NodeControls.Add(new Components.NodePlotter
+ treeProcesses.NodeControls.Add(new ProcessHacker.Components.NodePlotter()
{
DataPropertyName = "CpuHistory",
ParentColumn = column
});
- column = new TreeColumn("I/O History", 60)
- {
- IsVisible = false,
- MinColumnWidth = 10
- };
+ column = new TreeColumn("I/O History", 60);
+ column.IsVisible = false;
+ column.MinColumnWidth = 10;
treeProcesses.Columns.Add(column);
- treeProcesses.NodeControls.Add(new Components.NodePlotter
+ treeProcesses.NodeControls.Add(new ProcessHacker.Components.NodePlotter()
{
DataPropertyName = "IoHistory",
ParentColumn = column
});
- treeProcesses.KeyDown += this.ProcessTree_KeyDown;
- treeProcesses.MouseDown += this.treeProcesses_MouseDown;
- treeProcesses.MouseUp += this.treeProcesses_MouseUp;
- treeProcesses.DoubleClick += this.treeProcesses_DoubleClick;
+ treeProcesses.KeyDown += new KeyEventHandler(ProcessTree_KeyDown);
+ treeProcesses.MouseDown += new MouseEventHandler(treeProcesses_MouseDown);
+ treeProcesses.MouseUp += new MouseEventHandler(treeProcesses_MouseUp);
+ treeProcesses.DoubleClick += new EventHandler(treeProcesses_DoubleClick);
nodeName.ToolTipProvider = _tooltipProvider = new ProcessToolTipProvider(this);
@@ -264,15 +260,15 @@ private void provider_Updated()
{
if (_draw)
{
- this.BeginInvoke(new MethodInvoker(() =>
+ this.BeginInvoke(new MethodInvoker(delegate
{
- if (this._treeModel.GetSortColumn() != string.Empty)
+ if (_treeModel.GetSortColumn() != "")
{
- this._treeModel.CallStructureChanged(new TreePathEventArgs(new TreePath()));
+ _treeModel.CallStructureChanged(new TreePathEventArgs(new TreePath()));
}
//treeProcesses.InvalidateNodeControlCache();
- this.treeProcesses.Invalidate();
+ treeProcesses.Invalidate();
}));
}
@@ -283,12 +279,12 @@ private void PerformDelayed(int delay, MethodInvoker action)
{
Timer t = new Timer();
- t.Tick += (sender, args) =>
+ t.Tick += new EventHandler(delegate(object o, EventArgs args)
{
t.Enabled = false;
action();
t.Dispose();
- };
+ });
t.Interval = delay;
t.Enabled = true;
@@ -298,66 +294,50 @@ private Color GetProcessColor(ProcessItem p)
{
if (Settings.Instance.UseColorDebuggedProcesses && p.IsBeingDebugged)
return Settings.Instance.ColorDebuggedProcesses;
-
- if (Settings.Instance.UseColorElevatedProcesses && p.ElevationType == TokenElevationType.Full)
+ else if (Settings.Instance.UseColorElevatedProcesses &&
+ p.ElevationType == TokenElevationType.Full)
return Settings.Instance.ColorElevatedProcesses;
-
- if (Settings.Instance.UseColorPosixProcesses && p.IsPosix)
+ else if (Settings.Instance.UseColorPosixProcesses &&
+ p.IsPosix)
return Settings.Instance.ColorPosixProcesses;
-
- if (Settings.Instance.UseColorWow64Processes && p.IsWow64)
+ else if (Settings.Instance.UseColorWow64Processes &&
+ p.IsWow64)
return Settings.Instance.ColorWow64Processes;
-
- if (Settings.Instance.UseColorJobProcesses && p.IsInSignificantJob)
+ else if (Settings.Instance.UseColorJobProcesses && p.IsInSignificantJob)
return Settings.Instance.ColorJobProcesses;
-
- if (
- Settings.Instance.UseColorPackedProcesses &&
- Settings.Instance.VerifySignatures &&
- !string.IsNullOrEmpty(p.Name) &&
+ else if (Settings.Instance.UseColorPackedProcesses &&
+ Settings.Instance.VerifySignatures &&
+ p.Name != null &&
Program.ImposterNames.Contains(p.Name.ToLowerInvariant()) &&
- p.VerifyResult != VerifyResult.Trusted &&
- p.VerifyResult != VerifyResult.Unknown &&
- !string.IsNullOrEmpty(p.FileName)
- )
+ p.VerifyResult != VerifyResult.Trusted &&
+ p.VerifyResult != VerifyResult.Unknown &&
+ p.FileName != null)
return Settings.Instance.ColorPackedProcesses;
-
- if (Settings.Instance.UseColorPackedProcesses &&
+ else if (Settings.Instance.UseColorPackedProcesses &&
Settings.Instance.VerifySignatures &&
p.VerifyResult != VerifyResult.Trusted &&
p.VerifyResult != VerifyResult.NoSignature &&
p.VerifyResult != VerifyResult.Unknown)
return Settings.Instance.ColorPackedProcesses;
-
- if (Settings.Instance.UseColorDotNetProcesses && p.IsDotNet)
+ else if (Settings.Instance.UseColorDotNetProcesses && p.IsDotNet)
return Settings.Instance.ColorDotNetProcesses;
-
- if (Settings.Instance.UseColorPackedProcesses && p.IsPacked)
+ else if (Settings.Instance.UseColorPackedProcesses && p.IsPacked)
return Settings.Instance.ColorPackedProcesses;
-
- if (this._dumpMode && Settings.Instance.UseColorServiceProcesses &&
- this.DumpProcessServices.ContainsKey(p.Pid) && this.DumpProcessServices[p.Pid].Count > 0)
+ else if (_dumpMode && Settings.Instance.UseColorServiceProcesses &&
+ DumpProcessServices.ContainsKey(p.Pid) && DumpProcessServices[p.Pid].Count > 0)
return Settings.Instance.ColorServiceProcesses;
-
- if (!this._dumpMode && Settings.Instance.UseColorServiceProcesses &&
+ else if (!_dumpMode && Settings.Instance.UseColorServiceProcesses &&
Program.HackerWindow.ProcessServices.ContainsKey(p.Pid) &&
Program.HackerWindow.ProcessServices[p.Pid].Count > 0)
return Settings.Instance.ColorServiceProcesses;
-
- if (Settings.Instance.UseColorSystemProcesses && string.Equals(p.Username, "NT AUTHORITY\\SYSTEM", StringComparison.OrdinalIgnoreCase))
+ else if (Settings.Instance.UseColorSystemProcesses && p.Username == "NT AUTHORITY\\SYSTEM")
return Settings.Instance.ColorSystemProcesses;
-
- if (this._dumpMode &&
- Settings.Instance.UseColorOwnProcesses &&
- string.Equals(p.Username, this.DumpUserName, StringComparison.OrdinalIgnoreCase))
+ else if (_dumpMode && Settings.Instance.UseColorOwnProcesses && p.Username == DumpUserName)
return Settings.Instance.ColorOwnProcesses;
-
- if (!this._dumpMode &&
- Settings.Instance.UseColorOwnProcesses &&
- string.Equals(p.Username, Program.CurrentUsername, StringComparison.OrdinalIgnoreCase))
+ else if (!_dumpMode && Settings.Instance.UseColorOwnProcesses && p.Username == Program.CurrentUsername)
return Settings.Instance.ColorOwnProcesses;
-
- return SystemColors.Window;
+ else
+ return SystemColors.Window;
}
public void AddItem(ProcessItem item)
@@ -372,25 +352,25 @@ public void UpdateItems()
private void provider_DictionaryAdded(ProcessItem item)
{
- this.BeginInvoke(new MethodInvoker(() =>
+ this.BeginInvoke(new MethodInvoker(delegate
{
- lock (this._listLock)
+ lock (_listLock)
{
- this._treeModel.Add(item);
+ _treeModel.Add(item);
TreeNodeAdv node = this.FindTreeNode(item.Pid);
if (node != null)
{
- if (item.RunId > 0 && this._runCount > 0)
+ if (item.RunId > 0 && _runCount > 0)
{
node.State = TreeNodeAdv.NodeState.New;
-
- this.PerformDelayed(Settings.Instance.HighlightingDuration, () =>
+ this.PerformDelayed(Settings.Instance.HighlightingDuration,
+ new MethodInvoker(delegate
{
node.State = TreeNodeAdv.NodeState.Normal;
- this.treeProcesses.Invalidate();
- });
+ treeProcesses.Invalidate();
+ }));
}
node.BackColor = this.GetProcessColor(item);
@@ -402,9 +382,9 @@ private void provider_DictionaryAdded(ProcessItem item)
private void provider_DictionaryModified(ProcessItem oldItem, ProcessItem newItem)
{
- this.BeginInvoke(new MethodInvoker(() =>
+ this.BeginInvoke(new MethodInvoker(delegate
{
- lock (this._listLock)
+ lock (_listLock)
{
TreeNodeAdv node = this.FindTreeNode(newItem.Pid);
@@ -413,16 +393,16 @@ private void provider_DictionaryModified(ProcessItem oldItem, ProcessItem newIte
node.BackColor = this.GetProcessColor(newItem);
}
- this._treeModel.Nodes[newItem.Pid].ProcessItem = newItem;
+ _treeModel.Nodes[newItem.Pid].ProcessItem = newItem;
}
}));
}
private void provider_DictionaryRemoved(ProcessItem item)
{
- this.BeginInvoke(new MethodInvoker(() =>
+ this.BeginInvoke(new MethodInvoker(delegate
{
- lock (this._listLock)
+ lock (_listLock)
{
TreeNodeAdv node = this.FindTreeNode(item.Pid);
@@ -430,27 +410,27 @@ private void provider_DictionaryRemoved(ProcessItem item)
{
//if (this.StateHighlighting)
//{
- node.State = TreeNodeAdv.NodeState.Removed;
-
- this.PerformDelayed(Settings.Instance.HighlightingDuration, () =>
- {
- try
- {
- this._treeModel.Remove(item);
- this.RefreshItems();
- }
- catch (Exception ex)
+ node.State = TreeNodeAdv.NodeState.Removed;
+ this.PerformDelayed(Settings.Instance.HighlightingDuration,
+ new MethodInvoker(delegate
{
- Logging.Log(ex);
- }
- });
+ try
+ {
+ _treeModel.Remove(item);
+ this.RefreshItems();
+ }
+ catch (Exception ex)
+ {
+ Logging.Log(ex);
+ }
+ }));
//}
//else
//{
// _treeModel.Remove(item);
//}
- this.treeProcesses.Invalidate();
+ treeProcesses.Invalidate();
}
}
}));
@@ -498,8 +478,8 @@ public TreeNodeAdv FindTreeNode(int pid)
{
if (_treeModel.Nodes.ContainsKey(pid))
return treeProcesses.FindNode(_treeModel.GetPath(_treeModel.Nodes[pid]));
-
- return null;
+ else
+ return null;
}
public TreeNodeAdv FindTreeNode(ProcessNode node)
diff --git a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTreeModel.cs b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTreeModel.cs
index be57269b4..d3583a538 100644
--- a/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTreeModel.cs
+++ b/1.x/trunk/ProcessHacker/Components/ProcessTree/ProcessTreeModel.cs
@@ -37,9 +37,9 @@ namespace ProcessHacker
///
public class ProcessTreeModel : ITreeModel
{
- private readonly ProcessTree _tree;
- private readonly Dictionary _processes = new Dictionary();
- private readonly List _roots = new List();
+ private ProcessTree _tree;
+ private Dictionary _processes = new Dictionary();
+ private List _roots = new List();
public ProcessTreeModel(ProcessTree tree)
{
@@ -109,7 +109,7 @@ public void Modify(ProcessItem oldItem, ProcessItem newItem)
public void Remove(ProcessItem item)
{
ProcessNode itemNode = _processes[item.Pid];
- ProcessNode[] itemChildren;
+ ProcessNode[] itemChildren = null;
// Dispose of the process node we're removing.
itemNode.Dispose();
@@ -141,19 +141,21 @@ public void Remove(ProcessItem item)
this.StructureChanged(this, new TreePathEventArgs(new TreePath()));
// Expand the children because TreeViewAdv collapses them by default.
- foreach (ProcessNode n in itemChildren)
+ if (itemChildren != null)
{
- try
+ foreach (ProcessNode n in itemChildren)
{
- _tree.FindTreeNode(n).ExpandAll();
- }
- catch (Exception ex)
- {
- Logging.Log(ex);
+ try
+ {
+ _tree.FindTreeNode(n).ExpandAll();
+ }
+ catch (Exception ex)
+ {
+ Logging.Log(ex);
+ }
}
}
-
_tree.Invalidate();
}
@@ -162,12 +164,14 @@ public TreePath GetPath(ProcessNode node)
if (node == null)
return TreePath.Empty;
- if (this.GetSortColumn() != string.Empty)
+ if (this.GetSortColumn() != "")
{
return new TreePath(node);
}
-
- return node.TreePath;
+ else
+ {
+ return node.TreePath;
+ }
}
public void MoveChildrenToRoot(ProcessNode node)
@@ -199,7 +203,7 @@ public string GetSortColumn()
if (column.SortOrder != SortOrder.None)
return column.Header.ToLowerInvariant();
- return string.Empty;
+ return "";
}
public SortOrder GetSortOrder()
@@ -213,20 +217,17 @@ public SortOrder GetSortOrder()
public int ModifySort(int sortResult, SortOrder order)
{
- switch (order)
- {
- case SortOrder.Ascending:
- return -sortResult;
- case SortOrder.Descending:
- return sortResult;
- }
-
- return 0;
+ if (order == SortOrder.Ascending)
+ return -sortResult;
+ else if (order == SortOrder.Descending)
+ return sortResult;
+ else
+ return 0;
}
public System.Collections.IEnumerable GetChildren(TreePath treePath)
{
- if (this.GetSortColumn() != string.Empty)
+ if (this.GetSortColumn() != "")
{
List nodes = new List();
string sortC = this.GetSortColumn();
@@ -234,140 +235,143 @@ public System.Collections.IEnumerable GetChildren(TreePath treePath)
nodes.AddRange(_processes.Values);
- nodes.Sort((n1, n2) =>
- {
- // We have a problem here - the GdiHandlesNumber and UserHandlesNumber
- // properties are dynamically retrieved, so if n1 == n2 we may end up
- // getting different values for the same process due to the timing.
- // If we do, then Array.Sort will throw an exception.
- //
- // The temporary HACK used here is to return 0 whenever n1 == n2.
- if (n1 == n2)
- return 0;
-
- switch (sortC)
+ nodes.Sort(new Comparison(delegate(ProcessNode n1, ProcessNode n2)
{
- case "name":
- return this.ModifySort(string.Compare(n1.Name, n2.Name), sortO);
- case "pid":
- return this.ModifySort(n1.Pid.CompareTo(n2.Pid), sortO);
- case "pvt. memory":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PrivatePageCount.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.PrivatePageCount), sortO);
- case "working set":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.WorkingSetSize.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.WorkingSetSize), sortO);
- case "peak working set":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PeakWorkingSetSize.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.PeakWorkingSetSize), sortO);
- case "private ws":
- return this.ModifySort(n1.PrivateWorkingSetNumber.CompareTo(n2.PrivateWorkingSetNumber), sortO);
- case "shared ws":
- return this.ModifySort(n1.SharedWorkingSetNumber.CompareTo(n2.SharedWorkingSetNumber), sortO);
- case "shareable ws":
- return this.ModifySort(n1.ShareableWorkingSetNumber.CompareTo(n2.ShareableWorkingSetNumber), sortO);
- case "virtual size":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.VirtualSize.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.VirtualSize), sortO);
- case "peak virtual size":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PeakVirtualSize.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.PeakVirtualSize), sortO);
- case "pagefile usage":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PagefileUsage.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.PagefileUsage), sortO);
- case "peak pagefile usage":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PeakPagefileUsage.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.PeakPagefileUsage), sortO);
- case "page faults":
- return this.ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PageFaultCount.CompareTo(
- n2.ProcessItem.Process.VirtualMemoryCounters.PageFaultCount), sortO);
- case "cpu":
- return this.ModifySort(n1.ProcessItem.CpuUsage.CompareTo(n2.ProcessItem.CpuUsage), sortO);
- case "username":
- return this.ModifySort(string.Compare(n1.Username, n2.Username), sortO);
- case "session id":
- return this.ModifySort(n1.ProcessItem.SessionId.CompareTo(n2.ProcessItem.SessionId), sortO);
- case "priority class":
- case "base priority":
- return this.ModifySort(n1.ProcessItem.Process.BasePriority.CompareTo(
- n2.ProcessItem.Process.BasePriority), sortO);
- case "description":
- return this.ModifySort(string.Compare(n1.Description, n2.Description), sortO);
- case "company":
- return this.ModifySort(string.Compare(n1.Company, n2.Company), sortO);
- case "file name":
- return this.ModifySort(string.Compare(n1.FileName, n2.FileName), sortO);
- case "command line":
- return this.ModifySort(string.Compare(n1.CommandLine, n2.CommandLine), sortO);
- case "threads":
- return this.ModifySort(n1.ProcessItem.Process.NumberOfThreads.CompareTo(
- n2.ProcessItem.Process.NumberOfThreads), sortO);
- case "handles":
- return this.ModifySort(n1.ProcessItem.Process.HandleCount.CompareTo(
- n2.ProcessItem.Process.HandleCount), sortO);
- case "gdi handles":
- return this.ModifySort(n1.GdiHandlesNumber.CompareTo(n2.GdiHandlesNumber), sortO);
- case "user handles":
- return this.ModifySort(n1.UserHandlesNumber.CompareTo(n2.UserHandlesNumber), sortO);
- case "i/o total":
- return this.ModifySort(n1.IoTotalNumber.CompareTo(n2.IoTotalNumber), sortO);
- case "i/o ro":
- return this.ModifySort(n1.IoReadOtherNumber.CompareTo(n2.IoReadOtherNumber), sortO);
- case "i/o w":
- return this.ModifySort(n1.IoWriteNumber.CompareTo(n2.IoWriteNumber), sortO);
- case "integrity":
- return this.ModifySort(n1.IntegrityLevel.CompareTo(n2.IntegrityLevel), sortO);
- case "i/o priority":
- return this.ModifySort(n1.IoPriority.CompareTo(n2.IoPriority), sortO);
- case "page priority":
- return this.ModifySort(n1.PagePriority.CompareTo(n2.PagePriority), sortO);
- case "start time":
- return this.ModifySort(n1.ProcessItem.CreateTime.CompareTo(n2.ProcessItem.CreateTime), sortO);
- case "start time (relative)":
- // Invert the order - bigger dates are actually smaller if we use the relative time span.
- return -this.ModifySort(n1.ProcessItem.CreateTime.CompareTo(n2.ProcessItem.CreateTime), sortO);
- case "total cpu time":
- return this.ModifySort((n1.ProcessItem.Process.KernelTime + n1.ProcessItem.Process.UserTime).
- CompareTo(n2.ProcessItem.Process.KernelTime + n2.ProcessItem.Process.UserTime), sortO);
- case "kernel cpu time":
- return this.ModifySort(n1.ProcessItem.Process.KernelTime.CompareTo(
- n2.ProcessItem.Process.KernelTime), sortO);
- case "user cpu time":
- return this.ModifySort(n1.ProcessItem.Process.UserTime.CompareTo(
- n2.ProcessItem.Process.UserTime), sortO);
- case "verification status":
- return this.ModifySort(string.Compare(n1.VerificationStatus, n2.VerificationStatus), sortO);
- case "verified signer":
- return this.ModifySort(string.Compare(n1.VerifiedSigner, n2.VerifiedSigner), sortO);
- default:
+ // We have a problem here - the GdiHandlesNumber and UserHandlesNumber
+ // properties are dynamically retrieved, so if n1 == n2 we may end up
+ // getting different values for the same process due to the timing.
+ // If we do, then Array.Sort will throw an exception.
+ //
+ // The temporary HACK used here is to return 0 whenever n1 == n2.
+ if (n1 == n2)
return 0;
- }
- });
+
+ switch (sortC)
+ {
+ case "name":
+ return ModifySort(string.Compare(n1.Name, n2.Name), sortO);
+ case "pid":
+ return ModifySort(n1.Pid.CompareTo(n2.Pid), sortO);
+ case "pvt. memory":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PrivatePageCount.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.PrivatePageCount), sortO);
+ case "working set":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.WorkingSetSize.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.WorkingSetSize), sortO);
+ case "peak working set":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PeakWorkingSetSize.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.PeakWorkingSetSize), sortO);
+ case "private ws":
+ return ModifySort(n1.PrivateWorkingSetNumber.CompareTo(n2.PrivateWorkingSetNumber), sortO);
+ case "shared ws":
+ return ModifySort(n1.SharedWorkingSetNumber.CompareTo(n2.SharedWorkingSetNumber), sortO);
+ case "shareable ws":
+ return ModifySort(n1.ShareableWorkingSetNumber.CompareTo(n2.ShareableWorkingSetNumber), sortO);
+ case "virtual size":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.VirtualSize.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.VirtualSize), sortO);
+ case "peak virtual size":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PeakVirtualSize.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.PeakVirtualSize), sortO);
+ case "pagefile usage":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PagefileUsage.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.PagefileUsage), sortO);
+ case "peak pagefile usage":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PeakPagefileUsage.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.PeakPagefileUsage), sortO);
+ case "page faults":
+ return ModifySort(n1.ProcessItem.Process.VirtualMemoryCounters.PageFaultCount.CompareTo(
+ n2.ProcessItem.Process.VirtualMemoryCounters.PageFaultCount), sortO);
+ case "cpu":
+ return ModifySort(n1.ProcessItem.CpuUsage.CompareTo(n2.ProcessItem.CpuUsage), sortO);
+ case "username":
+ return ModifySort(string.Compare(n1.Username, n2.Username), sortO);
+ case "session id":
+ return ModifySort(n1.ProcessItem.SessionId.CompareTo(n2.ProcessItem.SessionId), sortO);
+ case "priority class":
+ case "base priority":
+ return ModifySort(n1.ProcessItem.Process.BasePriority.CompareTo(
+ n2.ProcessItem.Process.BasePriority), sortO);
+ case "description":
+ return ModifySort(string.Compare(n1.Description, n2.Description), sortO);
+ case "company":
+ return ModifySort(string.Compare(n1.Company, n2.Company), sortO);
+ case "file name":
+ return ModifySort(string.Compare(n1.FileName, n2.FileName), sortO);
+ case "command line":
+ return ModifySort(string.Compare(n1.CommandLine, n2.CommandLine), sortO);
+ case "threads":
+ return ModifySort(n1.ProcessItem.Process.NumberOfThreads.CompareTo(
+ n2.ProcessItem.Process.NumberOfThreads), sortO);
+ case "handles":
+ return ModifySort(n1.ProcessItem.Process.HandleCount.CompareTo(
+ n2.ProcessItem.Process.HandleCount), sortO);
+ case "gdi handles":
+ return ModifySort(n1.GdiHandlesNumber.CompareTo(n2.GdiHandlesNumber), sortO);
+ case "user handles":
+ return ModifySort(n1.UserHandlesNumber.CompareTo(n2.UserHandlesNumber), sortO);
+ case "i/o total":
+ return ModifySort(n1.IoTotalNumber.CompareTo(n2.IoTotalNumber), sortO);
+ case "i/o ro":
+ return ModifySort(n1.IoReadOtherNumber.CompareTo(n2.IoReadOtherNumber), sortO);
+ case "i/o w":
+ return ModifySort(n1.IoWriteNumber.CompareTo(n2.IoWriteNumber), sortO);
+ case "integrity":
+ return ModifySort(n1.IntegrityLevel.CompareTo(n2.IntegrityLevel), sortO);
+ case "i/o priority":
+ return ModifySort(n1.IoPriority.CompareTo(n2.IoPriority), sortO);
+ case "page priority":
+ return ModifySort(n1.PagePriority.CompareTo(n2.PagePriority), sortO);
+ case "start time":
+ return ModifySort(n1.ProcessItem.CreateTime.CompareTo(n2.ProcessItem.CreateTime), sortO);
+ case "start time (relative)":
+ // Invert the order - bigger dates are actually smaller if we use the relative time span.
+ return -ModifySort(n1.ProcessItem.CreateTime.CompareTo(n2.ProcessItem.CreateTime), sortO);
+ case "total cpu time":
+ return ModifySort((n1.ProcessItem.Process.KernelTime + n1.ProcessItem.Process.UserTime).
+ CompareTo(n2.ProcessItem.Process.KernelTime + n2.ProcessItem.Process.UserTime), sortO);
+ case "kernel cpu time":
+ return ModifySort(n1.ProcessItem.Process.KernelTime.CompareTo(
+ n2.ProcessItem.Process.KernelTime), sortO);
+ case "user cpu time":
+ return ModifySort(n1.ProcessItem.Process.UserTime.CompareTo(
+ n2.ProcessItem.Process.UserTime), sortO);
+ case "verification status":
+ return ModifySort(string.Compare(n1.VerificationStatus, n2.VerificationStatus), sortO);
+ case "verified signer":
+ return ModifySort(string.Compare(n1.VerifiedSigner, n2.VerifiedSigner), sortO);
+ default:
+ return 0;
+ }
+ }));
return nodes;
}
if (treePath.IsEmpty())
return _roots;
-
- return (treePath.LastNode as ProcessNode).Children;
+ else
+ return (treePath.LastNode as ProcessNode).Children;
}
public bool IsLeaf(TreePath treePath)
{
// When we're sorting the whole tree is a flat list, so there are no children.
- if (this.GetSortColumn() != string.Empty)
+ if (this.GetSortColumn() != "")
return true;
if (treePath.IsEmpty())
return false;
-
- return (treePath.LastNode as ProcessNode).Children.Count == 0;
+ else
+ return (treePath.LastNode as ProcessNode).Children.Count == 0;
}
public event EventHandler NodesChanged;
+
public event EventHandler NodesInserted;
+
public event EventHandler NodesRemoved;
+
public event EventHandler StructureChanged;
public void CallStructureChanged(TreePathEventArgs args)
diff --git a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoveryData.cs b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoveryData.cs
index 5b79f4785..d3e500410 100644
--- a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoveryData.cs
+++ b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoveryData.cs
@@ -67,7 +67,7 @@ public RecoveryData(RecoveryCallback callback, object state)
public void Invoke()
{
if(Callback != null)
- Callback(State);
+ Callback(State);
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoverySettings.cs b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoverySettings.cs
index f8679aadf..0b7d57446 100644
--- a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoverySettings.cs
+++ b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RecoverySettings.cs
@@ -34,8 +34,8 @@ namespace ProcessHackerRestartRecovery
///
public class RecoverySettings
{
- private readonly RecoveryData recoveryData;
- private readonly uint pingInterval;
+ private RecoveryData recoveryData;
+ private uint pingInterval;
///
/// Initializes a new instance of the RecoverySettings class.
@@ -83,10 +83,9 @@ public uint PingInterval
public override string ToString()
{
return String.Format("delegate: {0}, state: {1}, ping: {2}",
- this.recoveryData.Callback.Method,
- this.recoveryData.State,
- this.PingInterval
- );
+ this.recoveryData.Callback.Method.ToString(),
+ this.recoveryData.State.ToString(),
+ this.PingInterval);
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryInterop.cs b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryInterop.cs
index 7a406b735..34976f142 100644
--- a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryInterop.cs
+++ b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryInterop.cs
@@ -44,7 +44,7 @@ static AppRestartRecoveryNativeMethods()
private static UInt32 InternalRecoveryHandler(IntPtr parameter)
{
- bool cancelled;
+ bool cancelled = false;
ApplicationRecoveryInProgress(out cancelled);
GCHandle handle = GCHandle.FromIntPtr(parameter);
diff --git a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryManager.cs b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryManager.cs
index c42c6bee8..e2ea8dad4 100644
--- a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryManager.cs
+++ b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartRecoveryManager.cs
@@ -40,7 +40,10 @@ public static class ApplicationRestartRecoveryManager
public static void RegisterForRestart()
{
// Register for automatic restart if the application was terminated for any reason other than a system reboot or a system update.
- RegisterForApplicationRestart(new RestartSettings("-recovered", RestartRestrictions.NotOnReboot | RestartRestrictions.NotOnPatch));
+ ApplicationRestartRecoveryManager.RegisterForApplicationRestart(
+ new RestartSettings("-recovered",
+ RestartRestrictions.NotOnReboot
+ | RestartRestrictions.NotOnPatch));
}
public static void RegisterForRecovery()
@@ -49,10 +52,9 @@ public static void RegisterForRecovery()
// In some cases it might make sense to pass this initial state.
// Another approach: When doing "auto-save", register for recovery everytime, and pass
// the current state I.E. data for recovery at that time.
- RecoveryData data = new RecoveryData(RecoveryProcedure, null);
+ RecoveryData data = new RecoveryData(new RecoveryCallback(RecoveryProcedure), null);
RecoverySettings settings = new RecoverySettings(data, 0);
-
- RegisterForApplicationRecovery(settings);
+ ApplicationRestartRecoveryManager.RegisterForApplicationRecovery(settings);
}
///
@@ -71,12 +73,12 @@ private static int RecoveryProcedure(object state)
try
{
// Remove the icons or they remain in the system try.
- ProcessHacker.Program.HackerWindow.ExecuteOnIcons(icon => icon.Visible = false);
- ProcessHacker.Program.HackerWindow.ExecuteOnIcons(icon => icon.Dispose());
+ ProcessHacker.Program.HackerWindow.ExecuteOnIcons((icon) => icon.Visible = false);
+ ProcessHacker.Program.HackerWindow.ExecuteOnIcons((icon) => icon.Dispose());
// Make sure KPH connection is closed.
- if (KProcessHacker2.Instance.KphIsConnected)
- KProcessHacker2.Instance.Dispose();
+ if (ProcessHacker.Native.KProcessHacker.Instance != null)
+ ProcessHacker.Native.KProcessHacker.Instance.Close();
}
catch { }
@@ -130,13 +132,10 @@ private static void RegisterForApplicationRecovery(RecoverySettings settings)
HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRecoveryCallback(AppRestartRecoveryNativeMethods.internalCallback, (IntPtr)handle, settings.PingInterval, (uint)0);
- switch (hr)
- {
- case HResult.InvalidArgument:
- throw new ArgumentException("Application was not registered for recovery due to bad parameters.");
- case HResult.Fail:
- throw new ExternalException("Application failed to register for recovery.");
- }
+ if (hr == HResult.InvalidArgument)
+ throw new ArgumentException("Application was not registered for recovery due to bad parameters.");
+ else if (hr == HResult.Fail)
+ throw new ExternalException("Application failed to register for recovery.");
}
}
@@ -177,7 +176,7 @@ private static bool ApplicationRecoveryInProgress()
{
if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
{
- bool canceled;
+ bool canceled = false;
HResult hr = AppRestartRecoveryNativeMethods.ApplicationRecoveryInProgress(out canceled);
@@ -186,8 +185,8 @@ private static bool ApplicationRecoveryInProgress()
return canceled;
}
-
- return true;
+ else
+ return true;
}
///
@@ -219,13 +218,10 @@ private static void RegisterForApplicationRestart(RestartSettings settings)
{
HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRestart(settings.Command, settings.Restrictions);
- switch (hr)
- {
- case HResult.Fail:
- throw new InvalidOperationException("Application failed to registered for restart.");
- case HResult.InvalidArgument:
- throw new ArgumentException("Failed to register application for restart due to bad parameters.");
- }
+ if (hr == HResult.Fail)
+ throw new InvalidOperationException("Application failed to registered for restart.");
+ else if (hr == HResult.InvalidArgument)
+ throw new ArgumentException("Failed to register application for restart due to bad parameters.");
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartSettings.cs b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartSettings.cs
index 861f2b5df..877515386 100644
--- a/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartSettings.cs
+++ b/1.x/trunk/ProcessHacker/Components/RestartRecoveryLib/RestartSettings.cs
@@ -32,8 +32,8 @@ namespace ProcessHackerRestartRecovery
/// less than 60 seconds beforeterminating.
public class RestartSettings
{
- private readonly string command;
- private readonly RestartRestrictions restrictions;
+ private string command;
+ private RestartRestrictions restrictions;
///
/// Creates a new instance of the RestartSettings class.
diff --git a/1.x/trunk/ProcessHacker/Components/SectionProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/SectionProperties.Designer.cs
index 85bd5c3dd..8b9d45ebc 100644
--- a/1.x/trunk/ProcessHacker/Components/SectionProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/SectionProperties.Designer.cs
@@ -42,7 +42,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 3);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(61, 13);
+ this.label1.Size = new System.Drawing.Size(54, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Attributes:";
//
@@ -69,7 +69,7 @@ private void InitializeComponent()
this.labelAttributes.AutoSize = true;
this.labelAttributes.Location = new System.Drawing.Point(75, 3);
this.labelAttributes.Name = "labelAttributes";
- this.labelAttributes.Size = new System.Drawing.Size(38, 13);
+ this.labelAttributes.Size = new System.Drawing.Size(36, 13);
this.labelAttributes.TabIndex = 0;
this.labelAttributes.Text = "Image";
//
@@ -77,7 +77,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.labelAttributes);
this.Controls.Add(this.labelSize);
this.Controls.Add(this.label2);
diff --git a/1.x/trunk/ProcessHacker/Components/SectionProperties.cs b/1.x/trunk/ProcessHacker/Components/SectionProperties.cs
index e0e9cb174..3dcc0c788 100644
--- a/1.x/trunk/ProcessHacker/Components/SectionProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/SectionProperties.cs
@@ -6,7 +6,7 @@ namespace ProcessHacker.Components
{
public partial class SectionProperties : UserControl
{
- private readonly SectionHandle _sectionHandle;
+ private SectionHandle _sectionHandle;
public SectionProperties(SectionHandle sectionHandle)
{
diff --git a/1.x/trunk/ProcessHacker/Components/SectionProperties.resx b/1.x/trunk/ProcessHacker/Components/SectionProperties.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/SectionProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/SectionProperties.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.Designer.cs
index c187078fb..d158aa1e9 100644
--- a/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.Designer.cs
@@ -44,7 +44,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 3);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(84, 13);
+ this.label1.Size = new System.Drawing.Size(75, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Current Count:";
//
@@ -53,7 +53,7 @@ private void InitializeComponent()
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 25);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(94, 13);
+ this.label2.Size = new System.Drawing.Size(85, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Maximum Count:";
//
@@ -101,7 +101,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.buttonAcquire);
this.Controls.Add(this.buttonRelease);
this.Controls.Add(this.label2);
diff --git a/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.cs b/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.cs
index 89e44030b..0cd493efe 100644
--- a/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.cs
@@ -9,7 +9,7 @@ namespace ProcessHacker.Components
{
public partial class SemaphoreProperties : UserControl
{
- private readonly SemaphoreHandle _semaphoreHandle;
+ private SemaphoreHandle _semaphoreHandle;
public SemaphoreProperties(SemaphoreHandle semaphoreHandle)
{
diff --git a/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.resx b/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/SemaphoreProperties.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/ServiceList.Designer.cs b/1.x/trunk/ProcessHacker/Components/ServiceList.Designer.cs
index e8d1ed296..33bd1aa98 100644
--- a/1.x/trunk/ProcessHacker/Components/ServiceList.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/ServiceList.Designer.cs
@@ -34,13 +34,13 @@ private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ServiceList));
- this.listServices = new ProcessHacker.Components.ExtendedListView();
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnDescription = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnStatus = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnStartType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnPID = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.listServices = new System.Windows.Forms.ListView();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnDescription = new System.Windows.Forms.ColumnHeader();
+ this.columnType = new System.Windows.Forms.ColumnHeader();
+ this.columnStatus = new System.Windows.Forms.ColumnHeader();
+ this.columnStartType = new System.Windows.Forms.ColumnHeader();
+ this.columnPID = new System.Windows.Forms.ColumnHeader();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
@@ -55,7 +55,6 @@ private void InitializeComponent()
this.columnStartType,
this.columnPID});
this.listServices.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listServices.DoubleClickChecks = true;
this.listServices.FullRowSelect = true;
this.listServices.HideSelection = false;
this.listServices.Location = new System.Drawing.Point(0, 0);
@@ -110,8 +109,8 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listServices);
+ this.DoubleBuffered = true;
this.Name = "ServiceList";
this.Size = new System.Drawing.Size(685, 472);
this.ResumeLayout(false);
@@ -120,7 +119,7 @@ private void InitializeComponent()
#endregion
- private ExtendedListView listServices;
+ private System.Windows.Forms.ListView listServices;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.ColumnHeader columnDescription;
diff --git a/1.x/trunk/ProcessHacker/Components/ServiceList.cs b/1.x/trunk/ProcessHacker/Components/ServiceList.cs
index 8ed3b420a..851ae92d2 100644
--- a/1.x/trunk/ProcessHacker/Components/ServiceList.cs
+++ b/1.x/trunk/ProcessHacker/Components/ServiceList.cs
@@ -22,7 +22,9 @@
using System;
using System.Collections.Generic;
+using System.Reflection;
using System.Windows.Forms;
+using ProcessHacker.Common;
using ProcessHacker.Common.Ui;
using ProcessHacker.Native.Api;
using ProcessHacker.UI;
@@ -32,10 +34,10 @@ namespace ProcessHacker.Components
public partial class ServiceList : UserControl
{
private ServiceProvider _provider;
- private int _runCount;
- private readonly HighlightingContext _highlightingContext;
- private readonly List _needsAdd = new List();
- private bool _needsSort;
+ private int _runCount = 0;
+ private HighlightingContext _highlightingContext;
+ private List _needsAdd = new List();
+ private bool _needsSort = false;
public new event KeyEventHandler KeyDown;
public new event MouseEventHandler MouseDown;
public new event MouseEventHandler MouseUp;
@@ -47,11 +49,12 @@ public ServiceList()
InitializeComponent();
_highlightingContext = new HighlightingContext(listServices);
- listServices.KeyDown += this.ServiceList_KeyDown;
- listServices.MouseDown += this.listServices_MouseDown;
- listServices.MouseUp += this.listServices_MouseUp;
- listServices.DoubleClick += this.listServices_DoubleClick;
- listServices.SelectedIndexChanged += this.listServices_SelectedIndexChanged;
+ listServices.SetTheme("explorer");
+ listServices.KeyDown += new KeyEventHandler(ServiceList_KeyDown);
+ listServices.MouseDown += new MouseEventHandler(listServices_MouseDown);
+ listServices.MouseUp += new MouseEventHandler(listServices_MouseUp);
+ listServices.DoubleClick += new EventHandler(listServices_DoubleClick);
+ listServices.SelectedIndexChanged += new System.EventHandler(listServices_SelectedIndexChanged);
listServices.ListViewItemSorter = new SortedListViewComparer(listServices);
}
@@ -87,6 +90,20 @@ private void ServiceList_KeyDown(object sender, KeyEventArgs e)
#region Properties
+ public new bool DoubleBuffered
+ {
+ get
+ {
+ return (bool)typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).GetValue(listServices, null);
+ }
+ set
+ {
+ typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).SetValue(listServices, value, null);
+ }
+ }
+
public override bool Focused
{
get
@@ -107,7 +124,7 @@ public override ContextMenuStrip ContextMenuStrip
set { listServices.ContextMenuStrip = value; }
}
- public ExtendedListView List
+ public ListView List
{
get { return listServices; }
}
@@ -119,10 +136,10 @@ public ServiceProvider Provider
{
if (_provider != null)
{
- _provider.DictionaryAdded -= this.provider_DictionaryAdded;
- _provider.DictionaryModified -= this.provider_DictionaryModified;
- _provider.DictionaryRemoved -= this.provider_DictionaryRemoved;
- _provider.Updated -= this.provider_Updated;
+ _provider.DictionaryAdded -= new ServiceProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryModified -= new ServiceProvider.ProviderDictionaryModified(provider_DictionaryModified);
+ _provider.DictionaryRemoved -= new ServiceProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated -= new ServiceProvider.ProviderUpdateOnce(provider_Updated);
}
_provider = value;
@@ -133,10 +150,10 @@ public ServiceProvider Provider
{
//_provider.InterlockedExecute(new MethodInvoker(() =>
//{
- _provider.DictionaryAdded += this.provider_DictionaryAdded;
- _provider.DictionaryModified += this.provider_DictionaryModified;
- _provider.DictionaryRemoved += this.provider_DictionaryRemoved;
- _provider.Updated += this.provider_Updated;
+ _provider.DictionaryAdded += new ServiceProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryModified += new ServiceProvider.ProviderDictionaryModified(provider_DictionaryModified);
+ _provider.DictionaryRemoved += new ServiceProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated += new ServiceProvider.ProviderUpdateOnce(provider_Updated);
foreach (ServiceItem item in _provider.Dictionary.Values)
{
@@ -196,13 +213,13 @@ private void provider_Updated()
if (_needsSort)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- if (_needsSort)
{
- listServices.Sort();
- _needsSort = false;
- }
- }));
+ if (_needsSort)
+ {
+ listServices.Sort();
+ _needsSort = false;
+ }
+ }));
}
_runCount++;
@@ -220,18 +237,21 @@ public void UpdateItems()
private void provider_DictionaryAdded(ServiceItem item)
{
- HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext, item.RunId > 0 && _runCount > 0)
- {
- Name = item.Status.ServiceName,
- Text = item.Status.ServiceName
- };
-
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Status.DisplayName));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Status.ServiceStatusProcess.ServiceType.ToString()));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Status.ServiceStatusProcess.CurrentState.ToString()));
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Config.StartType.ToString()));
+ HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext,
+ item.RunId > 0 && _runCount > 0);
+
+ litem.Name = item.Status.ServiceName;
+ litem.Text = item.Status.ServiceName;
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem,
+ item.Status.DisplayName));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem,
+ item.Status.ServiceStatusProcess.ServiceType.ToString()));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem,
+ item.Status.ServiceStatusProcess.CurrentState.ToString()));
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem,
+ item.Config.StartType.ToString()));
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem,
- item.Status.ServiceStatusProcess.ProcessID == 0 ? string.Empty :
+ item.Status.ServiceStatusProcess.ProcessID == 0 ? "" :
item.Status.ServiceStatusProcess.ProcessID.ToString()));
if ((item.Status.ServiceStatusProcess.ServiceType & ServiceType.InteractiveProcess) != 0)
@@ -267,7 +287,7 @@ private void provider_DictionaryModified(ServiceItem oldItem, ServiceItem newIte
litem.SubItems[2].Text = newItem.Status.ServiceStatusProcess.ServiceType.ToString();
litem.SubItems[3].Text = newItem.Status.ServiceStatusProcess.CurrentState.ToString();
litem.SubItems[4].Text = newItem.Config.StartType.ToString();
- litem.SubItems[5].Text = newItem.Status.ServiceStatusProcess.ProcessID == 0 ? string.Empty :
+ litem.SubItems[5].Text = newItem.Status.ServiceStatusProcess.ProcessID == 0 ? "" :
newItem.Status.ServiceStatusProcess.ProcessID.ToString();
_needsSort = true;
}
diff --git a/1.x/trunk/ProcessHacker/Components/ServiceList.resx b/1.x/trunk/ProcessHacker/Components/ServiceList.resx
index 2d0bf5c69..6cdf0e270 100644
--- a/1.x/trunk/ProcessHacker/Components/ServiceList.resx
+++ b/1.x/trunk/ProcessHacker/Components/ServiceList.resx
@@ -112,99 +112,99 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
- AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w
+ AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w
LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZTeXN0
ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMAAACa
- EwAAAk1TRnQBSQFMAgEBBAEAAQwBAAEMAQABEAEAARABAAT/ASEBAAj/AUIBTQE2BwABNgMAASgDAAFA
+ EwAAAk1TRnQBSQFMAgEBBAEAAQwBAAEEAQABEAEAARABAAT/ASEBAAj/AUIBTQE2BwABNgMAASgDAAFA
AwABIAMAAQEBAAEgBgABIP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8AegADOwFjA1gBvwNX
- Ab8DOwFjWAADQAFwAVICVAGmAVEBZQF5AeoBOwF/AaQB9wE7AX8BpAH3ATsBfwGkAfcBOwF/AaQB9wE7
- AX8BpAH3ATsBfwGkAfcBOwF/AaQB9wE7AX8BpAH3ATsBfQGkAfcBTAFwAZAB8QNMAZNUAAMdASkDCgEO
- AwEBAgNjAeoDvQH/A7IB/wNcAeoDAQECAwoBDgMdASkUAAMKAQ0DDgETA04BmAFkAlgB4wGAAUYBQQH1
- AZIBTQEpAfoBkgFNASkB+gF7AUgBNwH2AWYBVQFSAeoBVwJVAboDEAEWAwoBDQgAAVgBaQF0AeYBiQGP
- AZEB8AGnAcMB2gH9AZ4B2wH0Af8BlgHaAfMB/wGOAdgB8wH/AYYB1wHzAf8BdgHUAfIB/wFwAdMB8gH/
- AWkB0gHxAf8BYwHQAfEB/wFgAc8B8QH/AbEB2QHnAf4BTQFsAYcB8AgAA1IBqQHDAY4BXQH/AcABiwFb
- Af8BvgGIAVkB/wG7AYUBVgH/AbkBgwFUAf8BtAFzAVEB/wGyAXEBTwH/AbEBcAFNAf8BrgFuAUwB/wGt
- AWsBSwH/AasBagFJAf8BqQFoAUgB/wGpAWYBRgH/A1IBqQwAA1ABmwNaAf0DZAHnAxIBGQNkAecDywH/
- A8cB/wNiAecDEgEZA1wB5wNEAf0DTwGbDAADRAF5ASYBXwGlAfsBcwJfAfsBvwFVASoB/wH+AbkBVgH/
- Af4BuQFXAf8B/gG5AVcB/wH+AbkBVwH/Af4BuQFWAf8B/gG5AVYB/wGxAT4BGQH/AWgBWQFeAfUBPgFz
- AZwB+ANIAYMEAAE/AYQBpwH3Ae8B+gH+Af8BoQHpAfkB/wGRAeUB+AH/AYEB4QH3Af8BaQHeAfYB/wFa
- AdoB9QH/AUsB1wH0Af8BPgHTAfMB/wEwAdAB8gH/ASUBzQHxAf8BHQHLAfAB/wHKAfIB+wH/AT8BhAGn
- AfcIAAHIAZIBYTX/AakBZwFGAf8IAANEAXsDvAH/A94B/wOmAf8DZwH0A38B/gPEAf8DwgH/A20B/gNl
- AfQDpgH/A9IB/wOAAf8DRAF7CAABKQF9AbwB/gGCAboB7gH/AZ8BWwFNAf8B9QG7AYQC/wGsAVAB/wH+
- AagBTwH/Af4BogFMAf8B/gGcAUgC/wGjAUoC/wGfAUUB/wH4Aa4BbQH/AaQBUwE/Af8BgwG8Ae8B/wEq
- AXcBtQH+BAABPgGEAaoB+AHyAfoB/QH/AbMB7QH6Af8BpAHpAfkB/wGVAeYB+AH/AYUB4gH3Af8BgQHh
- AfcB/wFxAeAB9wH/AWYB3QH2Af8BWQHaAfUB/wFLAdYB8wH/AT4B0wHyAf8B6AH5Af0B/wEsAZQB2gH/
- CAABygGUAWML/wH+A/8B/QH/Av4B/QH/Av4B/AH/Av4B/AH/Av4B/AH/Av4B/AH/Av4B+gH/Av4B+gH/
- AvwB+QX/AaoBaAFIAf8IAANFAX0DkQH+A9UB/wPFAf8DywH/A9EB/wPJAf8DxwH/A8wB/wPFAf8DvQH/
- A8sB/wNuAf4DRQF9CAABKwFxAbMB/AFtAbMB6gH/AbMBngGUAv8BtwFVAv8BtgFYAf8B/gGyAVYB/wH+
- AawBUgH/Af4BpQFOAf8B/QGeAUgB/wH+AZcBQwL/AY0BOAH/AbwBjwGCAf8BcwG4Ae0B/wEqAWkBoAH6
- BAABQQGLAa8B+QH2AfwB/gH/AcgB8gH8Af8BuQHvAfsB/wGsAewB+gH/AYwB5AH4Af8BigHjAfgB/wGC
- AeEB9wH/AXAB3wH3Af8BZAHdAfYB/wFYAdoB9QH/AU4B1wH0Af8B5wH4Af0B/wEsAZQB2gH/CAABzAGX
- AWQH/wH8A/8B/QH/Av4B/AH/Av4B/AH/Av4B+wH/Av0B+gH/Av0B+gH/Av0B+gH/Av0B+gH/AvwB9wH/
- AvsB9gX/AawBagFJAf8MAANIAYUDxQH/A8EB/wPFAf8DxwH/A6oB/wOnAf8DwQH/A74B/wO1Af8DqgH/
- A0gBhQwAAzIBUAGKAUkBOQH/AfwByAGrAv8B0QGYAf8B/gHHAWIB/wH+Ab8BXQH/Af4BuQFZAf8B/gGx
- AVMB/wH+AagBTgH/Af0BoAFJAv8BtwFvAf8B/gGpAYAB/wGIAUUBNwH/AjoBOQFgBAABQAGSAa8B+gH+
+ Ab8DOwFjWAADQAFwAVICVAGmAVABZgF9AeoBOgGAAagB9wE6AYABqAH3AToBgAGoAfcBOgGAAagB9wE6
+ AYABqAH3AToBgAGoAfcBOgGAAagB9wE6AYABqAH3AToBfwGoAfcBSQFyAZQB8QNMAZNUAAMdASkDCgEO
+ AwEBAgNkAeoDvQH/A7IB/wNcAeoDAQECAwoBDgMdASkUAAMKAQ0DDgETA04BmAFlAlgB4wGCAUYBPgH1
+ AZUBTQEpAfoBlQFNASkB+gF9AUgBNgH2AWkBVQFRAeoBVwJVAboDEAEWAwoBDQgAAVgBagF5AeYBjgGW
+ AZgB8AGnAcYB3QH9AZ4B2wH0Af8BlgHaAfMB/wGOAdgB8wH/AYYB1wHzAf8BdwHUAfIB/wFxAdMB8gH/
+ AWoB0gHxAf8BZAHQAfEB/wFhAc8B8QH/AbMB2wHpAf4BSwFuAYwB8AgAA1IBqQHDAY4BXgH/AcABiwFc
+ Af8BvgGIAVoB/wG7AYUBVwH/AbkBgwFVAf8BtAF0AVIB/wGyAXIBUAH/AbEBcQFOAf8BrgFvAU0B/wGt
+ AWwBTAH/AasBawFKAf8BqQFpAUkB/wGpAWcBRwH/A1IBqQwAA1ABmwNcAf0DZAHnAxIBGQNkAecDywH/
+ A8cB/wNiAecDEgEZA1wB5wNFAf0DTwGbDAADRAF5ASYBXwGpAfsBdgJfAfsBvwFWASsB/wH+AbkBVwH/
+ Af4BuQFYAf8B/gG5AVgB/wH+AbkBWAH/Af4BuQFXAf8B/gG5AVcB/wGxAT8BGgH/AWkBWQFgAfUBPgF0
+ AZ8B+ANIAYMEAAE+AYUBqwH3Ae8B+gH+Af8BoQHpAfkB/wGRAeUB+AH/AYEB4QH3Af8BagHeAfYB/wFb
+ AdoB9QH/AUwB1wH0Af8BPwHTAfMB/wExAdAB8gH/ASYBzQHxAf8BHgHLAfAB/wHKAfIB+wH/AT4BhQGr
+ AfcIAAHIAZIBYjX/AakBaAFHAf8IAANEAXsDvAH/A94B/wOmAf8DagH0A38B/gPEAf8DwgH/A20B/gNl
+ AfQDpgH/A9IB/wOAAf8DRAF7CAABKQF9Ab4B/gGCAboB7gH/AZ8BXAFOAf8B9QG7AYQC/wGsAVEB/wH+
+ AagBUAH/Af4BogFNAf8B/gGcAUkC/wGjAUsC/wGfAUYB/wH4Aa4BbgH/AaQBVAFAAf8BgwG8Ae8B/wEq
+ AXcBtwH+BAABPgGHAa8B+AHyAfoB/QH/AbMB7QH6Af8BpAHpAfkB/wGVAeYB+AH/AYUB4gH3Af8BgQHh
+ AfcB/wFyAeAB9wH/AWcB3QH2Af8BWgHaAfUB/wFMAdYB8wH/AT8B0wHyAf8B6AH5Af0B/wEtAZQB2gH/
+ CAABygGUAWQL/wH+A/8B/QH/Av4B/QH/Av4B/AH/Av4B/AH/Av4B/AH/Av4B/AH/Av4B+gH/Av4B+gH/
+ AvwB+QX/AaoBaQFJAf8IAANFAX0DkwH+A9UB/wPFAf8DywH/A9EB/wPJAf8DxwH/A8wB/wPFAf8DvQH/
+ A8sB/wNuAf4DRQF9CAABKwFyAbUB/AFuAbMB6gH/AbMBngGUAv8BtwFWAv8BtgFZAf8B/gGyAVcB/wH+
+ AawBUwH/Af4BpQFPAf8B/QGeAUkB/wH+AZcBRAL/AY0BOQH/AbwBjwGCAf8BdAG4Ae0B/wEqAWoBogH6
+ BAABQQGMAbIB+QH2AfwB/gH/AcgB8gH8Af8BuQHvAfsB/wGsAewB+gH/AYwB5AH4Af8BigHjAfgB/wGC
+ AeEB9wH/AXEB3wH3Af8BZQHdAfYB/wFZAdoB9QH/AU8B1wH0Af8B5wH4Af0B/wEtAZQB2gH/CAABzAGX
+ AWUH/wH8A/8B/QH/Av4B/AH/Av4B/AH/Av4B+wH/Av0B+gH/Av0B+gH/Av0B+gH/Av0B+gH/AvwB9wH/
+ AvsB9gX/AawBawFKAf8MAANIAYUDxQH/A8EB/wPFAf8DxwH/A6oB/wOnAf8DwQH/A74B/wO1Af8DqgH/
+ A0gBhQwAAzIBUAGKAUoBOgH/AfwByAGrAv8B0QGYAf8B/gHHAWMB/wH+Ab8BXgH/Af4BuQFaAf8B/gGx
+ AVQB/wH+AagBTwH/Af0BoAFKAv8BtwFwAf8B/gGpAYAB/wGIAUYBOAH/AjoBOQFgBAABPwGVAbMB+gH+
A/8B+AH9Av8B9gH9Av8B9QH8Av8B3gHbAdEB/wGtAcoBxQH/AaYBxQHAAf8BpAHDAb0B/wGeAb0BtgH/
- AZcBugGzAf8BkgG4AbIB/wHhAcsBtwH/ASwBlAHaAf8BwwGEAUkB/wJVAVMBsAHRAZwBaAX/Av4B/AH/
+ AZcBugGzAf8BkgG4AbIB/wHhAcsBtwH/AS0BlAHaAf8BwwGEAUoB/wJVAVMBsAHRAZwBaQX/Av4B/AH/
Av4B/AH/Av4B/AH/Av0B+wH/Av0B+wH/Av0B+gH/Av0B+AH/AvsB+QH/AfsB+gH3Af8B+wH6AfYB/wH7
- AfgB9AX/AbABbwFNAf8EAANcAc0DYAHjA2wB7gPPAf8DxgH/A8wB/wNbAcYDLAFEAywBRANbAcYDwQH/
- A7wB/wO5Af8DYQHuA1kB4wNaAc0HAAEBAjoBOQFgAcQBQQEUAf8B9gHkAdYC/wHkAaQC/wHUAWcC/wHJ
- AV4C/wHAAVgC/wG2AVQC/wHBAYAB/wH2AdcBxgH/AcUBPgEUAf8DPQFpAwMBBAQAAT4BmAGvAfoB6AH2
- AfsB/wF1AcUB6gH/AVIBrgHjAf8BSAGoAeEB/wFYAa0B3wH/Ae0B9gH3Af8B7QH1AfYB/wHnAe8B8wH/
- AeUB7AHuAf8B5QHrAe0B/wHlAesB7QH/AfgB8wHvAf8BLAGUAdoB/wHwAeIB2AH/AbgBigFQAf0B1AGe
- AWoF/wL+AfwB/wL9AfsB/wL9AfwB/wL9AfsB/wL9AfkB/wL8AfgB/wH7AfkB9wH/AfsB+QH1Af8B+wH4
- AfQB/wH7AfcB8gH/AfsB9QHyBf8BsgFxAU8B/wQAA7QB/QPiAf8D0gH/A8YB/wPNAf8DsQH/AywBRAgA
- AywBRAOoAf8DwgH/A7cB/wPAAf8D0gH/A1AB/QgAAwUBBwM9AWkBvAE9AREB/wH0AeIB1AH/AUMBcAGp
- Af8BQgFwAagB/wFCAXABqAH/AUMBcAGpAf8B8wHWAcMB/wG+ATsBEQH/AkABPwFvAwcBCggAAUsBfwGQ
- AfIB8QH6Af0B/wGUAd4B9QH/AZMB3AH0Af8BgQHVAfIB/wHAAakBlwH/AZEBwQHkAf8BLAGUAdoB/wEs
- AZQB2gH/ASwBlAHaAf8BLAGUAdoB/wEsAZQB2gH/ASwBlAHaAf8BLAGUAdoB/wHwAeIB2AH/AcQBhgFL
- Af8B1QGgAWsF/wL9AfwB/wL9AfsB/wL9AfoB/wL8AfkB/wH8AfsB9wH/AfsB+QH1Af8B+wH4AfQB/wH7
- AfcB8wH/AfsB9QHyAf8B+gHzAe8B/wH4AfIB7AX/AbUBcwFRAf8EAAO2Af0D6QH/A9YB/wPJAf8DzgH/
- A6UB/wMsAUQIAAMsAUQDrAH/A8QB/wO6Af8DxgH/A90B/wNWAf0MAAMEAQUDUQGiASkBYgGnAf8BnAHM
- AfgB/wGvAdQB9wH/Aa8B1AH3Af8BpQHPAfYB/wEpAWkBrgH/AVUCUwGtAwcBCQwAAU4BeQGIAfAB9wH8
+ AfgB9AX/AbABcAFOAf8EAANcAc0DYgHjA24B7gPPAf8DxgH/A8wB/wNbAcYDLAFEAywBRANbAcYDwQH/
+ A7wB/wO5Af8DYQHuA1kB4wNaAc0HAAEBAjoBOQFgAcQBQgEVAf8B9gHkAdYC/wHkAaQC/wHUAWgC/wHJ
+ AV8C/wHAAVkC/wG2AVUC/wHBAYAB/wH2AdcBxgH/AcUBPwEVAf8DPQFpAwMBBAQAAT0BmgGzAfoB6AH2
+ AfsB/wF2AcUB6gH/AVMBrgHjAf8BSQGoAeEB/wFZAa0B3wH/Ae0B9gH3Af8B7QH1AfYB/wHnAe8B8wH/
+ AeUB7AHuAf8B5QHrAe0B/wHlAesB7QH/AfgB8wHvAf8BLQGUAdoB/wHwAeIB2AH/AbkBigFRAf0B1AGe
+ AWsF/wL+AfwB/wL9AfsB/wL9AfwB/wL9AfsB/wL9AfkB/wL8AfgB/wH7AfkB9wH/AfsB+QH1Af8B+wH4
+ AfQB/wH7AfcB8gH/AfsB9QHyBf8BsgFyAVAB/wQAA7UB/QPiAf8D0gH/A8YB/wPNAf8DsQH/AywBRAgA
+ AywBRAOoAf8DwgH/A7cB/wPAAf8D0gH/A1EB/QgAAwUBBwM9AWkBvAE+ARIB/wH0AeIB1AH/AUQBcQGp
+ Af8BQwFxAagB/wFDAXEBqAH/AUQBcQGpAf8B8wHWAcMB/wG+ATwBEgH/AkABPwFvAwcBCggAAUoBgwGW
+ AfIB8QH6Af0B/wGUAd4B9QH/AZMB3AH0Af8BgQHVAfIB/wHAAakBlwH/AZEBwQHkAf8BLQGUAdoB/wEt
+ AZQB2gH/AS0BlAHaAf8BLQGUAdoB/wEtAZQB2gH/AS0BlAHaAf8BLQGUAdoB/wHwAeIB2AH/AcQBhgFM
+ Af8B1QGgAWwF/wL9AfwB/wL9AfsB/wL9AfoB/wL8AfkB/wH8AfsB9wH/AfsB+QH1Af8B+wH4AfQB/wH7
+ AfcB8wH/AfsB9QHyAf8B+gHzAe8B/wH4AfIB7AX/AbUBdAFSAf8EAAO3Af0D6QH/A9YB/wPJAf8DzgH/
+ A6UB/wMsAUQIAAMsAUQDrAH/A8QB/wO6Af8DxgH/A90B/wNYAf0MAAMEAQUDUQGiASoBYwGnAf8BnAHM
+ AfgB/wGvAdQB9wH/Aa8B1AH3Af8BpQHPAfYB/wEqAWoBrgH/AVUCUwGtAwcBCQwAAUwBfAGNAfAB9wH8
Af4B/wGOAeQB+AH/AZEB3gH1Af8BnwHgAfUB/wHjAbEBjAH/AfoB9gHxAf8B6gHJAa4F/wHoAccBrBH/
- AfEB5QHbAf8BxgGGAUwB/wHYAaIBbgX/Av0B+gH/AvwB+gH/AfwB+wH5Af8B+wH6AfYB/wH7AfgB9QH/
- AfsB9wH0Af8B+wH2AfEB/wH4AfQB7gH/AfcB8gHrAf8B9wHwAeoB/wH2AewB6AX/AbcBgQFTAf8EAANc
- Ac0DZgHjA3YB7gPYAf8DzQH/A7wB/wNbAcYDLAFEAywBRANbAcYDwwH/A8IB/wPNAf8DZwHuA18B4wNc
+ AfEB5QHbAf8BxgGGAU0B/wHYAaIBbwX/Av0B+gH/AvwB+gH/AfwB+wH5Af8B+wH6AfYB/wH7AfgB9QH/
+ AfsB9wH0Af8B+wH2AfEB/wH4AfQB7gH/AfcB8gHrAf8B9wHwAeoB/wH2AewB6AX/AbcBgQFUAf8EAANc
+ Ac0DaAHjA3kB7gPYAf8DzQH/A7wB/wNbAcYDLAFEAywBRANbAcYDwwH/A8IB/wPNAf8DaQHuA2AB4wNc
Ac0QAAFZAlsBxAGmAcoB7gH/AasBzAHqAf8BpwHQAfYB/wGoAdAB9gH/AasBzAHqAf8BpwHNAe4B/wFZ
- AlwBzBAAAT4BlQGqAfgB/QL+Af8B/gP/Av4C/wH9Af4C/wHlAbQBjwH/AfoB9gHyAf8B6QHGAaoB/wHp
- AcYBrAH/AegBxwGsAf8B6AHHAawB/wHpAckBsAH/AegByAGwAf8B6AHMAbUB/wHyAecB3gH/AcgBigFQ
- Af8B2QGjAW4F/wH8AfsB+QH/AfwB+wH4Af8B+wH5AfcB/wH7AfcB9AH/AfoB9wHyAf8B+QH1AfAB/wH3
- AfMB7QH/AfYB7wHqAf8B9QHrAecB/wHzAeoB5AH/AfIB5wHeBf8BugGFAVUB/wwAA0gBhQPUAf8DzAH/
- A8kB/wO6Af8DnAH/A6EB/wPCAf8DxgH/A8EB/wO3Af8DSAGFGAABUQFdAWsB7QHZAegB9wH/AZcBxQHx
- Af8BjgG7AeUB/wF0AakB0QH/AYkBtQHfAf8BzQHfAe4B/wFMAWQBdwHxAwQBBgwAAVsBXgFgAdABUAGi
- AbYB+gFRAaMBtwH6AVEBowG3AfoBUQGjAbcB+gHnAbcBlAH/AfsB9wH0Af8B6QHDAaYF/wHoAccBrBH/
- AfcB8QHrAf8BywGPAVYB/wHbAaQBbzX/Ab0BhwFYAf8IAANFAX0DrwH+A9wB/wPUAf8D2QH/A9sB/wPW
- Af8D1AH/A9kB/wPSAf8DywH/A8gB/wN5Af4DRQF9FAABAQEzAYcB/wFxAZcBuAH/AYoBtwHkAf8BZgGc
- AcgB/wEKATUBYwH/AQ4BOQFnAf8BFwE6AWAB/wEjAUYBUgH6AwUBByAAAekBugGYAf8B+wH3AfQB/wHp
+ AlwBzBAAAT4BlwGvAfgB/QL+Af8B/gP/Av4C/wH9Af4C/wHlAbQBjwH/AfoB9gHyAf8B6QHGAaoB/wHp
+ AcYBrAH/AegBxwGsAf8B6AHHAawB/wHpAckBsAH/AegByAGwAf8B6AHMAbUB/wHyAecB3gH/AcgBigFR
+ Af8B2QGjAW8F/wH8AfsB+QH/AfwB+wH4Af8B+wH5AfcB/wH7AfcB9AH/AfoB9wHyAf8B+QH1AfAB/wH3
+ AfMB7QH/AfYB7wHqAf8B9QHrAecB/wHzAeoB5AH/AfIB5wHeBf8BugGFAVYB/wwAA0gBhQPUAf8DzAH/
+ A8kB/wO6Af8DnAH/A6EB/wPCAf8DxgH/A8EB/wO3Af8DSAGFGAABUAFdAW4B7QHZAegB9wH/AZcBxQHx
+ Af8BjgG7AeUB/wF1AakB0QH/AYkBtQHfAf8BzQHfAe4B/wFJAWQBewHxAwQBBgwAAVsBYAFiAdABUQGk
+ AbsB+gFSAaUBvAH6AVIBpQG8AfoBUgGlAbwB+gHnAbcBlAH/AfsB9wH0Af8B6QHDAaYF/wHoAccBrBH/
+ AfcB8QHrAf8BywGPAVcB/wHbAaQBcDX/Ab0BhwFZAf8IAANFAX0DsQH+A9wB/wPUAf8D2QH/A9sB/wPW
+ Af8D1AH/A9kB/wPSAf8DywH/A8gB/wN5Af4DRQF9FAABAgE0AYcB/wFyAZcBuAH/AYoBtwHkAf8BZwGc
+ AcgB/wELATYBZAH/AQ8BOgFoAf8BGAE7AWEB/wEiAUUBUwH6AwUBByAAAekBugGYAf8B+wH3AfQB/wHp
AcMBpgH/AekBwwGmAf8B6QHDAaYB/wHpAcMBpgH/AekBwwGmAf8B6QHDAaYB/wHpAcMBpgH/AfsB9wH0
- Af8BzgGTAVsB/wHcAacBcAH/AdwBpwFwAf8B3AGnAXAB/wHcAacBcAH/AdwBpwFwAf8B3AGnAXAB/wHc
- AacBcAH/AdwBpwFwAf8B3AGnAXAB/wHcAacBcAH/AdwBpwFwAf8B3AGnAXAB/wHcAacBcAH/AdwBpwFw
- Af8BwAGLAVsB/wgAA0QBewPcAf8D7QH/A9sB/wOGAfQDqQH+A9YB/wPUAf8DmwH+A30B9APLAf8D5wH/
- A7cB/wNEAXsUAAEEAUABlwH/AQcBTQGfAf8BBAE/AYoB/wEEAUABhwH/AQYBQAGHAf8BCgFBAYUB/wEH
- ATYBagH/AUcBUwFgAfEkAAHrAb0BmwH/AfsB9wH0Hf8B+wH3AfQB/wHRAZcBYQH/Ab4BqAGFAf0B6AG5
+ Af8BzgGTAVwB/wHcAacBcQH/AdwBpwFxAf8B3AGnAXEB/wHcAacBcQH/AdwBpwFxAf8B3AGnAXEB/wHc
+ AacBcQH/AdwBpwFxAf8B3AGnAXEB/wHcAacBcQH/AdwBpwFxAf8B3AGnAXEB/wHcAacBcQH/AdwBpwFx
+ Af8BwAGLAVwB/wgAA0QBewPcAf8D7QH/A9sB/wOKAfQDqwH+A9YB/wPUAf8DnQH+A38B9APLAf8D5wH/
+ A7cB/wNEAXsUAAEFAUEBlwH/AQgBTgGfAf8BBQFAAYoB/wEFAUEBhwH/AQcBQQGHAf8BCwFCAYUB/wEI
+ ATcBawH/AUUBUQFgAfEkAAHrAb0BmwH/AfsB9wH0Hf8B+wH3AfQB/wHRAZcBYgH/AcABqAGFAf0B6AG5
AZIB/wHoAbkBkgH/AegBuQGSAf8B6AG5AZIB/wHoAbkBkgH/AegBuQGSAf8B6AG5AZIB/wHoAbkBkgH/
- AegBuQGSAf8B6AG5AZIB/wHoAbkBkgH/AegBuQGSAf8B6AG5AZIB/wG1AZABWgH9DAADUAGbA7kB/QNt
- AecDEgEZA20B5wPeAf8D3QH/A2sB5wMSARkDaQHnA6cB/QNQAZsYAANDAXcBEQFOAYEB/gEHAU0BmwH/
- AQcBTQGZAf8BBgFIAZMB/wEEAT8BhwH/AQ4BPgFxAf4CRgFHAYEkAAHsAb8BngH/AfsB9wH0Af8BnAHV
- AaUB/wGYAdMBoQH/AYsBywGTAf8BggHGAYkB/wF1AcMBhAH/AXEBwQGAAf8BbQG+AXMB/wH7AfcB9AH/
- AdQBmwFmAf8DPgFrAY4BfQFvAfQB3AGnAXAB/wHcAaYBbwH/AdoBpAFvAf8B2AGiAW4B/wHVAaABawH/
- AdQBngFqAf8B0gGdAWgB/wHPAZoBZwH/Ac4BmQFlAf8BywGWAWQB/wHJAZQBYQH/AYcBdwFlAfQDPgFr
- EAADHQEpAwoBDgMBAQIDbwHqA+UB/wPkAf8DaQHqAwEBAgMKAQ4DHQEpIAADRQF9AT4BUgFvAfQBBQFA
- AZAB/wEEAT0BigH/ATcBQwFpAfUDSAGEKAABhAF5AXMB6wH7AfcB9AH/AfsB9wH0Af8B+wH3AfQB/wH7
- AfcB9AH/AfsB9wH0Af8B+wH3AfQB/wH7AfcB9AH/AfsB9wH0Af8B+wH3AfQB/wGnAYsBaQH4WAADOwFj
- A1kBvwNZAb8DOwFjbAADRgF+AXABaQFmAeMB7QHAAZ8B/wHrAb4BnQH/AecBtwGTAf8B5AGyAYwB/wHi
- Aa8BiAH/AeABrAGEAf8B3QGpAYAB/wHcAaUBdAH/A10BygFCAU0BPgcAAT4DAAEoAwABQAMAASADAAEB
+ AegBuQGSAf8B6AG5AZIB/wHoAbkBkgH/AegBuQGSAf8B6AG5AZIB/wG2AZABXAH9DAADUAGbA7oB/QNv
+ AecDEgEZA28B5wPeAf8D3QH/A20B5wMSARkDawHnA6cB/QNQAZsYAANDAXcBEQFOAYMB/gEIAU4BmwH/
+ AQgBTgGZAf8BBwFJAZMB/wEFAUABhwH/AQ4BPgFxAf4CRgFHAYEkAAHsAb8BngH/AfsB9wH0Af8BnAHV
+ AaUB/wGYAdMBoQH/AYsBywGTAf8BggHGAYkB/wF2AcMBhAH/AXIBwQGAAf8BbgG+AXQB/wH7AfcB9AH/
+ AdQBmwFnAf8DPgFrAZIBgQFyAfQB3AGnAXEB/wHcAaYBcAH/AdoBpAFwAf8B2AGiAW8B/wHVAaABbAH/
+ AdQBngFrAf8B0gGdAWkB/wHPAZoBaAH/Ac4BmQFmAf8BywGWAWUB/wHJAZQBYgH/AYsBeQFlAfQDPgFr
+ EAADHQEpAwoBDgMBAQIDcgHqA+UB/wPkAf8DbAHqAwEBAgMKAQ4DHQEpIAADRQF9AT0BUgFyAfQBBgFB
+ AZAB/wEFAT4BigH/ATQBQwFqAfUDSAGEKAABigF9AXYB6wH7AfcB9AH/AfsB9wH0Af8B+wH3AfQB/wH7
+ AfcB9AH/AfsB9wH0Af8B+wH3AfQB/wH7AfcB9AH/AfsB9wH0Af8B+wH3AfQB/wGsAY4BawH4WAADOwFj
+ A1kBvwNZAb8DOwFjbAADRgF+AXYBbQFoAeMB7QHAAZ8B/wHrAb4BnQH/AecBtwGTAf8B5AGyAYwB/wHi
+ Aa8BiAH/AeABrAGEAf8B3QGpAYAB/wHcAaUBdQH/A10BygFCAU0BPgcAAT4DAAEoAwABQAMAASADAAEB
AQABAQYAAQEWAAP/gQAC/wH8AT8C/wEAAQMC/wHgAQcBwAEDAQABAwEAAQEBwAEDAYABAQEAAQMBAAEB
AYABAQGAAQEBAAEDAQABAQGAAQEBgAEBAQABAwEAAQEBwAEDAYABAQMAAQECAAGAAQEDAAIBAYABwAED
AwACAQGAAeABBwMAAQECAAHwAQ8DAAEBAcABAwHwAQcDAAEBAYABAQHwAQcB+AIAAQEBgAEBAfABDwH4
diff --git a/1.x/trunk/ProcessHacker/Components/ServiceProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/ServiceProperties.Designer.cs
index acfc699af..8d374d3d0 100644
--- a/1.x/trunk/ProcessHacker/Components/ServiceProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/ServiceProperties.Designer.cs
@@ -33,10 +33,10 @@ protected override void Dispose(bool disposing)
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
- this.listServices = new ProcessHacker.Components.ExtendedListView();
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnDescription = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnStatus = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.listServices = new System.Windows.Forms.ListView();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnDescription = new System.Windows.Forms.ColumnHeader();
+ this.columnStatus = new System.Windows.Forms.ColumnHeader();
this.panelService = new System.Windows.Forms.Panel();
this.buttonPermissions = new System.Windows.Forms.Button();
this.textServiceDll = new System.Windows.Forms.TextBox();
@@ -70,14 +70,13 @@ private void InitializeComponent()
//
// listServices
//
- this.listServices.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.listServices.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.listServices.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnName,
this.columnDescription,
this.columnStatus});
- this.listServices.DoubleClickChecks = true;
this.listServices.FullRowSelect = true;
this.listServices.HideSelection = false;
this.listServices.Location = new System.Drawing.Point(3, 3);
@@ -108,8 +107,8 @@ private void InitializeComponent()
//
// panelService
//
- this.panelService.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.panelService.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.panelService.Controls.Add(this.buttonPermissions);
this.panelService.Controls.Add(this.textServiceDll);
this.panelService.Controls.Add(this.label8);
@@ -156,12 +155,12 @@ private void InitializeComponent()
//
// textServiceDll
//
- this.textServiceDll.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textServiceDll.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textServiceDll.Location = new System.Drawing.Point(107, 222);
this.textServiceDll.Name = "textServiceDll";
this.textServiceDll.ReadOnly = true;
- this.textServiceDll.Size = new System.Drawing.Size(274, 22);
+ this.textServiceDll.Size = new System.Drawing.Size(274, 20);
this.textServiceDll.TabIndex = 23;
//
// label8
@@ -169,7 +168,7 @@ private void InitializeComponent()
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(6, 225);
this.label8.Name = "label8";
- this.label8.Size = new System.Drawing.Size(66, 13);
+ this.label8.Size = new System.Drawing.Size(69, 13);
this.label8.TabIndex = 22;
this.label8.Text = "Service DLL:";
//
@@ -188,11 +187,11 @@ private void InitializeComponent()
//
// textPassword
//
- this.textPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textPassword.Location = new System.Drawing.Point(107, 196);
this.textPassword.Name = "textPassword";
- this.textPassword.Size = new System.Drawing.Size(251, 22);
+ this.textPassword.Size = new System.Drawing.Size(251, 20);
this.textPassword.TabIndex = 20;
this.textPassword.Text = "password";
this.textPassword.UseSystemPasswordChar = true;
@@ -203,7 +202,7 @@ private void InitializeComponent()
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(6, 199);
this.label7.Name = "label7";
- this.label7.Size = new System.Drawing.Size(59, 13);
+ this.label7.Size = new System.Drawing.Size(56, 13);
this.label7.TabIndex = 19;
this.label7.Text = "Password:";
//
@@ -233,17 +232,16 @@ private void InitializeComponent()
//
// textDescription
//
- this.textDescription.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textDescription.BackColor = System.Drawing.Color.WhiteSmoke;
- this.textDescription.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
- this.textDescription.Location = new System.Drawing.Point(6, 21);
+ this.textDescription.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textDescription.BorderStyle = System.Windows.Forms.BorderStyle.None;
+ this.textDescription.Location = new System.Drawing.Point(6, 47);
this.textDescription.Multiline = true;
this.textDescription.Name = "textDescription";
this.textDescription.ReadOnly = true;
this.textDescription.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
- this.textDescription.Size = new System.Drawing.Size(375, 64);
+ this.textDescription.Size = new System.Drawing.Size(375, 38);
this.textDescription.TabIndex = 17;
//
// buttonStart
@@ -272,11 +270,11 @@ private void InitializeComponent()
//
// textLoadOrderGroup
//
- this.textLoadOrderGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textLoadOrderGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textLoadOrderGroup.Location = new System.Drawing.Point(240, 118);
this.textLoadOrderGroup.Name = "textLoadOrderGroup";
- this.textLoadOrderGroup.Size = new System.Drawing.Size(141, 22);
+ this.textLoadOrderGroup.Size = new System.Drawing.Size(141, 20);
this.textLoadOrderGroup.TabIndex = 15;
//
// comboErrorControl
@@ -311,7 +309,7 @@ private void InitializeComponent()
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(195, 94);
this.label6.Name = "label6";
- this.label6.Size = new System.Drawing.Size(60, 13);
+ this.label6.Size = new System.Drawing.Size(59, 13);
this.label6.TabIndex = 11;
this.label6.Text = "Start Type:";
//
@@ -320,7 +318,7 @@ private void InitializeComponent()
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(6, 121);
this.label5.Name = "label5";
- this.label5.Size = new System.Drawing.Size(77, 13);
+ this.label5.Size = new System.Drawing.Size(68, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Error Control:";
//
@@ -329,7 +327,7 @@ private void InitializeComponent()
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 94);
this.label4.Name = "label4";
- this.label4.Size = new System.Drawing.Size(33, 13);
+ this.label4.Size = new System.Drawing.Size(34, 13);
this.label4.TabIndex = 9;
this.label4.Text = "Type:";
//
@@ -338,7 +336,7 @@ private void InitializeComponent()
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(195, 121);
this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(43, 13);
+ this.label3.Size = new System.Drawing.Size(39, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Group:";
//
@@ -359,17 +357,17 @@ private void InitializeComponent()
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 147);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(68, 13);
+ this.label2.Size = new System.Drawing.Size(64, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Binary Path:";
//
// textUserAccount
//
- this.textUserAccount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textUserAccount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textUserAccount.Location = new System.Drawing.Point(107, 170);
this.textUserAccount.Name = "textUserAccount";
- this.textUserAccount.Size = new System.Drawing.Size(274, 22);
+ this.textUserAccount.Size = new System.Drawing.Size(274, 20);
this.textUserAccount.TabIndex = 4;
//
// label1
@@ -377,34 +375,33 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 173);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(78, 13);
+ this.label1.Size = new System.Drawing.Size(75, 13);
this.label1.TabIndex = 3;
this.label1.Text = "User Account:";
//
// textServiceBinaryPath
//
- this.textServiceBinaryPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textServiceBinaryPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textServiceBinaryPath.Location = new System.Drawing.Point(107, 144);
this.textServiceBinaryPath.Name = "textServiceBinaryPath";
- this.textServiceBinaryPath.Size = new System.Drawing.Size(274, 22);
+ this.textServiceBinaryPath.Size = new System.Drawing.Size(274, 20);
this.textServiceBinaryPath.TabIndex = 2;
//
// labelServiceDisplayName
//
- this.labelServiceDisplayName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
- this.labelServiceDisplayName.Location = new System.Drawing.Point(198, 5);
+ this.labelServiceDisplayName.AutoSize = true;
+ this.labelServiceDisplayName.Location = new System.Drawing.Point(6, 26);
this.labelServiceDisplayName.Name = "labelServiceDisplayName";
- this.labelServiceDisplayName.Size = new System.Drawing.Size(183, 13);
+ this.labelServiceDisplayName.Size = new System.Drawing.Size(111, 13);
this.labelServiceDisplayName.TabIndex = 1;
this.labelServiceDisplayName.Text = "Service Display Name";
- this.labelServiceDisplayName.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// labelServiceName
//
this.labelServiceName.AutoSize = true;
this.labelServiceName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.labelServiceName.Location = new System.Drawing.Point(6, 4);
+ this.labelServiceName.Location = new System.Drawing.Point(6, 5);
this.labelServiceName.Name = "labelServiceName";
this.labelServiceName.Size = new System.Drawing.Size(86, 13);
this.labelServiceName.TabIndex = 0;
@@ -414,7 +411,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listServices);
this.Controls.Add(this.panelService);
this.Name = "ServiceProperties";
@@ -427,7 +423,7 @@ private void InitializeComponent()
#endregion
- private ExtendedListView listServices;
+ private System.Windows.Forms.ListView listServices;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ColumnHeader columnDescription;
private System.Windows.Forms.ColumnHeader columnStatus;
diff --git a/1.x/trunk/ProcessHacker/Components/ServiceProperties.cs b/1.x/trunk/ProcessHacker/Components/ServiceProperties.cs
index bf15a7173..f24df402f 100644
--- a/1.x/trunk/ProcessHacker/Components/ServiceProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/ServiceProperties.cs
@@ -39,7 +39,7 @@ namespace ProcessHacker.Components
public partial class ServiceProperties : UserControl
{
private QueryServiceConfig _oldConfig;
- private readonly ServiceProvider _provider;
+ private ServiceProvider _provider;
public event EventHandler NeedsClose;
@@ -52,6 +52,7 @@ public ServiceProperties(string[] services)
InitializeComponent();
listServices.ListViewItemSorter = new SortedListViewComparer(listServices);
+ listServices.SetTheme("explorer");
ColumnSettings.LoadSettings(Settings.Instance.ServiceMiniListColumns, listServices);
PID = -1;
@@ -73,12 +74,12 @@ public ServiceProperties(string[] services)
_provider.Dictionary[s].Status.ServiceStatusProcess.CurrentState.ToString() })).Name = s;
}
- _provider.DictionaryModified += this._provider_DictionaryModified;
- _provider.DictionaryRemoved += this._provider_DictionaryRemoved;
+ _provider.DictionaryModified += new ServiceProvider.ProviderDictionaryModified(_provider_DictionaryModified);
+ _provider.DictionaryRemoved += new ServiceProvider.ProviderDictionaryRemoved(_provider_DictionaryRemoved);
- this.comboErrorControl.Fill(typeof(ServiceErrorControl));
- this.comboStartType.Fill(typeof(ServiceStartType));
- this.comboType.Fill(typeof(ProcessHacker.Native.Api.ServiceType));
+ Utils.Fill(comboErrorControl, typeof(ServiceErrorControl));
+ Utils.Fill(comboStartType, typeof(ServiceStartType));
+ Utils.Fill(comboType, typeof(ProcessHacker.Native.Api.ServiceType));
comboType.Items.Add("Win32OwnProcess, InteractiveProcess");
comboType.Items.Add("Win32ShareProcess, InteractiveProcess");
@@ -94,7 +95,7 @@ public ServiceProperties(string[] services)
public int PID { get; set; }
- public ExtendedListView List
+ public ListView List
{
get { return listServices; }
}
@@ -126,11 +127,11 @@ private void Close()
private void _provider_DictionaryRemoved(ServiceItem item)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- // remove the item from the list if it's there
- if (listServices.Items.ContainsKey(item.Status.ServiceName))
- listServices.Items[item.Status.ServiceName].Remove();
- }));
+ {
+ // remove the item from the list if it's there
+ if (listServices.Items.ContainsKey(item.Status.ServiceName))
+ listServices.Items[item.Status.ServiceName].Remove();
+ }));
}
private void _provider_DictionaryModified(ServiceItem oldItem, ServiceItem newItem)
@@ -139,46 +140,40 @@ private void _provider_DictionaryModified(ServiceItem oldItem, ServiceItem newIt
return;
this.BeginInvoke(new MethodInvoker(() =>
- {
- // update the state of the service
- if (listServices.Items.ContainsKey(newItem.Status.ServiceName))
- listServices.Items[newItem.Status.ServiceName].SubItems[2].Text =
- newItem.Status.ServiceStatusProcess.CurrentState.ToString();
-
- // update the start and stop buttons if we have a service selected
- if (listServices.SelectedItems.Count == 1)
{
- if (listServices.SelectedItems[0].Name == newItem.Status.ServiceName)
- {
- buttonStart.Enabled = false;
- buttonStop.Enabled = false;
+ // update the state of the service
+ if (listServices.Items.ContainsKey(newItem.Status.ServiceName))
+ listServices.Items[newItem.Status.ServiceName].SubItems[2].Text =
+ newItem.Status.ServiceStatusProcess.CurrentState.ToString();
- switch (newItem.Status.ServiceStatusProcess.CurrentState)
+ // update the start and stop buttons if we have a service selected
+ if (listServices.SelectedItems.Count == 1)
+ {
+ if (listServices.SelectedItems[0].Name == newItem.Status.ServiceName)
{
- case ServiceState.Running:
- this.buttonStop.Enabled = true;
- break;
- case ServiceState.Stopped:
- this.buttonStart.Enabled = true;
- break;
+ buttonStart.Enabled = false;
+ buttonStop.Enabled = false;
+
+ if (newItem.Status.ServiceStatusProcess.CurrentState == ServiceState.Running)
+ buttonStop.Enabled = true;
+ else if (newItem.Status.ServiceStatusProcess.CurrentState == ServiceState.Stopped)
+ buttonStart.Enabled = true;
}
}
- }
- // if the service was just started in this process, add it to the list
- if (newItem.Status.ServiceStatusProcess.ProcessID == this.PID && oldItem.Status.ServiceStatusProcess.ProcessID == 0)
- {
- if (!listServices.Items.ContainsKey(newItem.Status.ServiceName))
+ // if the service was just started in this process, add it to the list
+ if (newItem.Status.ServiceStatusProcess.ProcessID == this.PID && oldItem.Status.ServiceStatusProcess.ProcessID == 0)
{
- listServices.Items.Add(new ListViewItem(new string[]
+ if (!listServices.Items.ContainsKey(newItem.Status.ServiceName))
{
- newItem.Status.ServiceName,
- newItem.Status.DisplayName,
- newItem.Status.ServiceStatusProcess.CurrentState.ToString()
- })).Name = newItem.Status.ServiceName;
+ listServices.Items.Add(new ListViewItem(new string[] {
+ newItem.Status.ServiceName,
+ newItem.Status.DisplayName,
+ newItem.Status.ServiceStatusProcess.CurrentState.ToString()
+ })).Name = newItem.Status.ServiceName;
+ }
}
- }
- }));
+ }));
}
private void listServices_SelectedIndexChanged(object sender, EventArgs e)
@@ -270,10 +265,10 @@ private void UpdateInformation()
}
catch
{
- textDescription.Text = string.Empty;
+ textDescription.Text = "";
}
- textServiceDll.Text = string.Empty;
+ textServiceDll.Text = "";
if (item.Config.ServiceType == ProcessHacker.Native.Api.ServiceType.Win32ShareProcess)
{
@@ -315,17 +310,17 @@ private void UpdateInformation()
private void ClearControls()
{
- labelServiceName.Text = string.Empty;
- labelServiceDisplayName.Text = string.Empty;
- comboType.Text = string.Empty;
- comboStartType.Text = string.Empty;
- comboErrorControl.Text = string.Empty;
- textServiceBinaryPath.Text = string.Empty;
- textUserAccount.Text = string.Empty;
+ labelServiceName.Text = "";
+ labelServiceDisplayName.Text = "";
+ comboType.Text = "";
+ comboStartType.Text = "";
+ comboErrorControl.Text = "";
+ textServiceBinaryPath.Text = "";
+ textUserAccount.Text = "";
textPassword.Text = "password";
- textLoadOrderGroup.Text = string.Empty;
- textDescription.Text = string.Empty;
- textServiceDll.Text = string.Empty;
+ textLoadOrderGroup.Text = "";
+ textDescription.Text = "";
+ textServiceDll.Text = "";
}
private void buttonApply_Click(object sender, EventArgs e)
@@ -430,7 +425,8 @@ private void buttonDependents_Click(object sender, EventArgs e)
{
try
{
- using (ServiceController controller = new ServiceController(listServices.SelectedItems[0].Name))
+ using (ServiceController controller = new ServiceController(
+ listServices.SelectedItems[0].Name))
{
List dependents = new List();
@@ -452,7 +448,8 @@ private void buttonDependencies_Click(object sender, EventArgs e)
{
try
{
- using (ServiceController controller = new ServiceController(listServices.SelectedItems[0].Name))
+ using (ServiceController controller = new ServiceController(
+ listServices.SelectedItems[0].Name))
{
List dependencies = new List();
@@ -482,7 +479,7 @@ private void buttonPermissions_Click(object sender, EventArgs e)
SecurityEditor.EditSecurity(
this,
SecurityEditor.GetSecurableWrapper(
- access => new ServiceHandle(listServices.SelectedItems[0].Name, (ServiceAccess)access)
+ (access) => new ServiceHandle(listServices.SelectedItems[0].Name, (ServiceAccess)access)
),
listServices.SelectedItems[0].Name,
NativeTypeFactory.GetAccessEntries(NativeTypeFactory.ObjectType.Service)
diff --git a/1.x/trunk/ProcessHacker/Components/ServiceProperties.resx b/1.x/trunk/ProcessHacker/Components/ServiceProperties.resx
index 026c576b4..a5979aadf 100644
--- a/1.x/trunk/ProcessHacker/Components/ServiceProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/ServiceProperties.resx
@@ -112,12 +112,12 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/SplitButton.cs b/1.x/trunk/ProcessHacker/Components/SplitButton.cs
index 46c331906..49f3c78ca 100644
--- a/1.x/trunk/ProcessHacker/Components/SplitButton.cs
+++ b/1.x/trunk/ProcessHacker/Components/SplitButton.cs
@@ -20,18 +20,22 @@
namespace wyDay.Controls
{
- public sealed class SplitButton : Button
+ public class SplitButton : Button
{
private PushButtonState _state;
private const int SplitSectionWidth = 18;
- private static readonly int BorderSize = SystemInformation.Border3DSize.Width * 2;
- private bool skipNextOpen;
- private Rectangle dropDownRectangle;
- private bool showSplit;
- private bool isSplitMenuVisible;
- private ContextMenuStrip m_SplitMenuStrip;
+ private static int BorderSize = SystemInformation.Border3DSize.Width * 2;
+ private bool skipNextOpen = false;
+ private Rectangle dropDownRectangle = new Rectangle();
+ private bool showSplit = false;
+
+ private bool isSplitMenuVisible = false;
+
+
+ private ContextMenuStrip m_SplitMenuStrip = null;
+ private ContextMenu m_SplitMenu = null;
TextFormatFlags textFormatFlags = TextFormatFlags.Default;
@@ -55,6 +59,31 @@ public override ContextMenuStrip ContextMenuStrip
}
}
+ [DefaultValue(null)]
+ public ContextMenu SplitMenu
+ {
+ get { return m_SplitMenu; }
+ set
+ {
+ //remove the event handlers for the old SplitMenu
+ if (m_SplitMenu != null)
+ {
+ m_SplitMenu.Popup -= new EventHandler(SplitMenu_Popup);
+ }
+
+ //add the event handlers for the new SplitMenu
+ if (value != null)
+ {
+ ShowSplit = true;
+ value.Popup += new EventHandler(SplitMenu_Popup);
+ }
+ else
+ ShowSplit = false;
+
+ m_SplitMenu = value;
+ }
+ }
+
[DefaultValue(null)]
public ContextMenuStrip SplitMenuStrip
{
@@ -67,16 +96,16 @@ public ContextMenuStrip SplitMenuStrip
//remove the event handlers for the old SplitMenuStrip
if (m_SplitMenuStrip != null)
{
- m_SplitMenuStrip.Closing -= this.SplitMenuStrip_Closing;
- m_SplitMenuStrip.Opening -= this.SplitMenuStrip_Opening;
+ m_SplitMenuStrip.Closing -= new ToolStripDropDownClosingEventHandler(SplitMenuStrip_Closing);
+ m_SplitMenuStrip.Opening -= new CancelEventHandler(SplitMenuStrip_Opening);
}
//add the event handlers for the new SplitMenuStrip
if (value != null)
{
ShowSplit = true;
- value.Closing += this.SplitMenuStrip_Closing;
- value.Opening += this.SplitMenuStrip_Opening;
+ value.Closing += new ToolStripDropDownClosingEventHandler(SplitMenuStrip_Closing);
+ value.Opening += new CancelEventHandler(SplitMenuStrip_Opening);
}
else
ShowSplit = false;
@@ -262,7 +291,7 @@ protected override void OnMouseDown(MouseEventArgs e)
}
//handle ContextMenu re-clicking the drop-down region to close the menu
- if (m_SplitMenuStrip != null && e.Button == MouseButtons.Left && !isMouseEntered)
+ if (m_SplitMenu != null && e.Button == MouseButtons.Left && !isMouseEntered)
skipNextOpen = true;
if (dropDownRectangle.Contains(e.Location) && !isSplitMenuVisible && e.Button == MouseButtons.Left)
@@ -288,7 +317,7 @@ protected override void OnMouseUp(MouseEventArgs mevent)
{
ShowContextMenuStrip();
}
- else if (m_SplitMenuStrip == null && m_SplitMenuStrip == null || !isSplitMenuVisible)
+ else if (m_SplitMenuStrip == null && m_SplitMenu == null || !isSplitMenuVisible)
{
SetButtonDrawState();
@@ -429,8 +458,7 @@ public override Size GetPreferredSize(Size proposedSize)
{
if (AutoSize)
return CalculateButtonAutoSize();
-
- if (!string.IsNullOrEmpty(this.Text) && TextRenderer.MeasureText(this.Text, this.Font).Width + SplitSectionWidth > preferredSize.Width)
+ else if (!string.IsNullOrEmpty(Text) && TextRenderer.MeasureText(Text, Font).Width + SplitSectionWidth > preferredSize.Width)
return preferredSize + new Size(SplitSectionWidth + BorderSize * 2, 0);
}
@@ -607,9 +635,9 @@ private void LayoutTextBeforeOrAfterImage(Rectangle totalArea, bool textFirst, S
else if (h_image == HorizontalAlignment.Right && h_text == HorizontalAlignment.Right)
offset = excess_width;
else if (h_image == HorizontalAlignment.Center && (h_text == HorizontalAlignment.Left || h_text == HorizontalAlignment.Center))
- offset += excess_width / 3;
+ offset += (int)(excess_width / 3);
else
- offset += 2 * (excess_width / 3);
+ offset += (int)(2 * (excess_width / 3));
if (textFirst)
{
@@ -658,9 +686,9 @@ private void LayoutTextAboveOrBelowImage(Rectangle totalArea, bool textFirst, Si
else if (v_image == VerticalAlignment.Bottom && v_text == VerticalAlignment.Bottom)
offset = excess_height;
else if (v_image == VerticalAlignment.Center && (v_text == VerticalAlignment.Top || v_text == VerticalAlignment.Center))
- offset += excess_height / 3;
+ offset += (int)(excess_height / 3);
else
- offset += 2 * (excess_height / 3);
+ offset += (int)(2 * (excess_height / 3));
if (textFirst)
{
@@ -758,7 +786,11 @@ private void ShowContextMenuStrip()
State = PushButtonState.Pressed;
- if (m_SplitMenuStrip != null)
+ if (m_SplitMenu != null)
+ {
+ m_SplitMenu.Show(this, new Point(0, Height));
+ }
+ else if (m_SplitMenuStrip != null)
{
m_SplitMenuStrip.Show(this, new Point(0, Height), ToolStripDropDownDirection.BelowRight);
}
diff --git a/1.x/trunk/ProcessHacker/Components/StructViewer.Designer.cs b/1.x/trunk/ProcessHacker/Components/StructViewer.Designer.cs
index 2076588ad..f9c95d1bc 100644
--- a/1.x/trunk/ProcessHacker/Components/StructViewer.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/StructViewer.Designer.cs
@@ -28,6 +28,7 @@ protected override void Dispose(bool disposing)
///
private void InitializeComponent()
{
+ this.components = new System.ComponentModel.Container();
this.treeStruct = new Aga.Controls.Tree.TreeViewAdv();
this.columnName = new Aga.Controls.Tree.TreeColumn();
this.columnValue = new Aga.Controls.Tree.TreeColumn();
@@ -38,6 +39,8 @@ private void InitializeComponent()
this.decMenuItem = new System.Windows.Forms.MenuItem();
this.hexMenuItem = new System.Windows.Forms.MenuItem();
this.copyMenuItem = new System.Windows.Forms.MenuItem();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
// treeStruct
@@ -47,6 +50,9 @@ private void InitializeComponent()
this.treeStruct.Columns.Add(this.columnValue);
this.treeStruct.DefaultToolTipProvider = null;
this.treeStruct.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.treeStruct.DragDropMarkColor = System.Drawing.Color.Black;
+ this.treeStruct.FullRowSelect = true;
+ this.treeStruct.GridLineStyle = Aga.Controls.Tree.GridLineStyle.Horizontal;
this.treeStruct.LineColor = System.Drawing.SystemColors.ControlDark;
this.treeStruct.Location = new System.Drawing.Point(0, 0);
this.treeStruct.Model = null;
@@ -58,6 +64,7 @@ private void InitializeComponent()
this.treeStruct.ShowNodeToolTips = true;
this.treeStruct.Size = new System.Drawing.Size(362, 331);
this.treeStruct.TabIndex = 0;
+ this.treeStruct.UseColumns = true;
//
// columnName
//
@@ -120,17 +127,22 @@ private void InitializeComponent()
//
// copyMenuItem
//
+ this.vistaMenu.SetImage(this.copyMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyMenuItem.Index = 1;
this.copyMenuItem.Text = "&Copy";
//
+ // vistaMenu
+ //
+ this.vistaMenu.ContainerControl = this;
+ //
// StructViewer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.treeStruct);
this.Name = "StructViewer";
this.Size = new System.Drawing.Size(362, 331);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
}
@@ -147,5 +159,6 @@ private void InitializeComponent()
private System.Windows.Forms.MenuItem decMenuItem;
private System.Windows.Forms.MenuItem hexMenuItem;
private System.Windows.Forms.MenuItem copyMenuItem;
+ private wyDay.Controls.VistaMenu vistaMenu;
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/StructViewer.cs b/1.x/trunk/ProcessHacker/Components/StructViewer.cs
index b83c7d689..06a7ccc54 100644
--- a/1.x/trunk/ProcessHacker/Components/StructViewer.cs
+++ b/1.x/trunk/ProcessHacker/Components/StructViewer.cs
@@ -32,13 +32,17 @@ namespace ProcessHacker.Components
{
public partial class StructViewer : UserControl
{
- private readonly StructModel _model = new StructModel();
- readonly StructDef _struct;
+ private StructModel _model = new StructModel();
+ int _pid;
+ IntPtr _address;
+ StructDef _struct;
public StructViewer(int pid, IntPtr address, StructDef struc)
{
InitializeComponent();
+ _pid = pid;
+ _address = address;
_struct = struc;
treeStruct.Model = _model;
treeStruct.ContextMenu = menuStruct;
@@ -54,12 +58,8 @@ public StructViewer(int pid, IntPtr address, StructDef struc)
_struct.Structs = Program.Structs;
values = _struct.Read();
- _model.Nodes.Add(new StructNode(new FieldValue
- {
- Name = "Struct",
- FieldType = FieldType.StringUTF16,
- Value = string.Empty
- }));
+ _model.Nodes.Add(new StructNode(new FieldValue()
+ { Name = "Struct", FieldType = FieldType.StringUTF16, Value = "" }));
foreach (FieldValue val in values)
this.AddNode(_model.Nodes[0], val);
@@ -158,7 +158,8 @@ public string Value
if (_value.StructName != null)
return _value.StructName + "[" + memberCount.ToString() + "]";
- return type.ToString() + "[" + memberCount.ToString() + "]";
+ else
+ return type.ToString() + "[" + memberCount.ToString() + "]";
}
if (_value.StructName != null)
diff --git a/1.x/trunk/ProcessHacker/Components/StructViewer.resx b/1.x/trunk/ProcessHacker/Components/StructViewer.resx
index 50dae8683..62e3a554d 100644
--- a/1.x/trunk/ProcessHacker/Components/StructViewer.resx
+++ b/1.x/trunk/ProcessHacker/Components/StructViewer.resx
@@ -112,12 +112,18 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
+
+ 132, 17
+
+
+ 132, 17
+
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/TargetWindowButton.cs b/1.x/trunk/ProcessHacker/Components/TargetWindowButton.cs
index 2bc1a00a5..1c5723060 100644
--- a/1.x/trunk/ProcessHacker/Components/TargetWindowButton.cs
+++ b/1.x/trunk/ProcessHacker/Components/TargetWindowButton.cs
@@ -28,14 +28,14 @@ namespace ProcessHacker.Components
{
public delegate void TargetWindowFoundDelegate(int pid, int tid);
- public sealed class TargetWindowButton : ToolStripButton
+ public class TargetWindowButton : ToolStripButton
{
public event TargetWindowFoundDelegate TargetWindowFound;
private Control _parent;
- private readonly Control _dummy;
+ private Control _dummy;
private IntPtr _currentHWnd;
- private bool _targeting;
+ private bool _targeting = false;
public TargetWindowButton()
{
@@ -93,7 +93,12 @@ private void DrawWindowRectangle(IntPtr hWnd)
}
}
- private void RedrawWindow(IntPtr hWnd, bool workaround = true)
+ private void RedrawWindow(IntPtr hWnd)
+ {
+ this.RedrawWindow(hWnd, true);
+ }
+
+ private void RedrawWindow(IntPtr hWnd, bool workaround)
{
if (!Win32.RedrawWindow(
hWnd,
@@ -150,10 +155,11 @@ void dummy_MouseMove(object sender, MouseEventArgs e)
if (oldHWnd != IntPtr.Zero)
this.RedrawWindow(oldHWnd);
- int pid;
+ bool isPhWindow = false;
+ int pid, tid;
- Win32.GetWindowThreadProcessId(this._currentHWnd, out pid);
- bool isPhWindow = pid == Program.CurrentProcessId;
+ tid = Win32.GetWindowThreadProcessId(_currentHWnd, out pid);
+ isPhWindow = pid == Program.CurrentProcessId;
// Draw a rectangle over the current window.
if (
@@ -174,9 +180,9 @@ void dummy_MouseUp(object sender, MouseEventArgs e)
// Redraw the window we found.
this.RedrawWindow(_currentHWnd, false);
- int pid;
+ int pid, tid;
- int tid = Win32.GetWindowThreadProcessId(this._currentHWnd, out pid);
+ tid = Win32.GetWindowThreadProcessId(_currentHWnd, out pid);
if (this.TargetWindowFound != null)
this.TargetWindowFound(pid, tid);
diff --git a/1.x/trunk/ProcessHacker/Components/TaskDialog/ActiveTaskDialog.cs b/1.x/trunk/ProcessHacker/Components/TaskDialog/ActiveTaskDialog.cs
index 87581f86e..aaa4f1007 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskDialog/ActiveTaskDialog.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskDialog/ActiveTaskDialog.cs
@@ -11,6 +11,8 @@ namespace ProcessHacker.Components
using System;
using System.Drawing;
using System.Windows.Forms;
+ using System.Runtime.InteropServices;
+ using System.Diagnostics.CodeAnalysis;
///
/// The active Task Dialog window. Provides several methods for acting on the active TaskDialog.
@@ -22,7 +24,7 @@ public class ActiveTaskDialog : IWin32Window
///
/// The Task Dialog's window handle.
///
- private readonly IntPtr handle;
+ private IntPtr handle;
///
/// Creates a ActiveTaskDialog.
@@ -125,7 +127,7 @@ public bool SetProgressBarRange(Int16 minRange, Int16 maxRange)
// TDM_SET_PROGRESS_BAR_RANGE = WM_USER+105, // lParam = MAKELPARAM(nMinRange, nMaxRange)
// #define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h))
// #define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
- IntPtr lparam = (IntPtr)((minRange & 0xffff) | ((maxRange & 0xffff) << 16));
+ IntPtr lparam = (IntPtr)((((Int32)minRange) & 0xffff) | ((((Int32)maxRange) & 0xffff) << 16));
return UnsafeNativeMethods.SendMessage(
this.handle,
(uint)UnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_RANGE,
@@ -365,7 +367,7 @@ public void SetButtonElevationRequiredState(int buttonId, bool elevationRequired
this.handle,
(uint)UnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE,
(IntPtr)buttonId,
- elevationRequired ? new IntPtr(1) : IntPtr.Zero);
+ (IntPtr)(elevationRequired ? new IntPtr(1) : IntPtr.Zero));
}
///
diff --git a/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialog.cs b/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialog.cs
index 8ecc00828..f71864eae 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialog.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialog.cs
@@ -13,7 +13,6 @@ namespace ProcessHacker.Components
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
- using ProcessHacker.Native;
///
/// The signature of the callback that recieves notificaitons from the Task Dialog.
@@ -267,8 +266,6 @@ public enum ProgressBarState
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
public struct TaskDialogButton
{
- public static readonly int SizeOf;
-
///
/// The ID of the button. This value is returned by TaskDialog.Show when the button is clicked.
///
@@ -309,11 +306,6 @@ public string ButtonText
get { return this.buttonText; }
set { this.buttonText = value; }
}
-
- static TaskDialogButton()
- {
- SizeOf = Marshal.SizeOf(typeof(TaskDialogButton));
- }
}
///
@@ -1008,12 +1000,12 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
{
verificationFlagChecked = false;
radioButtonResult = 0;
- int result;
+ int result = 0;
UnsafeNativeMethods.TASKDIALOGCONFIG config = new UnsafeNativeMethods.TASKDIALOGCONFIG();
try
{
- config.cbSize = (uint)UnsafeNativeMethods.TASKDIALOGCONFIG.SizeOf;
+ config.cbSize = (uint)Marshal.SizeOf(typeof(UnsafeNativeMethods.TASKDIALOGCONFIG));
config.hwndParent = hwndOwner;
config.dwFlags = this.flags;
config.dwCommonButtons = this.commonButtons;
@@ -1044,8 +1036,8 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
if (customButtons.Length > 0)
{
// Hand marshal the buttons array.
- int elementSize = TaskDialogButton.SizeOf;
- config.pButtons = MemoryAlloc.PrivateHeap.Allocate(elementSize * customButtons.Length);
+ int elementSize = Marshal.SizeOf(typeof(TaskDialogButton));
+ config.pButtons = Marshal.AllocHGlobal(elementSize * (int)customButtons.Length);
for (int i = 0; i < customButtons.Length; i++)
{
unsafe // Unsafe because of pointer arithmatic.
@@ -1062,8 +1054,8 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
if (customRadioButtons.Length > 0)
{
// Hand marshal the buttons array.
- int elementSize = TaskDialogButton.SizeOf;
- config.pRadioButtons = MemoryAlloc.PrivateHeap.Allocate(elementSize * customRadioButtons.Length);
+ int elementSize = Marshal.SizeOf(typeof(TaskDialogButton));
+ config.pRadioButtons = Marshal.AllocHGlobal(elementSize * (int)customRadioButtons.Length);
for (int i = 0; i < customRadioButtons.Length; i++)
{
unsafe // Unsafe because of pointer arithmatic.
@@ -1115,7 +1107,7 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
// translate to the friendly version.
if (this.callback != null)
{
- config.pfCallback = this.PrivateCallback;
+ config.pfCallback = new UnsafeNativeMethods.TaskDialogCallback(this.PrivateCallback);
}
////config.lpCallbackData = this.callbackData; // How do you do this? Need to pin the ref?
@@ -1132,7 +1124,7 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
// that are not required for the users of this class.
if (config.pButtons != IntPtr.Zero)
{
- int elementSize = TaskDialogButton.SizeOf;
+ int elementSize = Marshal.SizeOf(typeof(TaskDialogButton));
for (int i = 0; i < config.cButtons; i++)
{
unsafe
@@ -1142,12 +1134,12 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
}
}
- MemoryAlloc.PrivateHeap.Free(config.pButtons);
+ Marshal.FreeHGlobal(config.pButtons);
}
if (config.pRadioButtons != IntPtr.Zero)
{
- int elementSize = TaskDialogButton.SizeOf;
+ int elementSize = Marshal.SizeOf(typeof(TaskDialogButton));
for (int i = 0; i < config.cRadioButtons; i++)
{
unsafe
@@ -1157,7 +1149,7 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
}
}
- MemoryAlloc.PrivateHeap.Free(config.pRadioButtons);
+ Marshal.FreeHGlobal(config.pRadioButtons);
}
}
@@ -1173,20 +1165,17 @@ private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out
/// Specifies additional noitification information. The contents of this parameter depends on the value of the msg parameter.
/// Specifies the application-defined value given in the call to TaskDialogIndirect.
/// A HRESULT. It's not clear in the spec what a failed result will do.
- private int PrivateCallback([In] IntPtr hwnd, [In] TaskDialogNotification msg, [In] UIntPtr wparam, [In] IntPtr lparam, [In] IntPtr refData)
+ private int PrivateCallback([In] IntPtr hwnd, [In] uint msg, [In] UIntPtr wparam, [In] IntPtr lparam, [In] IntPtr refData)
{
- TaskDialogCallback cb = this.callback;
- if (cb != null)
+ TaskDialogCallback callback = this.callback;
+ if (callback != null)
{
// Prepare arguments for the callback to the user we are insulating from Interop casting sillyness.
// Future: Consider reusing a single ActiveTaskDialog object and mark it as destroyed on the destry notification.
ActiveTaskDialog activeDialog = new ActiveTaskDialog(hwnd);
- TaskDialogNotificationArgs args = new TaskDialogNotificationArgs
- {
- Notification = msg
- };
-
+ TaskDialogNotificationArgs args = new TaskDialogNotificationArgs();
+ args.Notification = (TaskDialogNotification)msg;
switch (args.Notification)
{
case TaskDialogNotification.ButtonClicked:
@@ -1207,7 +1196,7 @@ private int PrivateCallback([In] IntPtr hwnd, [In] TaskDialogNotification msg, [
break;
}
- return (cb(activeDialog, args, this.callbackData) ? 1 : 0);
+ return (callback(activeDialog, args, this.callbackData) ? 1 : 0);
}
return 0; // false;
diff --git a/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialogCommonDialog.cs b/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialogCommonDialog.cs
index a8700a423..e401e5d2b 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialogCommonDialog.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskDialog/TaskDialogCommonDialog.cs
@@ -22,7 +22,7 @@ public class TaskDialogCommonDialog : CommonDialog
///
/// The TaskDialog we will display.
///
- private readonly TaskDialog taskDialog;
+ private TaskDialog taskDialog;
///
/// The result of the dialog, either a DialogResult value for common push buttons set in the TaskDialog.CommonButtons
diff --git a/1.x/trunk/ProcessHacker/Components/TaskDialog/UnsafeNativeMethods.cs b/1.x/trunk/ProcessHacker/Components/TaskDialog/UnsafeNativeMethods.cs
index 075d50565..3f2273ede 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskDialog/UnsafeNativeMethods.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskDialog/UnsafeNativeMethods.cs
@@ -9,13 +9,14 @@
namespace ProcessHacker.Components
{
using System;
+ using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
///
/// Class to hold native code interop declarations.
///
[System.Security.SuppressUnmanagedCodeSecurity]
- internal static class UnsafeNativeMethods
+ internal static partial class UnsafeNativeMethods
{
///
/// WM_USER taken from WinUser.h
@@ -31,7 +32,7 @@ internal static class UnsafeNativeMethods
/// wParam which is interpreted differently depending on the message.
/// The refrence data that was set to TaskDialog.CallbackData.
/// A HRESULT value. The return value is specific to the message being processed.
- internal delegate int TaskDialogCallback([In] IntPtr hwnd, [In] TaskDialogNotification msg, [In] UIntPtr wParam, [In] IntPtr lParam, [In] IntPtr refData);
+ internal delegate int TaskDialogCallback([In] IntPtr hwnd, [In] uint msg, [In] UIntPtr wParam, [In] IntPtr lParam, [In] IntPtr refData);
///
/// TASKDIALOG_FLAGS taken from CommCtrl.h.
@@ -312,8 +313,6 @@ internal static extern void TaskDialogIndirect(
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
internal struct TASKDIALOGCONFIG
{
- public static readonly int SizeOf;
-
///
/// Size of the structure in bytes.
///
@@ -441,12 +440,7 @@ internal struct TASKDIALOGCONFIG
/// Width of the Task Dialog's client area in DLU's.
/// If 0, Task Dialog will calculate the ideal width.
///
- public uint cxWidth;
-
- static TASKDIALOGCONFIG()
- {
- SizeOf = Marshal.SizeOf(typeof(TASKDIALOGCONFIG));
- }
+ public uint cxWidth;
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/COMTypes.cs b/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/COMTypes.cs
index d0c262547..3d938138b 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/COMTypes.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/COMTypes.cs
@@ -24,38 +24,39 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
+using System.Runtime.CompilerServices;
using ProcessHacker.Native.Api;
namespace TaskbarLib.Interop
{
#region "Interface Classes"
- [ComImportAttribute]
+ [ComImportAttribute()]
[GuidAttribute("86C14003-4D6B-4EF3-A7B4-0506663B2E68")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
internal class CApplicationDestinations { }
- [ComImportAttribute]
+ [ComImportAttribute()]
[GuidAttribute("86BEC222-30F2-47E0-9F25-60D11CD75C28")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
internal class CApplicationDocumentLists { }
- [ComImportAttribute]
+ [ComImportAttribute()]
[GuidAttribute("56FDF344-FD6D-11d0-958A-006097C9A090")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
internal class CTaskbarList { }
- [ComImportAttribute]
+ [ComImportAttribute()]
[GuidAttribute("00021401-0000-0000-C000-000000000046")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
internal class CShellLink { }
- [ComImportAttribute]
+ [ComImportAttribute()]
[GuidAttribute("77F10CF0-3DB5-4966-B520-B7C54FD35ED6")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
internal class CDestinationList { }
- [ComImportAttribute]
+ [ComImportAttribute()]
[GuidAttribute("2D3468C1-36A7-43B6-AC24-D3F02FD9607A")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
internal class CEnumerableObjectCollection { }
@@ -64,7 +65,7 @@ internal class CEnumerableObjectCollection { }
#region "Interfaces"
- [ComImportAttribute]
+ [ComImportAttribute()]
[GuidAttribute("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IObjectArray
diff --git a/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/Interop.cs b/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/Interop.cs
index 87633043c..1724f50d0 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/Interop.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskbarLib/Interop/Interop.cs
@@ -24,6 +24,7 @@
using System;
using System.Runtime.InteropServices;
using System.Security;
+using System.Text;
using ProcessHacker.Native.Api;
namespace TaskbarLib.Interop
@@ -139,16 +140,16 @@ internal struct CALPWSTR
}
[StructLayout(LayoutKind.Explicit)]
- public struct PropVariant : IDisposable
+ internal struct PropVariant : IDisposable
{
[FieldOffset(0)]
private ushort vt;
[FieldOffset(8)]
private IntPtr pointerValue;
[FieldOffset(8)]
- public byte byteValue;
+ private byte byteValue;
[FieldOffset(8)]
- public long longValue;
+ private long longValue;
[FieldOffset(8)]
private short boolValue;
[MarshalAs(UnmanagedType.Struct)]
@@ -245,10 +246,10 @@ internal static class UnsafeNativeMethods
public static extern HResult SetCurrentProcessExplicitAppUserModelID([MarshalAs(UnmanagedType.LPWStr)] string AppID);
[DllImport("shell32.dll")]
- public static extern HResult GetCurrentProcessExplicitAppUserModelID([Out, MarshalAs(UnmanagedType.LPWStr)] out string AppID);
+ public static extern HResult GetCurrentProcessExplicitAppUserModelID([Out(), MarshalAs(UnmanagedType.LPWStr)] out string AppID);
[DllImport("shell32.dll")]
- public static extern HResult SHGetPropertyStoreForWindow(IntPtr hwnd, ref Guid iid /*IID_IPropertyStore*/, [Out, MarshalAs(UnmanagedType.Interface)] out IPropertyStore propertyStore);
+ public static extern HResult SHGetPropertyStoreForWindow(IntPtr hwnd, ref Guid iid /*IID_IPropertyStore*/, [Out(), MarshalAs(UnmanagedType.Interface)] out IPropertyStore propertyStore);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern HResult SHCreateItemFromParsingName(string path, /* The following parameter is not used - binding context. */ IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem shellItem);
diff --git a/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListImpl.cs b/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListImpl.cs
index 4fe093d2f..dfde269d8 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListImpl.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListImpl.cs
@@ -25,6 +25,7 @@
using System.Collections.Generic;
using System.Linq;
using TaskbarLib.Interop;
+using System.Runtime.InteropServices;
using ProcessHacker.Native.Api;
namespace TaskbarLib
@@ -36,7 +37,7 @@ internal sealed class JumpListDestinations
{
//TODO: This is highly inefficient, but we want to maintain insertion order when adding the categories
//because the bottom categories are first to be truncated if screen estate is low.
- private readonly SortedDictionary> _categorizedDestinations =
+ private SortedDictionary> _categorizedDestinations =
new SortedDictionary>();
public void AddDestination(IJumpListDestination destination)
@@ -96,7 +97,8 @@ public IEnumerable Categories
select _categorizedDestinations[d].First().Category);
}
}
- public IEnumerable GetDestinationsByCategory(string category)
+ public IEnumerable GetDestinationsByCategory(
+ string category)
{
return
(from k in _categorizedDestinations.Keys
@@ -116,7 +118,7 @@ public void Clear()
///
internal sealed class JumpListTasks
{
- private readonly List _tasks = new List();
+ private List _tasks = new List();
public void AddTask(IJumpListTask task)
{
diff --git a/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListManager.cs b/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListManager.cs
index 5b863e49a..dd058596b 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListManager.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskbarLib/JumpLists/JumpListManager.cs
@@ -27,8 +27,10 @@
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
+using System.Threading;
using Microsoft.Win32;
using TaskbarLib.Interop;
+using System.Runtime.CompilerServices;
using ProcessHacker.Native.Api;
namespace TaskbarLib
@@ -51,13 +53,13 @@ public sealed class JumpListManager : IDisposable
{
#region Members
- readonly string _appId;
+ string _appId;
uint _maxSlotsInList;
- readonly JumpListTasks _tasks;
- readonly JumpListDestinations _destinations;
- readonly EventHandler _displaySettingsChangeHandler;
- readonly ICustomDestinationList _customDestinationList;
+ JumpListTasks _tasks;
+ JumpListDestinations _destinations;
+ EventHandler _displaySettingsChangeHandler;
+ ICustomDestinationList _customDestinationList;
ApplicationDestinationType _enabledAutoDestinationType; // = ApplicationDestinationType.Recent;
#endregion
diff --git a/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButton.cs b/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButton.cs
index 830a8b0dd..b3630b3ff 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButton.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButton.cs
@@ -32,7 +32,7 @@ namespace TaskbarLib
///
public sealed class ThumbButton
{
- private readonly ThumbButtonManager _manager;
+ private ThumbButtonManager _manager;
internal ThumbButton(ThumbButtonManager manager, int id, Icon icon, string tooltip)
{
@@ -70,15 +70,13 @@ internal THUMBBUTTON Win32ThumbButton
{
get
{
- THUMBBUTTON win32ThumbButton = new THUMBBUTTON
- {
- iId = this.Id,
- szTip = this.Tooltip,
- hIcon = this.Icon.Handle,
- dwFlags = this.Flags | ThumbnailButtonFlags.DISMISSONCLICK,
- dwMask = ThumbnailButtonMask.Flags
- };
+ THUMBBUTTON win32ThumbButton = new THUMBBUTTON();
+ win32ThumbButton.iId = Id;
+ win32ThumbButton.szTip = Tooltip;
+ win32ThumbButton.hIcon = Icon.Handle;
+ win32ThumbButton.dwFlags = Flags | ThumbnailButtonFlags.DISMISSONCLICK;
+ win32ThumbButton.dwMask = ThumbnailButtonMask.Flags;
if (Tooltip != null)
win32ThumbButton.dwMask |= ThumbnailButtonMask.Tooltip;
if (Icon != null)
diff --git a/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButtonManager.cs b/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButtonManager.cs
index 6d1e74ede..69ba0de5a 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButtonManager.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskbarLib/ThumbnailButtons/ThumbButtonManager.cs
@@ -37,7 +37,7 @@ public sealed class ThumbButtonManager : IDisposable
{
private sealed class MessageFilter : IMessageFilter
{
- private readonly ThumbButtonManager _manager;
+ private ThumbButtonManager _manager;
public MessageFilter(ThumbButtonManager manager)
{
@@ -48,13 +48,12 @@ public bool PreFilterMessage(ref Message m)
{
if (m.Msg == (int)Windows7Taskbar.TaskbarButtonCreatedMessage)
{
- this._manager.OnTaskbarButtonCreated();
+ _manager.OnTaskbarButtonCreated();
return true;
}
-
- if (m.Msg == (int)ProcessHacker.Native.Api.WindowMessage.Command)
+ else if (m.Msg == (int)ProcessHacker.Native.Api.WindowMessage.Command)
{
- this._manager.OnCommand(m.WParam);
+ _manager.OnCommand(m.WParam);
}
return false;
@@ -63,8 +62,8 @@ public bool PreFilterMessage(ref Message m)
public event EventHandler TaskbarButtonCreated;
- private readonly Form _form;
- private readonly MessageFilter _filter;
+ private Form _form;
+ private MessageFilter _filter;
private bool _disposed;
///
@@ -166,7 +165,7 @@ internal void RefreshThumbButtons()
}
}
- private readonly Dictionary _thumbButtons = new Dictionary();
+ private Dictionary _thumbButtons = new Dictionary();
#endregion
}
diff --git a/1.x/trunk/ProcessHacker/Components/TaskbarLib/Windows7Taskbar.cs b/1.x/trunk/ProcessHacker/Components/TaskbarLib/Windows7Taskbar.cs
index b05156236..e24e2c8f2 100644
--- a/1.x/trunk/ProcessHacker/Components/TaskbarLib/Windows7Taskbar.cs
+++ b/1.x/trunk/ProcessHacker/Components/TaskbarLib/Windows7Taskbar.cs
@@ -72,8 +72,9 @@ public static JumpListManager CreateJumpListManager()
private static IPropertyStore InternalGetWindowPropertyStore(IntPtr hwnd)
{
IPropertyStore propStore;
-
- UnsafeNativeMethods.SHGetPropertyStoreForWindow(hwnd, ref SafeNativeMethods.IID_IPropertyStore, out propStore);
+ HResult shGetPropertyStoreResult = UnsafeNativeMethods.SHGetPropertyStoreForWindow(
+ hwnd, ref SafeNativeMethods.IID_IPropertyStore, out propStore);
+ shGetPropertyStoreResult.ThrowIf();
return propStore;
}
@@ -118,16 +119,15 @@ public static string AppId
set
{
IPropertyStore propStore = InternalGetWindowPropertyStore(Program.HackerWindowHandle);
- if (propStore != null)
- {
- PropVariant pv = new PropVariant();
- pv.SetValue(value);
- propStore.SetValue(ref PropertyKey.PKEY_AppUserModel_ID, ref pv);
+ PropVariant pv = new PropVariant();
+ pv.SetValue(value);
- Marshal.ReleaseComObject(propStore);
- pv.Dispose();
- }
+ HResult setValueResult = propStore.SetValue(ref PropertyKey.PKEY_AppUserModel_ID, ref pv);
+ setValueResult.ThrowIf();
+
+ Marshal.ReleaseComObject(propStore);
+ pv.Dispose();
}
}
@@ -139,12 +139,14 @@ public static string ProcessAppId
get
{
string appId;
- UnsafeNativeMethods.GetCurrentProcessExplicitAppUserModelID(out appId);
+ HResult getProcessAppUserModeIDResult = UnsafeNativeMethods.GetCurrentProcessExplicitAppUserModelID(out appId);
+ getProcessAppUserModeIDResult.ThrowIf();
return appId;
}
set
{
- UnsafeNativeMethods.SetCurrentProcessExplicitAppUserModelID(value);
+ HResult setProcessAppUserModeIDResult = UnsafeNativeMethods.SetCurrentProcessExplicitAppUserModelID(value);
+ setProcessAppUserModeIDResult.ThrowIf();
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/ThreadList.Designer.cs b/1.x/trunk/ProcessHacker/Components/ThreadList.Designer.cs
index 9cff647c8..8fd5967a5 100644
--- a/1.x/trunk/ProcessHacker/Components/ThreadList.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/ThreadList.Designer.cs
@@ -32,11 +32,12 @@ protected override void Dispose(bool disposing)
///
private void InitializeComponent()
{
- this.listThreads = new ProcessHacker.Components.ExtendedListView();
- this.columnThreadID = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnContextSwitchesDelta = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnStartAddress = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnPriority = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.components = new System.ComponentModel.Container();
+ this.listThreads = new System.Windows.Forms.ListView();
+ this.columnThreadID = new System.Windows.Forms.ColumnHeader();
+ this.columnContextSwitchesDelta = new System.Windows.Forms.ColumnHeader();
+ this.columnStartAddress = new System.Windows.Forms.ColumnHeader();
+ this.columnPriority = new System.Windows.Forms.ColumnHeader();
this.menuThread = new System.Windows.Forms.ContextMenu();
this.inspectThreadMenuItem = new System.Windows.Forms.MenuItem();
this.terminateThreadMenuItem = new System.Windows.Forms.MenuItem();
@@ -83,22 +84,23 @@ private void InitializeComponent()
this.label4 = new System.Windows.Forms.Label();
this.labelTEBAddress = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
this.fileModule = new ProcessHacker.Components.FileNameBox();
this.tableInformation.SuspendLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
// listThreads
//
this.listThreads.AllowColumnReorder = true;
- this.listThreads.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.listThreads.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.listThreads.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnThreadID,
this.columnContextSwitchesDelta,
this.columnStartAddress,
this.columnPriority});
- this.listThreads.DoubleClickChecks = true;
this.listThreads.FullRowSelect = true;
this.listThreads.HideSelection = false;
this.listThreads.Location = new System.Drawing.Point(0, 0);
@@ -154,12 +156,14 @@ private void InitializeComponent()
// inspectThreadMenuItem
//
this.inspectThreadMenuItem.DefaultItem = true;
+ this.vistaMenu.SetImage(this.inspectThreadMenuItem, global::ProcessHacker.Properties.Resources.application_form_magnify);
this.inspectThreadMenuItem.Index = 0;
this.inspectThreadMenuItem.Text = "&Inspect";
this.inspectThreadMenuItem.Click += new System.EventHandler(this.inspectThreadMenuItem_Click);
//
// terminateThreadMenuItem
//
+ this.vistaMenu.SetImage(this.terminateThreadMenuItem, global::ProcessHacker.Properties.Resources.cross);
this.terminateThreadMenuItem.Index = 1;
this.terminateThreadMenuItem.Text = "&Terminate";
this.terminateThreadMenuItem.Click += new System.EventHandler(this.terminateThreadMenuItem_Click);
@@ -172,12 +176,14 @@ private void InitializeComponent()
//
// suspendThreadMenuItem
//
+ this.vistaMenu.SetImage(this.suspendThreadMenuItem, global::ProcessHacker.Properties.Resources.control_pause_blue);
this.suspendThreadMenuItem.Index = 3;
this.suspendThreadMenuItem.Text = "&Suspend";
this.suspendThreadMenuItem.Click += new System.EventHandler(this.suspendThreadMenuItem_Click);
//
// resumeThreadMenuItem
//
+ this.vistaMenu.SetImage(this.resumeThreadMenuItem, global::ProcessHacker.Properties.Resources.control_play_blue);
this.resumeThreadMenuItem.Index = 4;
this.resumeThreadMenuItem.Text = "&Resume";
this.resumeThreadMenuItem.Click += new System.EventHandler(this.resumeThreadMenuItem_Click);
@@ -201,6 +207,7 @@ private void InitializeComponent()
//
// tokenThreadMenuItem
//
+ this.vistaMenu.SetImage(this.tokenThreadMenuItem, global::ProcessHacker.Properties.Resources.locked);
this.tokenThreadMenuItem.Index = 8;
this.tokenThreadMenuItem.Text = "Token";
this.tokenThreadMenuItem.Click += new System.EventHandler(this.tokenThreadMenuItem_Click);
@@ -321,6 +328,7 @@ private void InitializeComponent()
//
// copyThreadMenuItem
//
+ this.vistaMenu.SetImage(this.copyThreadMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyThreadMenuItem.Index = 13;
this.copyThreadMenuItem.Text = "C&opy";
//
@@ -332,8 +340,8 @@ private void InitializeComponent()
//
// tableInformation
//
- this.tableInformation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.tableInformation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.tableInformation.ColumnCount = 4;
this.tableInformation.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableInformation.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
@@ -372,7 +380,7 @@ private void InitializeComponent()
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(3, 3);
this.label6.Name = "label6";
- this.label6.Size = new System.Drawing.Size(33, 13);
+ this.label6.Size = new System.Drawing.Size(32, 13);
this.label6.TabIndex = 1;
this.label6.Text = "State";
//
@@ -382,7 +390,7 @@ private void InitializeComponent()
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(3, 22);
this.label8.Name = "label8";
- this.label8.Size = new System.Drawing.Size(65, 13);
+ this.label8.Size = new System.Drawing.Size(63, 13);
this.label8.TabIndex = 1;
this.label8.Text = "Kernel Time";
//
@@ -392,7 +400,7 @@ private void InitializeComponent()
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(3, 41);
this.label9.Name = "label9";
- this.label9.Size = new System.Drawing.Size(56, 13);
+ this.label9.Size = new System.Drawing.Size(55, 13);
this.label9.TabIndex = 1;
this.label9.Text = "User Time";
//
@@ -400,9 +408,9 @@ private void InitializeComponent()
//
this.labelState.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelState.AutoSize = true;
- this.labelState.Location = new System.Drawing.Point(187, 3);
+ this.labelState.Location = new System.Drawing.Point(188, 3);
this.labelState.Name = "labelState";
- this.labelState.Size = new System.Drawing.Size(34, 13);
+ this.labelState.Size = new System.Drawing.Size(33, 13);
this.labelState.TabIndex = 1;
this.labelState.Text = "value";
//
@@ -410,9 +418,9 @@ private void InitializeComponent()
//
this.labelKernelTime.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelKernelTime.AutoSize = true;
- this.labelKernelTime.Location = new System.Drawing.Point(187, 22);
+ this.labelKernelTime.Location = new System.Drawing.Point(188, 22);
this.labelKernelTime.Name = "labelKernelTime";
- this.labelKernelTime.Size = new System.Drawing.Size(34, 13);
+ this.labelKernelTime.Size = new System.Drawing.Size(33, 13);
this.labelKernelTime.TabIndex = 1;
this.labelKernelTime.Text = "value";
//
@@ -420,9 +428,9 @@ private void InitializeComponent()
//
this.labelUserTime.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelUserTime.AutoSize = true;
- this.labelUserTime.Location = new System.Drawing.Point(187, 41);
+ this.labelUserTime.Location = new System.Drawing.Point(188, 41);
this.labelUserTime.Name = "labelUserTime";
- this.labelUserTime.Size = new System.Drawing.Size(34, 13);
+ this.labelUserTime.Size = new System.Drawing.Size(33, 13);
this.labelUserTime.TabIndex = 1;
this.labelUserTime.Text = "value";
//
@@ -430,9 +438,9 @@ private void InitializeComponent()
//
this.labelTotalTime.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelTotalTime.AutoSize = true;
- this.labelTotalTime.Location = new System.Drawing.Point(187, 61);
+ this.labelTotalTime.Location = new System.Drawing.Point(188, 61);
this.labelTotalTime.Name = "labelTotalTime";
- this.labelTotalTime.Size = new System.Drawing.Size(34, 13);
+ this.labelTotalTime.Size = new System.Drawing.Size(33, 13);
this.labelTotalTime.TabIndex = 1;
this.labelTotalTime.Text = "value";
//
@@ -442,7 +450,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(227, 61);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(95, 13);
+ this.label1.Size = new System.Drawing.Size(89, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Context Switches";
//
@@ -452,7 +460,7 @@ private void InitializeComponent()
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(227, 41);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(70, 13);
+ this.label2.Size = new System.Drawing.Size(65, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Base Priority";
//
@@ -462,7 +470,7 @@ private void InitializeComponent()
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(227, 22);
this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(43, 13);
+ this.label3.Size = new System.Drawing.Size(38, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Priority";
//
@@ -470,9 +478,9 @@ private void InitializeComponent()
//
this.labelContextSwitches.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelContextSwitches.AutoSize = true;
- this.labelContextSwitches.Location = new System.Drawing.Point(413, 61);
+ this.labelContextSwitches.Location = new System.Drawing.Point(414, 61);
this.labelContextSwitches.Name = "labelContextSwitches";
- this.labelContextSwitches.Size = new System.Drawing.Size(34, 13);
+ this.labelContextSwitches.Size = new System.Drawing.Size(33, 13);
this.labelContextSwitches.TabIndex = 7;
this.labelContextSwitches.Text = "value";
//
@@ -480,9 +488,9 @@ private void InitializeComponent()
//
this.labelBasePriority.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelBasePriority.AutoSize = true;
- this.labelBasePriority.Location = new System.Drawing.Point(413, 41);
+ this.labelBasePriority.Location = new System.Drawing.Point(414, 41);
this.labelBasePriority.Name = "labelBasePriority";
- this.labelBasePriority.Size = new System.Drawing.Size(34, 13);
+ this.labelBasePriority.Size = new System.Drawing.Size(33, 13);
this.labelBasePriority.TabIndex = 4;
this.labelBasePriority.Text = "value";
//
@@ -490,9 +498,9 @@ private void InitializeComponent()
//
this.labelPriority.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelPriority.AutoSize = true;
- this.labelPriority.Location = new System.Drawing.Point(413, 22);
+ this.labelPriority.Location = new System.Drawing.Point(414, 22);
this.labelPriority.Name = "labelPriority";
- this.labelPriority.Size = new System.Drawing.Size(34, 13);
+ this.labelPriority.Size = new System.Drawing.Size(33, 13);
this.labelPriority.TabIndex = 3;
this.labelPriority.Text = "value";
//
@@ -502,7 +510,7 @@ private void InitializeComponent()
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(3, 61);
this.label10.Name = "label10";
- this.label10.Size = new System.Drawing.Size(58, 13);
+ this.label10.Size = new System.Drawing.Size(57, 13);
this.label10.TabIndex = 1;
this.label10.Text = "Total Time";
//
@@ -520,9 +528,9 @@ private void InitializeComponent()
//
this.labelTEBAddress.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.labelTEBAddress.AutoSize = true;
- this.labelTEBAddress.Location = new System.Drawing.Point(413, 3);
+ this.labelTEBAddress.Location = new System.Drawing.Point(414, 3);
this.labelTEBAddress.Name = "labelTEBAddress";
- this.labelTEBAddress.Size = new System.Drawing.Size(34, 13);
+ this.labelTEBAddress.Size = new System.Drawing.Size(33, 13);
this.labelTEBAddress.TabIndex = 3;
this.labelTEBAddress.Text = "value";
//
@@ -532,14 +540,19 @@ private void InitializeComponent()
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(3, 356);
this.label7.Name = "label7";
- this.label7.Size = new System.Drawing.Size(77, 13);
+ this.label7.Size = new System.Drawing.Size(70, 13);
this.label7.TabIndex = 5;
this.label7.Text = "Start Module:";
//
+ // vistaMenu
+ //
+ this.vistaMenu.ContainerControl = this;
+ this.vistaMenu.DelaySetImageCalls = false;
+ //
// fileModule
//
- this.fileModule.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.fileModule.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.fileModule.Location = new System.Drawing.Point(79, 351);
this.fileModule.Name = "fileModule";
this.fileModule.ReadOnly = true;
@@ -550,15 +563,16 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.fileModule);
this.Controls.Add(this.label7);
this.Controls.Add(this.tableInformation);
this.Controls.Add(this.listThreads);
+ this.DoubleBuffered = true;
this.Name = "ThreadList";
this.Size = new System.Drawing.Size(450, 460);
this.tableInformation.ResumeLayout(false);
this.tableInformation.PerformLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
@@ -566,10 +580,11 @@ private void InitializeComponent()
#endregion
- private ExtendedListView listThreads;
+ private System.Windows.Forms.ListView listThreads;
private System.Windows.Forms.ColumnHeader columnThreadID;
private System.Windows.Forms.ColumnHeader columnContextSwitchesDelta;
private System.Windows.Forms.ColumnHeader columnStartAddress;
+ private wyDay.Controls.VistaMenu vistaMenu;
private System.Windows.Forms.ContextMenu menuThread;
private System.Windows.Forms.MenuItem inspectThreadMenuItem;
private System.Windows.Forms.MenuItem terminateThreadMenuItem;
diff --git a/1.x/trunk/ProcessHacker/Components/ThreadList.cs b/1.x/trunk/ProcessHacker/Components/ThreadList.cs
index 88c816297..08803545f 100644
--- a/1.x/trunk/ProcessHacker/Components/ThreadList.cs
+++ b/1.x/trunk/ProcessHacker/Components/ThreadList.cs
@@ -23,6 +23,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Reflection;
using System.Text;
using System.Windows.Forms;
using ProcessHacker.Common;
@@ -40,11 +41,11 @@ namespace ProcessHacker.Components
public partial class ThreadList : UserControl
{
private ThreadProvider _provider;
- private bool _useCycleTime;
- private int _runCount;
- private readonly List _needsAdd = new List();
- private readonly HighlightingContext _highlightingContext;
- private bool _needsSort;
+ private bool _useCycleTime = false;
+ private int _runCount = 0;
+ private List _needsAdd = new List();
+ private HighlightingContext _highlightingContext;
+ private bool _needsSort = false;
public new event KeyEventHandler KeyDown;
public new event MouseEventHandler MouseDown;
public new event MouseEventHandler MouseUp;
@@ -71,16 +72,23 @@ public ThreadList()
var comparer = (SortedListViewComparer)
(listThreads.ListViewItemSorter = new SortedListViewComparer(listThreads));
- comparer.CustomSorters.Add(1, (x, y) =>
- {
- if (OSVersion.HasCycleTime)
+ comparer.CustomSorters.Add(1,
+ (x, y) =>
{
- return ((ThreadItem)x.Tag).CyclesDelta.CompareTo((y.Tag as ThreadItem).CyclesDelta);
- }
-
- return ((ThreadItem)x.Tag).ContextSwitchesDelta.CompareTo((y.Tag as ThreadItem).ContextSwitchesDelta);
- });
- comparer.CustomSorters.Add(3, (x, y) => ((ThreadItem)x.Tag).PriorityI.CompareTo((y.Tag as ThreadItem).PriorityI));
+ if (OSVersion.HasCycleTime)
+ {
+ return (x.Tag as ThreadItem).CyclesDelta.CompareTo((y.Tag as ThreadItem).CyclesDelta);
+ }
+ else
+ {
+ return (x.Tag as ThreadItem).ContextSwitchesDelta.CompareTo((y.Tag as ThreadItem).ContextSwitchesDelta);
+ }
+ });
+ comparer.CustomSorters.Add(3,
+ (x, y) =>
+ {
+ return (x.Tag as ThreadItem).PriorityI.CompareTo((y.Tag as ThreadItem).PriorityI);
+ });
comparer.ColumnSortOrder.Add(0);
comparer.ColumnSortOrder.Add(2);
comparer.ColumnSortOrder.Add(3);
@@ -88,15 +96,27 @@ public ThreadList()
comparer.SortColumn = 1;
comparer.SortOrder = SortOrder.Descending;
- listThreads.KeyDown += this.ThreadList_KeyDown;
- listThreads.MouseDown += this.listThreads_MouseDown;
- listThreads.MouseUp += this.listThreads_MouseUp;
- listThreads.SelectedIndexChanged += this.listThreads_SelectedIndexChanged;
+ listThreads.KeyDown += new KeyEventHandler(ThreadList_KeyDown);
+ listThreads.MouseDown += new MouseEventHandler(listThreads_MouseDown);
+ listThreads.MouseUp += new MouseEventHandler(listThreads_MouseUp);
+ listThreads.SelectedIndexChanged += new System.EventHandler(listThreads_SelectedIndexChanged);
ColumnSettings.LoadSettings(Settings.Instance.ThreadListViewColumns, listThreads);
listThreads.ContextMenu = menuThread;
GenericViewMenu.AddMenuItems(copyThreadMenuItem.MenuItems, listThreads, null);
listThreads_SelectedIndexChanged(null, null);
+
+ _dontCalculate = false;
+ }
+
+ private bool _dontCalculate = true;
+
+ protected override void OnResize(EventArgs e)
+ {
+ if (_dontCalculate)
+ return;
+
+ base.OnResize(e);
}
private void listThreads_MouseUp(object sender, MouseEventArgs e)
@@ -166,16 +186,16 @@ private void listThreads_SelectedIndexChanged(object sender, System.EventArgs e)
}
else
{
- fileModule.Text = string.Empty;
+ fileModule.Text = "";
fileModule.Enabled = false;
- labelState.Text = string.Empty;
- labelKernelTime.Text = string.Empty;
- labelUserTime.Text = string.Empty;
- labelTotalTime.Text = string.Empty;
- labelTEBAddress.Text = string.Empty;
- labelPriority.Text = string.Empty;
- labelBasePriority.Text = string.Empty;
- labelContextSwitches.Text = string.Empty;
+ labelState.Text = "";
+ labelKernelTime.Text = "";
+ labelUserTime.Text = "";
+ labelTotalTime.Text = "";
+ labelTEBAddress.Text = "";
+ labelPriority.Text = "";
+ labelBasePriority.Text = "";
+ labelContextSwitches.Text = "";
}
if (this.SelectedIndexChanged != null)
@@ -189,20 +209,33 @@ private void ThreadList_KeyDown(object sender, KeyEventArgs e)
if (!e.Handled)
{
- switch (e.KeyCode)
+ if (e.KeyCode == Keys.Enter)
+ {
+ inspectThreadMenuItem_Click(null, null);
+ }
+ else if (e.KeyCode == Keys.Delete)
{
- case Keys.Enter:
- this.inspectThreadMenuItem_Click(null, null);
- break;
- case Keys.Delete:
- this.terminateThreadMenuItem_Click(null, null);
- break;
+ terminateThreadMenuItem_Click(null, null);
}
}
}
#region Properties
+ public new bool DoubleBuffered
+ {
+ get
+ {
+ return (bool)typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).GetValue(listThreads, null);
+ }
+ set
+ {
+ typeof(ListView).GetProperty("DoubleBuffered",
+ BindingFlags.NonPublic | BindingFlags.Instance).SetValue(listThreads, value, null);
+ }
+ }
+
public override bool Focused
{
get
@@ -223,7 +256,7 @@ public override ContextMenuStrip ContextMenuStrip
set { listThreads.ContextMenuStrip = value; }
}
- public ExtendedListView List
+ public ListView List
{
get { return listThreads; }
}
@@ -237,11 +270,11 @@ public ThreadProvider Provider
if (_provider != null)
{
- _provider.DictionaryAdded -= this.provider_DictionaryAdded;
- _provider.DictionaryModified -= this.provider_DictionaryModified;
- _provider.DictionaryRemoved -= this.provider_DictionaryRemoved;
- _provider.Updated -= this.provider_Updated;
- _provider.LoadingStateChanged -= this.provider_LoadingStateChanged;
+ _provider.DictionaryAdded -= new ThreadProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryModified -= new ThreadProvider.ProviderDictionaryModified(provider_DictionaryModified);
+ _provider.DictionaryRemoved -= new ThreadProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated -= new ThreadProvider.ProviderUpdateOnce(provider_Updated);
+ _provider.LoadingStateChanged -= new ThreadProvider.LoadingStateChangedDelegate(provider_LoadingStateChanged);
}
_provider = value;
@@ -273,11 +306,11 @@ public ThreadProvider Provider
else
listThreads.Columns[1].Text = "Context Switches Delta";
- _provider.DictionaryAdded += this.provider_DictionaryAdded;
- _provider.DictionaryModified += this.provider_DictionaryModified;
- _provider.DictionaryRemoved += this.provider_DictionaryRemoved;
- _provider.Updated += this.provider_Updated;
- _provider.LoadingStateChanged += this.provider_LoadingStateChanged;
+ _provider.DictionaryAdded += new ThreadProvider.ProviderDictionaryAdded(provider_DictionaryAdded);
+ _provider.DictionaryModified += new ThreadProvider.ProviderDictionaryModified(provider_DictionaryModified);
+ _provider.DictionaryRemoved += new ThreadProvider.ProviderDictionaryRemoved(provider_DictionaryRemoved);
+ _provider.Updated += new ThreadProvider.ProviderUpdateOnce(provider_Updated);
+ _provider.LoadingStateChanged += new ThreadProvider.LoadingStateChangedDelegate(provider_LoadingStateChanged);
this.EnableDisableMenuItems();
}
@@ -335,13 +368,13 @@ private void provider_Updated()
if (_needsSort)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- if (_needsSort)
{
- listThreads.Sort();
- _needsSort = false;
- }
- }));
+ if (_needsSort)
+ {
+ listThreads.Sort();
+ _needsSort = false;
+ }
+ }));
}
_runCount++;
@@ -351,7 +384,7 @@ private void EnableDisableMenuItems()
{
if (
// If KProcessHacker isn't available, hide Force Terminate.
- //KProcessHacker.Instance != null &&
+ KProcessHacker.Instance != null &&
// Terminating a system thread is the same as Force Terminate,
// so hide it if we're viewing PID 4.
_pid != 4
@@ -365,8 +398,7 @@ private System.Drawing.Color GetThreadColor(ThreadItem titem)
{
if (Settings.Instance.UseColorSuspended && titem.WaitReason == KWaitReason.Suspended)
return Settings.Instance.ColorSuspended;
-
- if (Settings.Instance.UseColorGuiThreads && titem.IsGuiThread)
+ else if (Settings.Instance.UseColorGuiThreads && titem.IsGuiThread)
return Settings.Instance.ColorGuiThreads;
return System.Drawing.SystemColors.Window;
@@ -374,13 +406,12 @@ private System.Drawing.Color GetThreadColor(ThreadItem titem)
private void provider_DictionaryAdded(ThreadItem item)
{
- HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext, item.RunId > 0 && _runCount > 0)
- {
- Name = item.Tid.ToString(),
- Text = item.Tid.ToString()
- };
+ HighlightedListViewItem litem = new HighlightedListViewItem(_highlightingContext,
+ item.RunId > 0 && _runCount > 0);
- litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, string.Empty));
+ litem.Name = item.Tid.ToString();
+ litem.Text = item.Tid.ToString();
+ litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, ""));
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.StartAddress));
litem.SubItems.Add(new ListViewItem.ListViewSubItem(litem, item.Priority));
litem.Tag = item;
@@ -393,60 +424,60 @@ private void provider_DictionaryAdded(ThreadItem item)
private void provider_DictionaryModified(ThreadItem oldItem, ThreadItem newItem)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- lock (listThreads)
{
- ListViewItem litem = listThreads.Items[newItem.Tid.ToString()];
+ lock (listThreads)
+ {
+ ListViewItem litem = listThreads.Items[newItem.Tid.ToString()];
- if (litem == null)
- return;
+ if (litem == null)
+ return;
- if (!_useCycleTime)
- {
- if (newItem.ContextSwitchesDelta == 0)
- litem.SubItems[1].Text = string.Empty;
- else
- litem.SubItems[1].Text = newItem.ContextSwitchesDelta.ToString("N0");
- }
- else
- {
- if (newItem.CyclesDelta == 0)
- litem.SubItems[1].Text = string.Empty;
+ if (!_useCycleTime)
+ {
+ if (newItem.ContextSwitchesDelta == 0)
+ litem.SubItems[1].Text = "";
+ else
+ litem.SubItems[1].Text = newItem.ContextSwitchesDelta.ToString("N0");
+ }
else
- litem.SubItems[1].Text = newItem.CyclesDelta.ToString("N0");
- }
+ {
+ if (newItem.CyclesDelta == 0)
+ litem.SubItems[1].Text = "";
+ else
+ litem.SubItems[1].Text = newItem.CyclesDelta.ToString("N0");
+ }
- litem.SubItems[2].Text = newItem.StartAddress;
- litem.SubItems[3].Text = newItem.Priority;
- litem.Tag = newItem;
+ litem.SubItems[2].Text = newItem.StartAddress;
+ litem.SubItems[3].Text = newItem.Priority;
+ litem.Tag = newItem;
- (litem as HighlightedListViewItem).NormalColor = GetThreadColor(newItem);
- _needsSort = true;
- }
- }));
+ (litem as HighlightedListViewItem).NormalColor = GetThreadColor(newItem);
+ _needsSort = true;
+ }
+ }));
}
private void provider_DictionaryRemoved(ThreadItem item)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- lock (listThreads)
{
- if (listThreads.Items.ContainsKey(item.Tid.ToString()))
- listThreads.Items[item.Tid.ToString()].Remove();
- }
- }));
+ lock (listThreads)
+ {
+ if (listThreads.Items.ContainsKey(item.Tid.ToString()))
+ listThreads.Items[item.Tid.ToString()].Remove();
+ }
+ }));
}
private void provider_LoadingStateChanged(bool loading)
{
this.BeginInvoke(new MethodInvoker(() =>
- {
- if (loading)
- listThreads.Cursor = Cursors.AppStarting;
- else
- listThreads.Cursor = Cursors.Default;
- }));
+ {
+ if (loading)
+ listThreads.Cursor = Cursors.AppStarting;
+ else
+ listThreads.Cursor = Cursors.Default;
+ }));
}
public void SaveSettings()
@@ -460,7 +491,7 @@ private void SetThreadPriority(ThreadPriorityLevel priority)
{
int tid = int.Parse(listThreads.SelectedItems[0].SubItems[0].Text);
- using (ThreadHandle thandle = new ThreadHandle(tid, OSVersion.MinThreadSetInfoAccess))
+ using (var thandle = new ThreadHandle(tid, OSVersion.MinThreadSetInfoAccess))
thandle.SetBasePriorityWin32(priority);
}
catch (Exception ex)
@@ -475,7 +506,7 @@ private void SetThreadIoPriority(int ioPriority)
{
int tid = int.Parse(listThreads.SelectedItems[0].SubItems[0].Text);
- using (ThreadHandle thandle = new ThreadHandle(tid, OSVersion.MinThreadSetInfoAccess))
+ using (var thandle = new ThreadHandle(tid, OSVersion.MinThreadSetInfoAccess))
thandle.SetIoPriority(ioPriority);
}
catch (Exception ex)
@@ -491,120 +522,136 @@ private void listThreads_DoubleClick(object sender, EventArgs e)
private void menuThread_Popup(object sender, EventArgs e)
{
- switch (this.listThreads.SelectedItems.Count)
+ if (listThreads.SelectedItems.Count == 0)
{
- case 0:
- return;
- case 1:
- this.menuThread.EnableAll();
- this.terminateThreadMenuItem.Text = "&Terminate Thread";
- this.forceTerminateThreadMenuItem.Text = "Force Terminate Thread";
- this.suspendThreadMenuItem.Text = "&Suspend Thread";
- this.resumeThreadMenuItem.Text = "&Resume Thread";
- this.priorityThreadMenuItem.Text = "&Priority";
- this.timeCriticalThreadMenuItem.Checked = false;
- this.highestThreadMenuItem.Checked = false;
- this.aboveNormalThreadMenuItem.Checked = false;
- this.normalThreadMenuItem.Checked = false;
- this.belowNormalThreadMenuItem.Checked = false;
- this.lowestThreadMenuItem.Checked = false;
- this.idleThreadMenuItem.Checked = false;
- this.ioPriority0ThreadMenuItem.Checked = false;
- this.ioPriority1ThreadMenuItem.Checked = false;
- this.ioPriority2ThreadMenuItem.Checked = false;
- this.ioPriority3ThreadMenuItem.Checked = false;
- try
+ menuThread.DisableAll();
+
+ return;
+ }
+ else if (listThreads.SelectedItems.Count == 1)
+ {
+ menuThread.EnableAll();
+
+ terminateThreadMenuItem.Text = "&Terminate Thread";
+ forceTerminateThreadMenuItem.Text = "Force Terminate Thread";
+ suspendThreadMenuItem.Text = "&Suspend Thread";
+ resumeThreadMenuItem.Text = "&Resume Thread";
+ priorityThreadMenuItem.Text = "&Priority";
+
+ timeCriticalThreadMenuItem.Checked = false;
+ highestThreadMenuItem.Checked = false;
+ aboveNormalThreadMenuItem.Checked = false;
+ normalThreadMenuItem.Checked = false;
+ belowNormalThreadMenuItem.Checked = false;
+ lowestThreadMenuItem.Checked = false;
+ idleThreadMenuItem.Checked = false;
+
+ ioPriority0ThreadMenuItem.Checked = false;
+ ioPriority1ThreadMenuItem.Checked = false;
+ ioPriority2ThreadMenuItem.Checked = false;
+ ioPriority3ThreadMenuItem.Checked = false;
+
+ try
+ {
+ using (var thandle = new ThreadHandle(
+ int.Parse(listThreads.SelectedItems[0].SubItems[0].Text),
+ Program.MinThreadQueryRights))
{
- using (var thandle = new ThreadHandle(int.Parse(this.listThreads.SelectedItems[0].SubItems[0].Text), Program.MinThreadQueryRights))
+ try
{
- try
+ switch (thandle.GetBasePriorityWin32())
+ {
+ case ThreadPriorityLevel.TimeCritical:
+ timeCriticalThreadMenuItem.Checked = true;
+ break;
+ case ThreadPriorityLevel.Highest:
+ highestThreadMenuItem.Checked = true;
+ break;
+ case ThreadPriorityLevel.AboveNormal:
+ aboveNormalThreadMenuItem.Checked = true;
+ break;
+ case ThreadPriorityLevel.Normal:
+ normalThreadMenuItem.Checked = true;
+ break;
+ case ThreadPriorityLevel.BelowNormal:
+ belowNormalThreadMenuItem.Checked = true;
+ break;
+ case ThreadPriorityLevel.Lowest:
+ lowestThreadMenuItem.Checked = true;
+ break;
+ case ThreadPriorityLevel.Idle:
+ idleThreadMenuItem.Checked = true;
+ break;
+ }
+ }
+ catch
+ {
+ priorityThreadMenuItem.Enabled = false;
+ }
+
+ try
+ {
+ if (OSVersion.HasIoPriority)
{
- switch (thandle.GetBasePriorityWin32())
+ switch (thandle.GetIoPriority())
{
- case ThreadPriorityLevel.TimeCritical:
- this.timeCriticalThreadMenuItem.Checked = true;
- break;
- case ThreadPriorityLevel.Highest:
- this.highestThreadMenuItem.Checked = true;
- break;
- case ThreadPriorityLevel.AboveNormal:
- this.aboveNormalThreadMenuItem.Checked = true;
- break;
- case ThreadPriorityLevel.Normal:
- this.normalThreadMenuItem.Checked = true;
+ case 0:
+ ioPriority0ThreadMenuItem.Checked = true;
break;
- case ThreadPriorityLevel.BelowNormal:
- this.belowNormalThreadMenuItem.Checked = true;
+ case 1:
+ ioPriority1ThreadMenuItem.Checked = true;
break;
- case ThreadPriorityLevel.Lowest:
- this.lowestThreadMenuItem.Checked = true;
+ case 2:
+ ioPriority2ThreadMenuItem.Checked = true;
break;
- case ThreadPriorityLevel.Idle:
- this.idleThreadMenuItem.Checked = true;
+ case 3:
+ ioPriority3ThreadMenuItem.Checked = true;
break;
}
}
- catch
- {
- this.priorityThreadMenuItem.Enabled = false;
- }
-
- try
- {
- if (OSVersion.HasIoPriority)
- {
- switch (thandle.GetIoPriority())
- {
- case 0:
- this.ioPriority0ThreadMenuItem.Checked = true;
- break;
- case 1:
- this.ioPriority1ThreadMenuItem.Checked = true;
- break;
- case 2:
- this.ioPriority2ThreadMenuItem.Checked = true;
- break;
- case 3:
- this.ioPriority3ThreadMenuItem.Checked = true;
- break;
- }
- }
- }
- catch
- {
- this.ioPriorityThreadMenuItem.Enabled = false;
- }
+ }
+ catch
+ {
+ ioPriorityThreadMenuItem.Enabled = false;
}
}
- catch
- {
- this.priorityThreadMenuItem.Enabled = false;
- this.ioPriorityThreadMenuItem.Enabled = false;
- }
- try
+ }
+ catch
+ {
+ priorityThreadMenuItem.Enabled = false;
+ ioPriorityThreadMenuItem.Enabled = false;
+ }
+
+ try
+ {
+ using (ThreadHandle thandle = new ThreadHandle(
+ int.Parse(listThreads.SelectedItems[0].Text), Program.MinThreadQueryRights
+ ))
{
- using (ThreadHandle thandle = new ThreadHandle(int.Parse(this.listThreads.SelectedItems[0].Text), Program.MinThreadQueryRights))
using (TokenHandle tokenHandle = thandle.GetToken(TokenAccess.Query))
{
- this.tokenThreadMenuItem.Enabled = true;
+ tokenThreadMenuItem.Enabled = true;
}
}
- catch (WindowsException)
- {
- this.tokenThreadMenuItem.Enabled = false;
- }
- break;
- default:
- this.terminateThreadMenuItem.Enabled = true;
- this.forceTerminateThreadMenuItem.Enabled = true;
- this.suspendThreadMenuItem.Enabled = true;
- this.resumeThreadMenuItem.Enabled = true;
- this.terminateThreadMenuItem.Text = "&Terminate Threads";
- this.forceTerminateThreadMenuItem.Text = "Force Terminate Threads";
- this.suspendThreadMenuItem.Text = "&Suspend Threads";
- this.resumeThreadMenuItem.Text = "&Resume Threads";
- this.copyThreadMenuItem.Enabled = true;
- break;
+ }
+ catch (WindowsException)
+ {
+ tokenThreadMenuItem.Enabled = false;
+ }
+ }
+ else
+ {
+ menuThread.DisableAll();
+
+ terminateThreadMenuItem.Enabled = true;
+ forceTerminateThreadMenuItem.Enabled = true;
+ suspendThreadMenuItem.Enabled = true;
+ resumeThreadMenuItem.Enabled = true;
+ terminateThreadMenuItem.Text = "&Terminate Threads";
+ forceTerminateThreadMenuItem.Text = "Force Terminate Threads";
+ suspendThreadMenuItem.Text = "&Suspend Threads";
+ resumeThreadMenuItem.Text = "&Resume Threads";
+ copyThreadMenuItem.Enabled = true;
}
if (listThreads.Items.Count == 0)
@@ -623,7 +670,10 @@ private void inspectThreadMenuItem_Click(object sender, EventArgs e)
return;
// Can't view system thread stacks if KPH isn't present.
- if (_pid == 4)
+ if (
+ _pid == 4 &&
+ KProcessHacker.Instance == null
+ )
{
PhUtils.ShowError(
"Process Hacker cannot view system thread stacks without KProcessHacker. " +
@@ -635,7 +685,7 @@ private void inspectThreadMenuItem_Click(object sender, EventArgs e)
}
// Suspending PH threads is not a good idea :(
- if (_pid == ProcessHandle.CurrentId)
+ if (_pid == ProcessHandle.GetCurrentId())
{
if (!PhUtils.ShowConfirmMessage(
"inspect",
@@ -651,10 +701,18 @@ private void inspectThreadMenuItem_Click(object sender, EventArgs e)
ProcessHandle phandle = null;
// If we have KPH, we don't need much access.
- if ((_provider.ProcessAccess & ProcessAccess.QueryLimitedInformation) != 0 ||
- (_provider.ProcessAccess & ProcessAccess.QueryInformation) != 0)
- phandle = _provider.ProcessHandle;
-
+ if (KProcessHacker.Instance != null)
+ {
+ if ((_provider.ProcessAccess & ProcessAccess.QueryLimitedInformation) != 0 ||
+ (_provider.ProcessAccess & ProcessAccess.QueryInformation) != 0)
+ phandle = _provider.ProcessHandle;
+ }
+ else
+ {
+ if ((_provider.ProcessAccess & (ProcessAccess.QueryInformation | ProcessAccess.VmRead)) != 0)
+ phandle = _provider.ProcessHandle;
+ }
+
// If we have KPH load kernel modules so we can get the kernel-mode stack.
try
{
@@ -684,7 +742,7 @@ private void terminateThreadMenuItem_Click(object sender, EventArgs e)
// Special case for system threads.
if (
- // KProcessHacker.Instance != null &&
+ KProcessHacker.Instance != null &&
_pid == 4
)
{
@@ -723,19 +781,21 @@ private void terminateThreadMenuItem_Click(object sender, EventArgs e)
return;
if (Program.ElevationType == TokenElevationType.Limited &&
+ KProcessHacker.Instance == null &&
Settings.Instance.ElevationLevel != (int)ElevationLevel.Never)
{
try
{
foreach (ListViewItem item in listThreads.SelectedItems)
{
- using (var thandle = new ThreadHandle(int.Parse(item.SubItems[0].Text), ThreadAccess.Terminate))
+ using (var thandle = new ThreadHandle(int.Parse(item.SubItems[0].Text),
+ ThreadAccess.Terminate))
{ }
}
}
catch
{
- string objects = string.Empty;
+ string objects = "";
foreach (ListViewItem item in listThreads.SelectedItems)
objects += item.SubItems[0].Text + ",";
@@ -808,24 +868,28 @@ private void suspendThreadMenuItem_Click(object sender, EventArgs e)
// return;
//}
- if (Program.ElevationType == TokenElevationType.Limited && Settings.Instance.ElevationLevel != (int)ElevationLevel.Never)
+ if (Program.ElevationType == TokenElevationType.Limited &&
+ KProcessHacker.Instance == null &&
+ Settings.Instance.ElevationLevel != (int)ElevationLevel.Never)
{
try
{
foreach (ListViewItem item in listThreads.SelectedItems)
{
- using (var thandle = new ThreadHandle(int.Parse(item.SubItems[0].Text), ThreadAccess.SuspendResume))
+ using (var thandle = new ThreadHandle(int.Parse(item.SubItems[0].Text),
+ ThreadAccess.SuspendResume))
{ }
}
}
catch
{
- string objects = string.Empty;
+ string objects = "";
foreach (ListViewItem item in listThreads.SelectedItems)
objects += item.SubItems[0].Text + ",";
- Program.StartProcessHackerAdmin("-e -type thread -action suspend -obj \"" + objects + "\" -hwnd " + this.Handle.ToString(), null, this.Handle);
+ Program.StartProcessHackerAdmin("-e -type thread -action suspend -obj \"" +
+ objects + "\" -hwnd " + this.Handle.ToString(), null, this.Handle);
return;
}
@@ -835,7 +899,8 @@ private void suspendThreadMenuItem_Click(object sender, EventArgs e)
{
try
{
- using (var thandle = new ThreadHandle(Int32.Parse(item.SubItems[0].Text), ThreadAccess.SuspendResume))
+ using (var thandle = new ThreadHandle(Int32.Parse(item.SubItems[0].Text),
+ ThreadAccess.SuspendResume))
thandle.Suspend();
}
catch (Exception ex)
@@ -861,7 +926,9 @@ private void resumeThreadMenuItem_Click(object sender, EventArgs e)
// return;
//}
- if (Program.ElevationType == TokenElevationType.Limited && Settings.Instance.ElevationLevel != (int)ElevationLevel.Never)
+ if (Program.ElevationType == TokenElevationType.Limited &&
+ KProcessHacker.Instance == null &&
+ Settings.Instance.ElevationLevel != (int)ElevationLevel.Never)
{
try
{
@@ -874,7 +941,7 @@ private void resumeThreadMenuItem_Click(object sender, EventArgs e)
}
catch
{
- string objects = string.Empty;
+ string objects = "";
foreach (ListViewItem item in listThreads.SelectedItems)
objects += item.SubItems[0].Text + ",";
@@ -889,7 +956,8 @@ private void resumeThreadMenuItem_Click(object sender, EventArgs e)
{
try
{
- using (ThreadHandle thandle = new ThreadHandle(Int32.Parse(item.SubItems[0].Text), ThreadAccess.SuspendResume))
+ using (var thandle = new ThreadHandle(Int32.Parse(item.SubItems[0].Text),
+ ThreadAccess.SuspendResume))
thandle.Resume();
}
catch (Exception ex)
@@ -917,12 +985,20 @@ private void inspectTEBMenuItem_Click(object sender, EventArgs e)
{
IntPtr tebBaseAddress = thandle.GetBasicInformation().TebBaseAddress;
- Program.HackerWindow.BeginInvoke(new MethodInvoker(() =>
- {
- StructWindow sw = new StructWindow(this._pid, tebBaseAddress, Program.Structs["TEB"]);
- sw.Show();
- sw.Activate();
- }));
+ Program.HackerWindow.BeginInvoke(new MethodInvoker(delegate
+ {
+ StructWindow sw = new StructWindow(_pid, tebBaseAddress, Program.Structs["TEB"]);
+
+ try
+ {
+ sw.Show();
+ sw.Activate();
+ }
+ catch (Exception ex)
+ {
+ Logging.Log(ex);
+ }
+ }));
}
}
catch (Exception ex)
@@ -938,7 +1014,7 @@ private void permissionsThreadMenuItem_Click(object sender, EventArgs e)
SecurityEditor.EditSecurity(
this,
SecurityEditor.GetSecurableWrapper(
- access => new ThreadHandle(int.Parse(listThreads.SelectedItems[0].Text), (ThreadAccess)access)
+ (access) => new ThreadHandle(int.Parse(listThreads.SelectedItems[0].Text), (ThreadAccess)access)
),
"Thread " + listThreads.SelectedItems[0].Text,
NativeTypeFactory.GetAccessEntries(NativeTypeFactory.ObjectType.Thread)
@@ -954,13 +1030,18 @@ private void tokenThreadMenuItem_Click(object sender, EventArgs e)
{
try
{
- using (ThreadHandle thandle = new ThreadHandle(int.Parse(listThreads.SelectedItems[0].Text), Program.MinThreadQueryRights))
- using (TokenWindow tokForm = new TokenWindow(thandle))
+ using (ThreadHandle thandle = new ThreadHandle(
+ int.Parse(listThreads.SelectedItems[0].Text), Program.MinThreadQueryRights
+ ))
{
+ TokenWindow tokForm = new TokenWindow(thandle);
+
tokForm.Text = "Thread Token";
tokForm.ShowDialog();
}
}
+ catch (ObjectDisposedException)
+ { }
catch (Exception ex)
{
PhUtils.ShowException("Unable to view the thread token", ex);
@@ -1006,287 +1087,287 @@ private unsafe void analyzeWaitMenuItem_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
int tid = int.Parse(listThreads.SelectedItems[0].SubItems[0].Text);
- ProcessHandle phandle;
+ ProcessHandle phandle = null;
if ((_provider.ProcessAccess & (ProcessAccess.QueryInformation | ProcessAccess.VmRead)) != 0)
phandle = _provider.ProcessHandle;
else
phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation | ProcessAccess.VmRead);
- //ProcessHandle processDupHandle = new ProcessHandle(_pid, ProcessAccess.DupHandle);
+ ProcessHandle processDupHandle = new ProcessHandle(_pid, ProcessAccess.DupHandle);
bool found = false;
- using (ThreadHandle thandle = new ThreadHandle(tid, ThreadAccess.GetContext | ThreadAccess.SuspendResume))
+ using (var thandle = new ThreadHandle(tid, ThreadAccess.GetContext | ThreadAccess.SuspendResume))
{
IntPtr[] lastParams = new IntPtr[4];
- thandle.WalkStack(phandle, stackFrame =>
- {
- uint address = stackFrame.PcAddress.ToUInt32();
- string name = _provider.Symbols.GetSymbolFromAddress(address).ToLowerInvariant();
-
- if (string.IsNullOrEmpty(name))
+ thandle.WalkStack(phandle, (stackFrame) =>
{
- // dummy
- }
- else if (
- name.StartsWith("kernel32.dll!sleep", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
-
- sb.Append("Thread is sleeping. Timeout: " +
- stackFrame.Params[0].ToInt32().ToString() + " milliseconds");
- }
- else if (
- name.StartsWith("ntdll.dll!zwdelayexecution", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntdelayexecution", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
-
- //bool alertable = stackFrame.Params[0].ToInt32() != 0;
- IntPtr timeoutAddress = stackFrame.Params[1];
- long timeout;
-
- phandle.ReadMemory(timeoutAddress, &timeout, sizeof(long));
+ uint address = stackFrame.PcAddress.ToUInt32();
+ string name = _provider.Symbols.GetSymbolFromAddress(address).ToLowerInvariant();
- if (timeout < 0)
+ if (name == null)
{
- sb.Append("Thread is sleeping. Timeout: " +
- (new TimeSpan(-timeout)).TotalMilliseconds.ToString() + " milliseconds");
+ // dummy
}
- else
+ else if (
+ name.StartsWith("kernel32.dll!sleep")
+ )
{
- sb.AppendLine("Thread is sleeping. Timeout: " + (new DateTime(timeout)).ToString());
+ found = true;
+
+ sb.Append("Thread is sleeping. Timeout: " +
+ stackFrame.Params[0].ToInt32().ToString() + " milliseconds");
}
- }
- else if (
- name.StartsWith("ntdll.dll!zwdeviceiocontrolfile", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntdeviceiocontrolfile", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ else if (
+ name.StartsWith("ntdll.dll!zwdelayexecution") ||
+ name.StartsWith("ntdll.dll!ntdelayexecution")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
+ bool alertable = stackFrame.Params[0].ToInt32() != 0;
+ IntPtr timeoutAddress = stackFrame.Params[1];
+ long timeout;
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for an I/O control request:");
+ phandle.ReadMemory(timeoutAddress, &timeout, sizeof(long));
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!ntfscontrolfile", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwfscontrolfile", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ if (timeout < 0)
+ {
+ sb.Append("Thread is sleeping. Timeout: " +
+ (new TimeSpan(-timeout)).TotalMilliseconds.ToString() + " milliseconds");
+ }
+ else
+ {
+ sb.AppendLine("Thread is sleeping. Timeout: " + (new DateTime(timeout)).ToString());
+ }
+ }
+ else if (
+ name.StartsWith("ntdll.dll!zwdeviceiocontrolfile") ||
+ name.StartsWith("ntdll.dll!ntdeviceiocontrolfile")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
+ IntPtr handle = stackFrame.Params[0];
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for an FS control request:");
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for an I/O control request:");
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!ntqueryobject", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwqueryobject", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("ntdll.dll!ntfscontrolfile") ||
+ name.StartsWith("ntdll.dll!zwfscontrolfile")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
+ IntPtr handle = stackFrame.Params[0];
- // Use the KiFastSystemCallRet args if the handle we have is wrong.
- if (handle.ToInt32() % 2 != 0 || handle == IntPtr.Zero)
- handle = lastParams[1];
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for an FS control request:");
- sb.AppendLine("Thread " + tid.ToString() + " is querying an object (most likely a named pipe):");
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("ntdll.dll!ntqueryobject") ||
+ name.StartsWith("ntdll.dll!zwqueryobject")
+ )
+ {
+ found = true;
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!zwreadfile", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntreadfile", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwwritefile", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwritefile", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ IntPtr handle = stackFrame.Params[0];
- IntPtr handle = stackFrame.Params[0];
+ // Use the KiFastSystemCallRet args if the handle we have is wrong.
+ if (handle.ToInt32() % 2 != 0 || handle == IntPtr.Zero)
+ handle = lastParams[1];
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for a named pipe or a file:");
+ sb.AppendLine("Thread " + tid.ToString() + " is querying an object (most likely a named pipe):");
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!zwremoveiocompletion", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntremoveiocompletion", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("ntdll.dll!zwreadfile") ||
+ name.StartsWith("ntdll.dll!ntreadfile") ||
+ name.StartsWith("ntdll.dll!zwwritefile") ||
+ name.StartsWith("ntdll.dll!ntwritefile")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
+ IntPtr handle = stackFrame.Params[0];
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for an I/O completion object:");
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for a named pipe or a file:");
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!zwreplywaitreceiveport", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntreplywaitreceiveport", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwrequestwaitreplyport", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntrequestwaitreplyport", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwalpcsendwaitreceiveport", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntalpcsendwaitreceiveport", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("ntdll.dll!zwremoveiocompletion") ||
+ name.StartsWith("ntdll.dll!ntremoveiocompletion")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
+ IntPtr handle = stackFrame.Params[0];
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for a LPC port:");
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for an I/O completion object:");
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if
- (
- name.StartsWith("ntdll.dll!zwsethighwaitloweventpair", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntsethighwaitloweventpair", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwsetlowwaithigheventpair", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntsetlowwaithigheventpair", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwwaithigheventpair", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwaithigheventpair", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwwaitloweventpair", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwaitloweventpair", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("ntdll.dll!zwreplywaitreceiveport") ||
+ name.StartsWith("ntdll.dll!ntreplywaitreceiveport") ||
+ name.StartsWith("ntdll.dll!zwrequestwaitreplyport") ||
+ name.StartsWith("ntdll.dll!ntrequestwaitreplyport") ||
+ name.StartsWith("ntdll.dll!zwalpcsendwaitreceiveport") ||
+ name.StartsWith("ntdll.dll!ntalpcsendwaitreceiveport")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
+ IntPtr handle = stackFrame.Params[0];
- // Use the KiFastSystemCallRet args if the handle we have is wrong.
- if (handle.ToInt32() % 2 != 0)
- handle = lastParams[1];
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for a LPC port:");
- sb.AppendLine("Thread " + tid.ToString() + " is waiting (" + name + ") for an event pair:");
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if
+ (
+ name.StartsWith("ntdll.dll!zwsethighwaitloweventpair") ||
+ name.StartsWith("ntdll.dll!ntsethighwaitloweventpair") ||
+ name.StartsWith("ntdll.dll!zwsetlowwaithigheventpair") ||
+ name.StartsWith("ntdll.dll!ntsetlowwaithigheventpair") ||
+ name.StartsWith("ntdll.dll!zwwaithigheventpair") ||
+ name.StartsWith("ntdll.dll!ntwaithigheventpair") ||
+ name.StartsWith("ntdll.dll!zwwaitloweventpair") ||
+ name.StartsWith("ntdll.dll!ntwaitloweventpair")
+ )
+ {
+ found = true;
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("user32.dll!ntusergetmessage", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("user32.dll!ntuserwaitmessage", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ IntPtr handle = stackFrame.Params[0];
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for a USER message.");
- }
- else if (
- name.StartsWith("ntdll.dll!zwwaitfordebugevent", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwaitfordebugevent", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ // Use the KiFastSystemCallRet args if the handle we have is wrong.
+ if (handle.ToInt32() % 2 != 0)
+ handle = lastParams[1];
- IntPtr handle = stackFrame.Params[0];
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting (" + name + ") for an event pair:");
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for a debug event:");
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("user32.dll!ntusergetmessage") ||
+ name.StartsWith("user32.dll!ntuserwaitmessage")
+ )
+ {
+ found = true;
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!zwwaitforkeyedevent", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwaitforkeyedevent", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!zwreleasekeyedevent", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntreleasekeyedevent", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for a USER message.");
+ }
+ else if (
+ name.StartsWith("ntdll.dll!zwwaitfordebugevent") ||
+ name.StartsWith("ntdll.dll!ntwaitfordebugevent")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
- IntPtr key = stackFrame.Params[1];
+ IntPtr handle = stackFrame.Params[0];
- sb.AppendLine("Thread " + tid.ToString() +
- " is waiting (" + name + ") for a keyed event (key 0x" +
- key.ToString("x") + "):");
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for a debug event:");
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!zwwaitformultipleobjects", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwaitformultipleobjects", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("kernel32.dll!waitformultipleobjects", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("ntdll.dll!zwwaitforkeyedevent") ||
+ name.StartsWith("ntdll.dll!ntwaitforkeyedevent") ||
+ name.StartsWith("ntdll.dll!zwreleasekeyedevent") ||
+ name.StartsWith("ntdll.dll!ntreleasekeyedevent")
+ )
+ {
+ found = true;
- int handleCount = stackFrame.Params[0].ToInt32();
- IntPtr handleAddress = stackFrame.Params[1];
- WaitType waitType = (WaitType)stackFrame.Params[2].ToInt32();
- bool alertable = stackFrame.Params[3].ToInt32() != 0;
+ IntPtr handle = stackFrame.Params[0];
+ IntPtr key = stackFrame.Params[1];
- // use the KiFastSystemCallRet args if we have the wrong args
- if (handleCount > 64)
- {
- handleCount = lastParams[1].ToInt32();
- handleAddress = lastParams[2];
- waitType = (WaitType)lastParams[3].ToInt32();
+ sb.AppendLine("Thread " + tid.ToString() +
+ " is waiting (" + name + ") for a keyed event (key 0x" +
+ key.ToString("x") + "):");
+
+ sb.AppendLine(this.GetHandleString(_pid, handle));
}
+ else if (
+ name.StartsWith("ntdll.dll!zwwaitformultipleobjects") ||
+ name.StartsWith("ntdll.dll!ntwaitformultipleobjects") ||
+ name.StartsWith("kernel32.dll!waitformultipleobjects")
+ )
+ {
+ found = true;
- IntPtr* handles = stackalloc IntPtr[handleCount];
+ int handleCount = stackFrame.Params[0].ToInt32();
+ IntPtr handleAddress = stackFrame.Params[1];
+ WaitType waitType = (WaitType)stackFrame.Params[2].ToInt32();
+ bool alertable = stackFrame.Params[3].ToInt32() != 0;
- phandle.ReadMemory(handleAddress, handles, handleCount * IntPtr.Size);
+ // use the KiFastSystemCallRet args if we have the wrong args
+ if (handleCount > 64)
+ {
+ handleCount = lastParams[1].ToInt32();
+ handleAddress = lastParams[2];
+ waitType = (WaitType)lastParams[3].ToInt32();
+ }
- sb.AppendLine("Thread " + tid.ToString() +
- " is waiting (alertable: " + alertable.ToString() + ", wait type: " +
- waitType.ToString() + ") for:");
+ IntPtr* handles = stackalloc IntPtr[handleCount];
- for (int i = 0; i < handleCount; i++)
- {
- sb.AppendLine(this.GetHandleString(_pid, handles[i]));
+ phandle.ReadMemory(handleAddress, handles, handleCount * IntPtr.Size);
+
+ sb.AppendLine("Thread " + tid.ToString() +
+ " is waiting (alertable: " + alertable.ToString() + ", wait type: " +
+ waitType.ToString() + ") for:");
+
+ for (int i = 0; i < handleCount; i++)
+ {
+ sb.AppendLine(this.GetHandleString(_pid, handles[i]));
+ }
}
- }
- else if (
- name.StartsWith("ntdll.dll!zwwaitforsingleobject", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwaitforsingleobject", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("kernel32.dll!waitforsingleobject", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ else if (
+ name.StartsWith("ntdll.dll!zwwaitforsingleobject") ||
+ name.StartsWith("ntdll.dll!ntwaitforsingleobject") ||
+ name.StartsWith("kernel32.dll!waitforsingleobject")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
- bool alertable = stackFrame.Params[1].ToInt32() != 0;
+ IntPtr handle = stackFrame.Params[0];
+ bool alertable = stackFrame.Params[1].ToInt32() != 0;
- sb.AppendLine("Thread " + tid.ToString() +
- " is waiting (alertable: " + alertable.ToString() + ") for:");
+ sb.AppendLine("Thread " + tid.ToString() +
+ " is waiting (alertable: " + alertable.ToString() + ") for:");
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
- else if (
- name.StartsWith("ntdll.dll!zwwaitforworkviaworkerfactory", StringComparison.OrdinalIgnoreCase) ||
- name.StartsWith("ntdll.dll!ntwaitforworkviaworkerfactory", StringComparison.OrdinalIgnoreCase)
- )
- {
- found = true;
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
+ else if (
+ name.StartsWith("ntdll.dll!zwwaitforworkviaworkerfactory") ||
+ name.StartsWith("ntdll.dll!ntwaitforworkviaworkerfactory")
+ )
+ {
+ found = true;
- IntPtr handle = stackFrame.Params[0];
+ IntPtr handle = stackFrame.Params[0];
- sb.AppendLine("Thread " + tid.ToString() + " is waiting for work from a worker factory:");
+ sb.AppendLine("Thread " + tid.ToString() + " is waiting for work from a worker factory:");
- sb.AppendLine(this.GetHandleString(_pid, handle));
- }
+ sb.AppendLine(this.GetHandleString(_pid, handle));
+ }
- lastParams = stackFrame.Params;
+ lastParams = stackFrame.Params;
- return !found;
- });
+ return !found;
+ });
}
if (found)
{
- new InformationBox(sb.ToString()).ShowDialog();
+ ScratchpadWindow.Create(sb.ToString());
}
else
{
@@ -1366,7 +1447,7 @@ private void ioPriority3ThreadMenuItem_Click(object sender, EventArgs e)
private void selectAllThreadMenuItem_Click(object sender, EventArgs e)
{
- this.listThreads.Items.SelectAll();
+ Utils.SelectAll(listThreads.Items);
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/ThreadList.resx b/1.x/trunk/ProcessHacker/Components/ThreadList.resx
index b6e44613c..65a9bbfba 100644
--- a/1.x/trunk/ProcessHacker/Components/ThreadList.resx
+++ b/1.x/trunk/ProcessHacker/Components/ThreadList.resx
@@ -112,12 +112,15 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
125, 17
+
+ 17, 17
+
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/TimerProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/TimerProperties.Designer.cs
index 74840966a..d803079f0 100644
--- a/1.x/trunk/ProcessHacker/Components/TimerProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/TimerProperties.Designer.cs
@@ -50,7 +50,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 3);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(55, 13);
+ this.label1.Size = new System.Drawing.Size(51, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Signaled:";
//
@@ -69,7 +69,7 @@ private void InitializeComponent()
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 25);
this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(91, 13);
+ this.label3.Size = new System.Drawing.Size(86, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Time Remaining:";
this.label3.Visible = false;
@@ -79,7 +79,7 @@ private void InitializeComponent()
this.labelSignaled.AutoSize = true;
this.labelSignaled.Location = new System.Drawing.Point(98, 3);
this.labelSignaled.Name = "labelSignaled";
- this.labelSignaled.Size = new System.Drawing.Size(33, 13);
+ this.labelSignaled.Size = new System.Drawing.Size(32, 13);
this.labelSignaled.TabIndex = 1;
this.labelSignaled.Text = "False";
//
@@ -98,7 +98,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.labelSignaled);
this.Controls.Add(this.labelTimeRemaining);
diff --git a/1.x/trunk/ProcessHacker/Components/TimerProperties.cs b/1.x/trunk/ProcessHacker/Components/TimerProperties.cs
index a5b60295e..ad7164745 100644
--- a/1.x/trunk/ProcessHacker/Components/TimerProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/TimerProperties.cs
@@ -8,7 +8,7 @@ namespace ProcessHacker.Components
{
public partial class TimerProperties : UserControl
{
- private readonly TimerHandle _timerHandle;
+ private TimerHandle _timerHandle;
public TimerProperties(TimerHandle timerHandle)
{
@@ -24,7 +24,7 @@ private void UpdateInfo()
{
try
{
- var basicInfo = _timerHandle.BasicInformation;
+ var basicInfo = _timerHandle.GetBasicInformation();
labelSignaled.Text = basicInfo.TimerState.ToString();
labelTimeRemaining.Text = (new TimeSpan(-basicInfo.RemainingTime)).ToString();
diff --git a/1.x/trunk/ProcessHacker/Components/TimerProperties.resx b/1.x/trunk/ProcessHacker/Components/TimerProperties.resx
index bfd9c479b..3add4121b 100644
--- a/1.x/trunk/ProcessHacker/Components/TimerProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/TimerProperties.resx
@@ -112,12 +112,12 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/TmRmProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/TmRmProperties.Designer.cs
index 4316da35f..e022334d4 100644
--- a/1.x/trunk/ProcessHacker/Components/TmRmProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/TmRmProperties.Designer.cs
@@ -42,7 +42,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 9);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(69, 13);
+ this.label1.Size = new System.Drawing.Size(63, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Description:";
//
@@ -57,29 +57,28 @@ private void InitializeComponent()
//
// textDescription
//
- this.textDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textDescription.Location = new System.Drawing.Point(75, 6);
this.textDescription.Name = "textDescription";
this.textDescription.ReadOnly = true;
- this.textDescription.Size = new System.Drawing.Size(252, 22);
+ this.textDescription.Size = new System.Drawing.Size(252, 20);
this.textDescription.TabIndex = 1;
//
// textGuid
//
- this.textGuid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textGuid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textGuid.Location = new System.Drawing.Point(49, 32);
this.textGuid.Name = "textGuid";
this.textGuid.ReadOnly = true;
- this.textGuid.Size = new System.Drawing.Size(278, 22);
+ this.textGuid.Size = new System.Drawing.Size(278, 20);
this.textGuid.TabIndex = 1;
//
// TmRmProperties
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.textGuid);
this.Controls.Add(this.textDescription);
this.Controls.Add(this.label2);
diff --git a/1.x/trunk/ProcessHacker/Components/TmRmProperties.cs b/1.x/trunk/ProcessHacker/Components/TmRmProperties.cs
index a981cd548..20db152ad 100644
--- a/1.x/trunk/ProcessHacker/Components/TmRmProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/TmRmProperties.cs
@@ -1,4 +1,9 @@
using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Drawing;
+using System.Data;
+using System.Text;
using System.Windows.Forms;
using ProcessHacker.Native.Objects;
@@ -6,7 +11,7 @@ namespace ProcessHacker.Components
{
public partial class TmRmProperties : UserControl
{
- private readonly ResourceManagerHandle _rmHandle;
+ private ResourceManagerHandle _rmHandle;
public TmRmProperties(ResourceManagerHandle rmHandle)
{
@@ -22,8 +27,8 @@ private void UpdateInfo()
{
try
{
- textDescription.Text = _rmHandle.Description;
- textGuid.Text = _rmHandle.Guid.ToString("B");
+ textDescription.Text = _rmHandle.GetDescription();
+ textGuid.Text = _rmHandle.GetGuid().ToString("B");
}
catch (Exception ex)
{
diff --git a/1.x/trunk/ProcessHacker/Components/TmRmProperties.resx b/1.x/trunk/ProcessHacker/Components/TmRmProperties.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/TmRmProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/TmRmProperties.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/TmTmProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/TmTmProperties.Designer.cs
index e6bee1e3c..2dfb45364 100644
--- a/1.x/trunk/ProcessHacker/Components/TmTmProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/TmTmProperties.Designer.cs
@@ -48,12 +48,12 @@ private void InitializeComponent()
//
// textGuid
//
- this.textGuid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textGuid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textGuid.Location = new System.Drawing.Point(49, 6);
this.textGuid.Name = "textGuid";
this.textGuid.ReadOnly = true;
- this.textGuid.Size = new System.Drawing.Size(244, 22);
+ this.textGuid.Size = new System.Drawing.Size(244, 20);
this.textGuid.TabIndex = 1;
//
// label2
@@ -61,25 +61,24 @@ private void InitializeComponent()
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 35);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(82, 13);
+ this.label2.Size = new System.Drawing.Size(78, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Log File Name:";
//
// textLogFileName
//
- this.textLogFileName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textLogFileName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textLogFileName.Location = new System.Drawing.Point(90, 32);
this.textLogFileName.Name = "textLogFileName";
this.textLogFileName.ReadOnly = true;
- this.textLogFileName.Size = new System.Drawing.Size(203, 22);
+ this.textLogFileName.Size = new System.Drawing.Size(203, 20);
this.textLogFileName.TabIndex = 1;
//
// TmTmProperties
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.textLogFileName);
this.Controls.Add(this.textGuid);
this.Controls.Add(this.label2);
diff --git a/1.x/trunk/ProcessHacker/Components/TmTmProperties.cs b/1.x/trunk/ProcessHacker/Components/TmTmProperties.cs
index 117196aa9..6b6ad3bc7 100644
--- a/1.x/trunk/ProcessHacker/Components/TmTmProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/TmTmProperties.cs
@@ -1,4 +1,9 @@
using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Drawing;
+using System.Data;
+using System.Text;
using System.Windows.Forms;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native;
@@ -7,7 +12,7 @@ namespace ProcessHacker.Components
{
public partial class TmTmProperties : UserControl
{
- private readonly TmHandle _tmHandle;
+ private TmHandle _tmHandle;
public TmTmProperties(TmHandle tmHandle)
{
@@ -23,8 +28,8 @@ private void UpdateInfo()
{
try
{
- textGuid.Text = _tmHandle.BasicInformation.TmIdentity.ToString("B");
- textLogFileName.Text = FileUtils.GetFileName(FileUtils.GetFileName(_tmHandle.LogFileName));
+ textGuid.Text = _tmHandle.GetBasicInformation().TmIdentity.ToString("B");
+ textLogFileName.Text = FileUtils.GetFileName(FileUtils.GetFileName(_tmHandle.GetLogFileName()));
}
catch (Exception ex)
{
diff --git a/1.x/trunk/ProcessHacker/Components/TmTmProperties.resx b/1.x/trunk/ProcessHacker/Components/TmTmProperties.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/TmTmProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/TmTmProperties.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/TokenGroupsList.Designer.cs b/1.x/trunk/ProcessHacker/Components/TokenGroupsList.Designer.cs
index ea9ca5c04..120f3f5d5 100644
--- a/1.x/trunk/ProcessHacker/Components/TokenGroupsList.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/TokenGroupsList.Designer.cs
@@ -28,9 +28,9 @@ protected override void Dispose(bool disposing)
///
private void InitializeComponent()
{
- this.listGroups = new ProcessHacker.Components.ExtendedListView();
- this.columnGroupName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnFlags = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.listGroups = new System.Windows.Forms.ListView();
+ this.columnGroupName = new System.Windows.Forms.ColumnHeader();
+ this.columnFlags = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// listGroups
@@ -40,12 +40,11 @@ private void InitializeComponent()
this.columnGroupName,
this.columnFlags});
this.listGroups.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listGroups.DoubleClickChecks = true;
this.listGroups.FullRowSelect = true;
this.listGroups.Location = new System.Drawing.Point(0, 0);
this.listGroups.Name = "listGroups";
this.listGroups.ShowItemToolTips = true;
- this.listGroups.Size = new System.Drawing.Size(416, 397);
+ this.listGroups.Size = new System.Drawing.Size(431, 397);
this.listGroups.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.listGroups.TabIndex = 4;
this.listGroups.UseCompatibleStateImageBehavior = false;
@@ -61,21 +60,20 @@ private void InitializeComponent()
this.columnFlags.Text = "Flags";
this.columnFlags.Width = 180;
//
- // TokenGroupsList
+ // TokenGroups
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.listGroups);
- this.Name = "TokenGroupsList";
- this.Size = new System.Drawing.Size(416, 397);
+ this.Name = "TokenGroups";
+ this.Size = new System.Drawing.Size(431, 397);
this.ResumeLayout(false);
}
#endregion
- private ExtendedListView listGroups;
+ private System.Windows.Forms.ListView listGroups;
private System.Windows.Forms.ColumnHeader columnGroupName;
private System.Windows.Forms.ColumnHeader columnFlags;
}
diff --git a/1.x/trunk/ProcessHacker/Components/TokenGroupsList.cs b/1.x/trunk/ProcessHacker/Components/TokenGroupsList.cs
index 9c3acb4e9..2af0f40cd 100644
--- a/1.x/trunk/ProcessHacker/Components/TokenGroupsList.cs
+++ b/1.x/trunk/ProcessHacker/Components/TokenGroupsList.cs
@@ -38,17 +38,18 @@ public TokenGroupsList(Sid[] groups)
if (groups != null)
{
- foreach (Sid t in groups)
+ for (int i = 0; i < groups.Length; i++)
{
- ListViewItem item = this.listGroups.Items.Add(new ListViewItem());
+ ListViewItem item = listGroups.Items.Add(new ListViewItem());
- item.Text = t.GetFullName(Settings.Instance.ShowAccountDomains);
- item.BackColor = this.GetAttributeColor(t.Attributes);
- item.SubItems.Add(new ListViewItem.ListViewSubItem(item, this.GetAttributeString(t.Attributes)));
+ item.Text = groups[i].GetFullName(Settings.Instance.ShowAccountDomains);
+ item.BackColor = GetAttributeColor(groups[i].Attributes);
+ item.SubItems.Add(new ListViewItem.ListViewSubItem(item, GetAttributeString(groups[i].Attributes)));
}
}
listGroups.ListViewItemSorter = new SortedListViewComparer(listGroups);
+ listGroups.SetDoubleBuffered(true);
listGroups.ContextMenu = listGroups.GetCopyMenu();
ColumnSettings.LoadSettings(Settings.Instance.GroupListColumns, listGroups);
listGroups.AddShortcuts();
@@ -70,17 +71,16 @@ public void DumpAddGroup(string name, SidAttributes attributes)
private string GetAttributeString(SidAttributes Attributes)
{
- string text = string.Empty;
+ string text = "";
if ((Attributes & SidAttributes.Integrity) != 0)
{
if ((Attributes & SidAttributes.IntegrityEnabled) != 0)
return "Integrity";
-
- return "Integrity (Disabled)";
+ else
+ return "Integrity (Disabled)";
}
-
- if ((Attributes & SidAttributes.LogonId) != 0)
+ else if ((Attributes & SidAttributes.LogonId) != 0)
text = "Logon ID";
else if ((Attributes & SidAttributes.Mandatory) != 0)
text = "Mandatory";
@@ -93,11 +93,10 @@ private string GetAttributeString(SidAttributes Attributes)
if ((Attributes & SidAttributes.EnabledByDefault) != 0)
return text + " (Default Enabled)";
-
- if ((Attributes & SidAttributes.Enabled) != 0)
+ else if ((Attributes & SidAttributes.Enabled) != 0)
return text;
-
- return text + " (Disabled)";
+ else
+ return text + " (Disabled)";
}
private Color GetAttributeColor(SidAttributes Attributes)
@@ -106,17 +105,16 @@ private Color GetAttributeColor(SidAttributes Attributes)
{
if ((Attributes & SidAttributes.IntegrityEnabled) == 0)
return Color.FromArgb(0xe0e0e0);
-
- return Color.White;
+ else
+ return Color.White;
}
if ((Attributes & SidAttributes.EnabledByDefault) != 0)
return Color.FromArgb(0xe0f0e0);
-
- if ((Attributes & SidAttributes.Enabled) != 0)
+ else if ((Attributes & SidAttributes.Enabled) != 0)
return Color.White;
-
- return Color.FromArgb(0xf0e0e0);
+ else
+ return Color.FromArgb(0xf0e0e0);
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Components/TokenGroupsList.resx b/1.x/trunk/ProcessHacker/Components/TokenGroupsList.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Components/TokenGroupsList.resx
+++ b/1.x/trunk/ProcessHacker/Components/TokenGroupsList.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/TokenProperties.Designer.cs b/1.x/trunk/ProcessHacker/Components/TokenProperties.Designer.cs
index 7af872ded..42dcc3850 100644
--- a/1.x/trunk/ProcessHacker/Components/TokenProperties.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Components/TokenProperties.Designer.cs
@@ -32,6 +32,7 @@ protected override void Dispose(bool disposing)
///
private void InitializeComponent()
{
+ this.components = new System.ComponentModel.Container();
this.tabControl = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
this.groupSource = new System.Windows.Forms.GroupBox();
@@ -71,10 +72,10 @@ private void InitializeComponent()
this.label4 = new System.Windows.Forms.Label();
this.tabGroups = new System.Windows.Forms.TabPage();
this.tabPrivileges = new System.Windows.Forms.TabPage();
- this.listPrivileges = new ProcessHacker.Components.ExtendedListView();
- this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnStatus = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnDesc = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
+ this.listPrivileges = new System.Windows.Forms.ListView();
+ this.columnName = new System.Windows.Forms.ColumnHeader();
+ this.columnStatus = new System.Windows.Forms.ColumnHeader();
+ this.columnDesc = new System.Windows.Forms.ColumnHeader();
this.enableMenuItem = new System.Windows.Forms.MenuItem();
this.disableMenuItem = new System.Windows.Forms.MenuItem();
this.removeMenuItem = new System.Windows.Forms.MenuItem();
@@ -82,12 +83,14 @@ private void InitializeComponent()
this.menuPrivileges = new System.Windows.Forms.ContextMenu();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.selectAllMenuItem = new System.Windows.Forms.MenuItem();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
this.tabControl.SuspendLayout();
this.tabGeneral.SuspendLayout();
this.groupSource.SuspendLayout();
this.groupToken.SuspendLayout();
this.tabAdvanced.SuspendLayout();
this.tabPrivileges.SuspendLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
// tabControl
@@ -100,7 +103,7 @@ private void InitializeComponent()
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
- this.tabControl.Size = new System.Drawing.Size(431, 433);
+ this.tabControl.Size = new System.Drawing.Size(575, 433);
this.tabControl.TabIndex = 3;
//
// tabGeneral
@@ -111,22 +114,22 @@ private void InitializeComponent()
this.tabGeneral.Location = new System.Drawing.Point(4, 22);
this.tabGeneral.Name = "tabGeneral";
this.tabGeneral.Padding = new System.Windows.Forms.Padding(3, 5, 3, 3);
- this.tabGeneral.Size = new System.Drawing.Size(423, 407);
+ this.tabGeneral.Size = new System.Drawing.Size(567, 407);
this.tabGeneral.TabIndex = 2;
this.tabGeneral.Text = "General";
this.tabGeneral.UseVisualStyleBackColor = true;
//
// groupSource
//
- this.groupSource.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupSource.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.groupSource.Controls.Add(this.label7);
this.groupSource.Controls.Add(this.label6);
this.groupSource.Controls.Add(this.textSourceName);
this.groupSource.Controls.Add(this.textSourceLUID);
this.groupSource.Location = new System.Drawing.Point(6, 247);
this.groupSource.Name = "groupSource";
- this.groupSource.Size = new System.Drawing.Size(411, 75);
+ this.groupSource.Size = new System.Drawing.Size(555, 75);
this.groupSource.TabIndex = 15;
this.groupSource.TabStop = false;
this.groupSource.Text = "Source";
@@ -136,7 +139,7 @@ private void InitializeComponent()
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(6, 48);
this.label7.Name = "label7";
- this.label7.Size = new System.Drawing.Size(34, 13);
+ this.label7.Size = new System.Drawing.Size(35, 13);
this.label7.TabIndex = 3;
this.label7.Text = "LUID:";
//
@@ -145,18 +148,18 @@ private void InitializeComponent()
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(6, 22);
this.label6.Name = "label6";
- this.label6.Size = new System.Drawing.Size(39, 13);
+ this.label6.Size = new System.Drawing.Size(38, 13);
this.label6.TabIndex = 2;
this.label6.Text = "Name:";
//
// textSourceName
//
- this.textSourceName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textSourceName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textSourceName.Location = new System.Drawing.Point(73, 19);
this.textSourceName.Name = "textSourceName";
this.textSourceName.ReadOnly = true;
- this.textSourceName.Size = new System.Drawing.Size(332, 22);
+ this.textSourceName.Size = new System.Drawing.Size(476, 20);
this.textSourceName.TabIndex = 1;
//
// textSourceLUID
@@ -164,13 +167,13 @@ private void InitializeComponent()
this.textSourceLUID.Location = new System.Drawing.Point(73, 45);
this.textSourceLUID.Name = "textSourceLUID";
this.textSourceLUID.ReadOnly = true;
- this.textSourceLUID.Size = new System.Drawing.Size(109, 22);
+ this.textSourceLUID.Size = new System.Drawing.Size(109, 20);
this.textSourceLUID.TabIndex = 4;
//
// groupToken
//
- this.groupToken.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupToken.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.groupToken.Controls.Add(this.buttonPermissions);
this.groupToken.Controls.Add(this.label9);
this.groupToken.Controls.Add(this.label1);
@@ -189,7 +192,7 @@ private void InitializeComponent()
this.groupToken.Controls.Add(this.textUserSID);
this.groupToken.Location = new System.Drawing.Point(6, 8);
this.groupToken.Name = "groupToken";
- this.groupToken.Size = new System.Drawing.Size(411, 233);
+ this.groupToken.Size = new System.Drawing.Size(555, 233);
this.groupToken.TabIndex = 14;
this.groupToken.TabStop = false;
this.groupToken.Text = "Token";
@@ -198,7 +201,7 @@ private void InitializeComponent()
//
this.buttonPermissions.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonPermissions.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.buttonPermissions.Location = new System.Drawing.Point(330, 201);
+ this.buttonPermissions.Location = new System.Drawing.Point(474, 201);
this.buttonPermissions.Name = "buttonPermissions";
this.buttonPermissions.Size = new System.Drawing.Size(75, 23);
this.buttonPermissions.TabIndex = 18;
@@ -211,7 +214,7 @@ private void InitializeComponent()
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(6, 100);
this.label9.Name = "label9";
- this.label9.Size = new System.Drawing.Size(83, 13);
+ this.label9.Size = new System.Drawing.Size(76, 13);
this.label9.TabIndex = 17;
this.label9.Text = "Primary Group:";
//
@@ -220,7 +223,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 22);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(33, 13);
+ this.label1.Size = new System.Drawing.Size(32, 13);
this.label1.TabIndex = 2;
this.label1.Text = "User:";
//
@@ -237,22 +240,22 @@ private void InitializeComponent()
//
// textPrimaryGroup
//
- this.textPrimaryGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textPrimaryGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textPrimaryGroup.Location = new System.Drawing.Point(88, 97);
this.textPrimaryGroup.Name = "textPrimaryGroup";
this.textPrimaryGroup.ReadOnly = true;
- this.textPrimaryGroup.Size = new System.Drawing.Size(317, 22);
+ this.textPrimaryGroup.Size = new System.Drawing.Size(461, 20);
this.textPrimaryGroup.TabIndex = 16;
//
// textUser
//
- this.textUser.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textUser.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textUser.Location = new System.Drawing.Point(88, 19);
this.textUser.Name = "textUser";
this.textUser.ReadOnly = true;
- this.textUser.Size = new System.Drawing.Size(317, 22);
+ this.textUser.Size = new System.Drawing.Size(461, 20);
this.textUser.TabIndex = 1;
//
// textElevated
@@ -260,7 +263,7 @@ private void InitializeComponent()
this.textElevated.Location = new System.Drawing.Point(88, 149);
this.textElevated.Name = "textElevated";
this.textElevated.ReadOnly = true;
- this.textElevated.Size = new System.Drawing.Size(109, 22);
+ this.textElevated.Size = new System.Drawing.Size(109, 20);
this.textElevated.TabIndex = 12;
//
// label8
@@ -268,18 +271,18 @@ private void InitializeComponent()
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(6, 74);
this.label8.Name = "label8";
- this.label8.Size = new System.Drawing.Size(45, 13);
+ this.label8.Size = new System.Drawing.Size(41, 13);
this.label8.TabIndex = 15;
this.label8.Text = "Owner:";
//
// textOwner
//
- this.textOwner.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textOwner.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textOwner.Location = new System.Drawing.Point(88, 71);
this.textOwner.Name = "textOwner";
this.textOwner.ReadOnly = true;
- this.textOwner.Size = new System.Drawing.Size(317, 22);
+ this.textOwner.Size = new System.Drawing.Size(461, 20);
this.textOwner.TabIndex = 14;
//
// label2
@@ -287,18 +290,18 @@ private void InitializeComponent()
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 126);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(63, 13);
+ this.label2.Size = new System.Drawing.Size(61, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Session ID:";
//
// textVirtualized
//
- this.textVirtualized.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textVirtualized.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textVirtualized.Location = new System.Drawing.Point(88, 175);
this.textVirtualized.Name = "textVirtualized";
this.textVirtualized.ReadOnly = true;
- this.textVirtualized.Size = new System.Drawing.Size(317, 22);
+ this.textVirtualized.Size = new System.Drawing.Size(461, 20);
this.textVirtualized.TabIndex = 11;
//
// textSessionID
@@ -306,7 +309,7 @@ private void InitializeComponent()
this.textSessionID.Location = new System.Drawing.Point(88, 123);
this.textSessionID.Name = "textSessionID";
this.textSessionID.ReadOnly = true;
- this.textSessionID.Size = new System.Drawing.Size(109, 22);
+ this.textSessionID.Size = new System.Drawing.Size(109, 20);
this.textSessionID.TabIndex = 4;
//
// labelVirtualization
@@ -314,7 +317,7 @@ private void InitializeComponent()
this.labelVirtualization.AutoSize = true;
this.labelVirtualization.Location = new System.Drawing.Point(6, 178);
this.labelVirtualization.Name = "labelVirtualization";
- this.labelVirtualization.Size = new System.Drawing.Size(79, 13);
+ this.labelVirtualization.Size = new System.Drawing.Size(69, 13);
this.labelVirtualization.TabIndex = 8;
this.labelVirtualization.Text = "Virtualization:";
//
@@ -332,18 +335,18 @@ private void InitializeComponent()
this.labelElevated.AutoSize = true;
this.labelElevated.Location = new System.Drawing.Point(6, 152);
this.labelElevated.Name = "labelElevated";
- this.labelElevated.Size = new System.Drawing.Size(53, 13);
+ this.labelElevated.Size = new System.Drawing.Size(52, 13);
this.labelElevated.TabIndex = 7;
this.labelElevated.Text = "Elevated:";
//
// textUserSID
//
- this.textUserSID.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textUserSID.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textUserSID.Location = new System.Drawing.Point(88, 45);
this.textUserSID.Name = "textUserSID";
this.textUserSID.ReadOnly = true;
- this.textUserSID.Size = new System.Drawing.Size(317, 22);
+ this.textUserSID.Size = new System.Drawing.Size(461, 20);
this.textUserSID.TabIndex = 6;
//
// tabAdvanced
@@ -363,7 +366,7 @@ private void InitializeComponent()
this.tabAdvanced.Location = new System.Drawing.Point(4, 22);
this.tabAdvanced.Name = "tabAdvanced";
this.tabAdvanced.Padding = new System.Windows.Forms.Padding(3);
- this.tabAdvanced.Size = new System.Drawing.Size(423, 407);
+ this.tabAdvanced.Size = new System.Drawing.Size(567, 407);
this.tabAdvanced.TabIndex = 3;
this.tabAdvanced.Text = "Advanced";
this.tabAdvanced.UseVisualStyleBackColor = true;
@@ -373,7 +376,7 @@ private void InitializeComponent()
this.textMemoryAvailable.Location = new System.Drawing.Point(118, 136);
this.textMemoryAvailable.Name = "textMemoryAvailable";
this.textMemoryAvailable.ReadOnly = true;
- this.textMemoryAvailable.Size = new System.Drawing.Size(284, 22);
+ this.textMemoryAvailable.Size = new System.Drawing.Size(191, 20);
this.textMemoryAvailable.TabIndex = 1;
//
// textMemoryUsed
@@ -381,7 +384,7 @@ private void InitializeComponent()
this.textMemoryUsed.Location = new System.Drawing.Point(118, 110);
this.textMemoryUsed.Name = "textMemoryUsed";
this.textMemoryUsed.ReadOnly = true;
- this.textMemoryUsed.Size = new System.Drawing.Size(284, 22);
+ this.textMemoryUsed.Size = new System.Drawing.Size(191, 20);
this.textMemoryUsed.TabIndex = 1;
//
// textAuthenticationId
@@ -389,7 +392,7 @@ private void InitializeComponent()
this.textAuthenticationId.Location = new System.Drawing.Point(118, 84);
this.textAuthenticationId.Name = "textAuthenticationId";
this.textAuthenticationId.ReadOnly = true;
- this.textAuthenticationId.Size = new System.Drawing.Size(284, 22);
+ this.textAuthenticationId.Size = new System.Drawing.Size(191, 20);
this.textAuthenticationId.TabIndex = 1;
//
// textTokenId
@@ -397,7 +400,7 @@ private void InitializeComponent()
this.textTokenId.Location = new System.Drawing.Point(118, 58);
this.textTokenId.Name = "textTokenId";
this.textTokenId.ReadOnly = true;
- this.textTokenId.Size = new System.Drawing.Size(284, 22);
+ this.textTokenId.Size = new System.Drawing.Size(191, 20);
this.textTokenId.TabIndex = 1;
//
// textImpersonationLevel
@@ -405,7 +408,7 @@ private void InitializeComponent()
this.textImpersonationLevel.Location = new System.Drawing.Point(118, 32);
this.textImpersonationLevel.Name = "textImpersonationLevel";
this.textImpersonationLevel.ReadOnly = true;
- this.textImpersonationLevel.Size = new System.Drawing.Size(284, 22);
+ this.textImpersonationLevel.Size = new System.Drawing.Size(191, 20);
this.textImpersonationLevel.TabIndex = 1;
//
// textTokenType
@@ -413,7 +416,7 @@ private void InitializeComponent()
this.textTokenType.Location = new System.Drawing.Point(118, 6);
this.textTokenType.Name = "textTokenType";
this.textTokenType.ReadOnly = true;
- this.textTokenType.Size = new System.Drawing.Size(284, 22);
+ this.textTokenType.Size = new System.Drawing.Size(191, 20);
this.textTokenType.TabIndex = 1;
//
// label13
@@ -421,7 +424,7 @@ private void InitializeComponent()
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(6, 139);
this.label13.Name = "label13";
- this.label13.Size = new System.Drawing.Size(100, 13);
+ this.label13.Size = new System.Drawing.Size(93, 13);
this.label13.TabIndex = 0;
this.label13.Text = "Memory Available:";
//
@@ -430,7 +433,7 @@ private void InitializeComponent()
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(6, 113);
this.label12.Name = "label12";
- this.label12.Size = new System.Drawing.Size(80, 13);
+ this.label12.Size = new System.Drawing.Size(75, 13);
this.label12.TabIndex = 0;
this.label12.Text = "Memory Used:";
//
@@ -439,7 +442,7 @@ private void InitializeComponent()
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(6, 87);
this.label11.Name = "label11";
- this.label11.Size = new System.Drawing.Size(114, 13);
+ this.label11.Size = new System.Drawing.Size(106, 13);
this.label11.TabIndex = 0;
this.label11.Text = "Authentication LUID:";
//
@@ -448,7 +451,7 @@ private void InitializeComponent()
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(6, 61);
this.label10.Name = "label10";
- this.label10.Size = new System.Drawing.Size(68, 13);
+ this.label10.Size = new System.Drawing.Size(69, 13);
this.label10.TabIndex = 0;
this.label10.Text = "Token LUID:";
//
@@ -457,7 +460,7 @@ private void InitializeComponent()
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(6, 35);
this.label5.Name = "label5";
- this.label5.Size = new System.Drawing.Size(113, 13);
+ this.label5.Size = new System.Drawing.Size(105, 13);
this.label5.TabIndex = 0;
this.label5.Text = "Impersonation Level:";
//
@@ -466,7 +469,7 @@ private void InitializeComponent()
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 9);
this.label4.Name = "label4";
- this.label4.Size = new System.Drawing.Size(33, 13);
+ this.label4.Size = new System.Drawing.Size(34, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Type:";
//
@@ -475,7 +478,7 @@ private void InitializeComponent()
this.tabGroups.Location = new System.Drawing.Point(4, 22);
this.tabGroups.Name = "tabGroups";
this.tabGroups.Padding = new System.Windows.Forms.Padding(3);
- this.tabGroups.Size = new System.Drawing.Size(423, 407);
+ this.tabGroups.Size = new System.Drawing.Size(567, 407);
this.tabGroups.TabIndex = 1;
this.tabGroups.Text = "Groups";
this.tabGroups.UseVisualStyleBackColor = true;
@@ -486,7 +489,7 @@ private void InitializeComponent()
this.tabPrivileges.Location = new System.Drawing.Point(4, 22);
this.tabPrivileges.Name = "tabPrivileges";
this.tabPrivileges.Padding = new System.Windows.Forms.Padding(3);
- this.tabPrivileges.Size = new System.Drawing.Size(423, 407);
+ this.tabPrivileges.Size = new System.Drawing.Size(567, 407);
this.tabPrivileges.TabIndex = 0;
this.tabPrivileges.Text = "Privileges";
this.tabPrivileges.UseVisualStyleBackColor = true;
@@ -499,12 +502,11 @@ private void InitializeComponent()
this.columnStatus,
this.columnDesc});
this.listPrivileges.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listPrivileges.DoubleClickChecks = true;
this.listPrivileges.FullRowSelect = true;
this.listPrivileges.Location = new System.Drawing.Point(3, 3);
this.listPrivileges.Name = "listPrivileges";
this.listPrivileges.ShowItemToolTips = true;
- this.listPrivileges.Size = new System.Drawing.Size(417, 401);
+ this.listPrivileges.Size = new System.Drawing.Size(561, 401);
this.listPrivileges.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.listPrivileges.TabIndex = 0;
this.listPrivileges.UseCompatibleStateImageBehavior = false;
@@ -527,24 +529,28 @@ private void InitializeComponent()
//
// enableMenuItem
//
+ this.vistaMenu.SetImage(this.enableMenuItem, global::ProcessHacker.Properties.Resources.tick);
this.enableMenuItem.Index = 0;
this.enableMenuItem.Text = "&Enable";
this.enableMenuItem.Click += new System.EventHandler(this.enableMenuItem_Click);
//
// disableMenuItem
//
+ this.vistaMenu.SetImage(this.disableMenuItem, global::ProcessHacker.Properties.Resources.cross);
this.disableMenuItem.Index = 1;
this.disableMenuItem.Text = "&Disable";
this.disableMenuItem.Click += new System.EventHandler(this.disableMenuItem_Click);
//
// removeMenuItem
//
+ this.vistaMenu.SetImage(this.removeMenuItem, global::ProcessHacker.Properties.Resources.delete);
this.removeMenuItem.Index = 2;
this.removeMenuItem.Text = "&Remove";
this.removeMenuItem.Click += new System.EventHandler(this.removeMenuItem_Click);
//
// copyMenuItem
//
+ this.vistaMenu.SetImage(this.copyMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyMenuItem.Index = 4;
this.copyMenuItem.Text = "&Copy";
//
@@ -570,14 +576,18 @@ private void InitializeComponent()
this.selectAllMenuItem.Text = "Select &All";
this.selectAllMenuItem.Click += new System.EventHandler(this.selectAllMenuItem_Click);
//
+ // vistaMenu
+ //
+ this.vistaMenu.ContainerControl = this;
+ this.vistaMenu.DelaySetImageCalls = false;
+ //
// TokenProperties
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.tabControl);
this.Name = "TokenProperties";
- this.Size = new System.Drawing.Size(431, 433);
+ this.Size = new System.Drawing.Size(575, 433);
this.tabControl.ResumeLayout(false);
this.tabGeneral.ResumeLayout(false);
this.groupSource.ResumeLayout(false);
@@ -587,6 +597,7 @@ private void InitializeComponent()
this.tabAdvanced.ResumeLayout(false);
this.tabAdvanced.PerformLayout();
this.tabPrivileges.ResumeLayout(false);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
}
@@ -601,10 +612,11 @@ private void InitializeComponent()
private System.Windows.Forms.TextBox textUser;
private System.Windows.Forms.TabPage tabGroups;
private System.Windows.Forms.TabPage tabPrivileges;
- private ExtendedListView listPrivileges;
+ private System.Windows.Forms.ListView listPrivileges;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ColumnHeader columnStatus;
private System.Windows.Forms.ColumnHeader columnDesc;
+ private wyDay.Controls.VistaMenu vistaMenu;
private System.Windows.Forms.MenuItem enableMenuItem;
private System.Windows.Forms.MenuItem disableMenuItem;
private System.Windows.Forms.MenuItem removeMenuItem;
diff --git a/1.x/trunk/ProcessHacker/Components/TokenProperties.cs b/1.x/trunk/ProcessHacker/Components/TokenProperties.cs
index c7cb9dcef..1cbd6e191 100644
--- a/1.x/trunk/ProcessHacker/Components/TokenProperties.cs
+++ b/1.x/trunk/ProcessHacker/Components/TokenProperties.cs
@@ -31,19 +31,19 @@
using ProcessHacker.Native.Security;
using ProcessHacker.Native.Security.AccessControl;
using ProcessHacker.UI;
-using ProcessHacker.Api;
namespace ProcessHacker.Components
{
- public partial class TokenProperties : ProcessPropertySheetPage
+ public partial class TokenProperties : UserControl
{
- private readonly IWithToken _object;
+ private IWithToken _object;
private TokenGroupsList _groups;
public TokenProperties(IWithToken obj)
{
InitializeComponent();
+ listPrivileges.SetDoubleBuffered(true);
listPrivileges.ListViewItemSorter = new SortedListViewComparer(listPrivileges);
GenericViewMenu.AddMenuItems(copyMenuItem.MenuItems, listPrivileges, null);
listPrivileges.ContextMenu = menuPrivileges;
@@ -60,10 +60,10 @@ public TokenProperties(IWithToken obj)
// "General"
try
{
- textUser.Text = thandle.User.GetFullName(true);
- textUserSID.Text = thandle.User.StringSid;
- textOwner.Text = thandle.Owner.GetFullName(true);
- textPrimaryGroup.Text = thandle.PrimaryGroup.GetFullName(true);
+ textUser.Text = thandle.GetUser().GetFullName(true);
+ textUserSID.Text = thandle.GetUser().StringSid;
+ textOwner.Text = thandle.GetOwner().GetFullName(true);
+ textPrimaryGroup.Text = thandle.GetPrimaryGroup().GetFullName(true);
}
catch (Exception ex)
{
@@ -72,7 +72,7 @@ public TokenProperties(IWithToken obj)
try
{
- textSessionID.Text = thandle.SessionId.ToString();
+ textSessionID.Text = thandle.GetSessionId().ToString();
}
catch (Exception ex)
{
@@ -81,20 +81,14 @@ public TokenProperties(IWithToken obj)
try
{
- TokenElevationType type = thandle.ElevationType;
-
- switch (type)
- {
- case TokenElevationType.Default:
- this.textElevated.Text = "N/A";
- break;
- case TokenElevationType.Full:
- this.textElevated.Text = "True";
- break;
- case TokenElevationType.Limited:
- this.textElevated.Text = "False";
- break;
- }
+ var type = thandle.GetElevationType();
+
+ if (type == TokenElevationType.Default)
+ textElevated.Text = "N/A";
+ else if (type == TokenElevationType.Full)
+ textElevated.Text = "True";
+ else if (type == TokenElevationType.Limited)
+ textElevated.Text = "False";
}
catch (Exception ex)
{
@@ -106,7 +100,7 @@ public TokenProperties(IWithToken obj)
{
try
{
- TokenHandle linkedToken = thandle.LinkedToken;
+ TokenHandle linkedToken = thandle.GetLinkedToken();
if (linkedToken != null)
linkedToken.Dispose();
@@ -125,8 +119,8 @@ public TokenProperties(IWithToken obj)
try
{
- bool virtAllowed = thandle.IsVirtualizationAllowed;
- bool virtEnabled = thandle.IsVirtualizationEnabled;
+ bool virtAllowed = thandle.IsVirtualizationAllowed();
+ bool virtEnabled = thandle.IsVirtualizationEnabled();
if (virtEnabled)
textVirtualized.Text = "Enabled";
@@ -144,7 +138,7 @@ public TokenProperties(IWithToken obj)
{
using (TokenHandle tokenSource = _object.GetToken(TokenAccess.QuerySource))
{
- var source = tokenSource.Source;
+ var source = tokenSource.GetSource();
textSourceName.Text = source.SourceName.TrimEnd('\0', '\r', '\n', ' ');
@@ -161,7 +155,7 @@ public TokenProperties(IWithToken obj)
// "Advanced"
try
{
- var statistics = thandle.Statistics;
+ var statistics = thandle.GetStatistics();
textTokenType.Text = statistics.TokenType.ToString();
textImpersonationLevel.Text = statistics.ImpersonationLevel.ToString();
@@ -177,7 +171,7 @@ public TokenProperties(IWithToken obj)
try
{
- Sid[] groups = thandle.Groups;
+ var groups = thandle.GetGroups();
_groups = new TokenGroupsList(groups);
@@ -194,11 +188,11 @@ public TokenProperties(IWithToken obj)
try
{
- var privileges = thandle.Privileges;
+ var privileges = thandle.GetPrivileges();
- foreach (Privilege t in privileges)
+ for (int i = 0; i < privileges.Length; i++)
{
- this.AddPrivilege(t);
+ this.AddPrivilege(privileges[i]);
}
}
catch (Exception ex)
@@ -211,10 +205,9 @@ public TokenProperties(IWithToken obj)
{
tabControl.Visible = false;
- Label errorMessage = new Label
- {
- Text = ex.Message
- };
+ Label errorMessage = new Label();
+
+ errorMessage.Text = ex.Message;
this.Padding = new Padding(15, 10, 0, 0);
this.Controls.Add(errorMessage);
@@ -224,10 +217,10 @@ public TokenProperties(IWithToken obj)
{
labelElevated.Enabled = false;
textElevated.Enabled = false;
- textElevated.Text = string.Empty;
+ textElevated.Text = "";
labelVirtualization.Enabled = false;
textVirtualized.Enabled = false;
- textVirtualized.Text = string.Empty;
+ textVirtualized.Text = "";
}
if (tabControl.TabPages[Settings.Instance.TokenWindowTab] != null)
@@ -257,10 +250,8 @@ public void DumpInitialize()
buttonPermissions.Visible = false;
listPrivileges.ContextMenu = listPrivileges.GetCopyMenu();
- _groups = new TokenGroupsList(null)
- {
- Dock = DockStyle.Fill
- };
+ _groups = new TokenGroupsList(null);
+ _groups.Dock = DockStyle.Fill;
tabGroups.Controls.Add(_groups);
}
@@ -343,35 +334,31 @@ private string GetAttributeString(SePrivilegeAttributes Attributes)
{
if ((Attributes & SePrivilegeAttributes.EnabledByDefault) != 0)
return "Default Enabled";
-
- if ((Attributes & SePrivilegeAttributes.Enabled) != 0)
+ else if ((Attributes & SePrivilegeAttributes.Enabled) != 0)
return "Enabled";
-
- if (Attributes == SePrivilegeAttributes.Disabled)
+ else if (Attributes == SePrivilegeAttributes.Disabled)
return "Disabled";
-
- return "Unknown";
+ else
+ return "Unknown";
}
private Color GetAttributeColor(SePrivilegeAttributes Attributes)
{
if ((Attributes & SePrivilegeAttributes.EnabledByDefault) != 0)
return Color.FromArgb(0xc0f0c0);
-
- if ((Attributes & SePrivilegeAttributes.Enabled) != 0)
+ else if ((Attributes & SePrivilegeAttributes.Enabled) != 0)
return Color.FromArgb(0xe0f0e0);
-
- if (Attributes == SePrivilegeAttributes.Disabled)
+ else if (Attributes == SePrivilegeAttributes.Disabled)
return Color.FromArgb(0xf0e0e0);
-
- return Color.White;
+ else
+ return Color.White;
}
private void menuPrivileges_Popup(object sender, EventArgs e)
{
if (listPrivileges.SelectedItems.Count == 0)
{
- //menuPrivileges.DisableAll();
+ menuPrivileges.DisableAll();
}
else
{
@@ -481,14 +468,14 @@ private void removeMenuItem_Click(object sender, EventArgs e)
private void selectAllMenuItem_Click(object sender, EventArgs e)
{
- this.listPrivileges.Items.SelectAll();
+ Utils.SelectAll(listPrivileges.Items);
}
private void buttonLinkedToken_Click(object sender, EventArgs e)
{
- using (TokenHandle thandle = _object.GetToken(TokenAccess.Query))
+ using (var thandle = _object.GetToken(TokenAccess.Query))
{
- TokenWithLinkedToken token = new TokenWithLinkedToken(thandle);
+ var token = new TokenWithLinkedToken(thandle);
TokenWindow window = new TokenWindow(token);
window.ShowDialog();
@@ -501,7 +488,7 @@ private void buttonPermissions_Click(object sender, EventArgs e)
{
SecurityEditor.EditSecurity(
this,
- SecurityEditor.GetSecurableWrapper(access => _object.GetToken((TokenAccess)access)),
+ SecurityEditor.GetSecurableWrapper((access) => _object.GetToken((TokenAccess)access)),
"Token",
NativeTypeFactory.GetAccessEntries(NativeTypeFactory.ObjectType.Token)
);
diff --git a/1.x/trunk/ProcessHacker/Components/TokenProperties.resx b/1.x/trunk/ProcessHacker/Components/TokenProperties.resx
index 802907d2f..0bae7478e 100644
--- a/1.x/trunk/ProcessHacker/Components/TokenProperties.resx
+++ b/1.x/trunk/ProcessHacker/Components/TokenProperties.resx
@@ -112,12 +112,15 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
+ 17, 17
+
+
125, 17
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/ToolStripEx.cs b/1.x/trunk/ProcessHacker/Components/ToolStripEx.cs
deleted file mode 100644
index 6a0907c20..000000000
--- a/1.x/trunk/ProcessHacker/Components/ToolStripEx.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System.Windows.Forms;
-using ProcessHacker.Common;
-
-namespace System
-{
- public class ToolStripEx : ToolStrip
- {
- private const uint WM_MOUSEACTIVATE = 0x21;
- private static readonly IntPtr MA_ACTIVATE = new IntPtr(1);
- private static readonly IntPtr MA_ACTIVATEANDEAT = new IntPtr(2);
- private const uint MA_NOACTIVATE = 3;
- private const uint MA_NOACTIVATEANDEAT = 4;
-
- private bool clickThrough = true;
-
- ///
- /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus.
- ///
- ///
- /// Default value is true, which is the same behavior provided by the base ToolStrip class.
- ///
- public bool ClickThrough
- {
- get { return this.clickThrough; }
- set { this.clickThrough = value; }
- }
-
- protected override void WndProc(ref Message m)
- {
- base.WndProc(ref m);
-
- if (this.clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == MA_ACTIVATEANDEAT)
- {
- m.Result = MA_ACTIVATE;
- }
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/Tracker.cs b/1.x/trunk/ProcessHacker/Components/Tracker.cs
deleted file mode 100644
index af4882b58..000000000
--- a/1.x/trunk/ProcessHacker/Components/Tracker.cs
+++ /dev/null
@@ -1,385 +0,0 @@
-using System;
-using ProcessHacker.Common;
-
-namespace ProcessHacker
-{
- using System.Windows.Forms;
- using System.ComponentModel;
- using System.Drawing;
-
- public class Tracker : Control
- {
- public Color DrawColor = Color.Empty;
-
- //SedondLine Maximum
- public int value2Max = 100;
-
- private int mover;
-
- public System.Collections.Generic.IList values;
- public System.Collections.Generic.IList values2;
-
- private int mValue;
- private int mMinimum;
- private int mMaximum = 100;
- private int mLower = 25;
- private int mUpper = 75;
-
- private int intDivision = 2;
- private int mGrid = 12;
-
- public bool UseSecondLine { get; set; }
-
- public Tracker()
- {
- this.SetStyle(ControlStyles.ResizeRedraw, true);
- this.SetStyle(ControlStyles.UserPaint, true);
- this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
- this.SetStyle(ControlStyles.DoubleBuffer, true);
-
- this.Draw();
- }
-
- [Category("Behavior"), DefaultValue(12), Description("The grid of Tracker.")]
- public int Grid
- {
- get { return mGrid; }
- set
- {
- if (value > 0)
- mGrid = value;
- }
- }
-
- [Category("Behavior"), DefaultValue(0), Description("The current value of Tracker, in the range specified by the Minimum and Maximum properties.")]
- public int Value
- {
- get { return this.mValue; }
- set
- {
- if (value > this.mMaximum)
- {
- this.mValue = this.mMaximum;
- }
- else if (value < this.mMinimum)
- {
- this.mValue = this.mMinimum;
- }
- else
- {
- this.mValue = value;
- }
- }
- }
-
- [Category("Behavior"), DefaultValue(0), Description("The lower bound of the range this Tracker is working with.")]
- public int Minimum
- {
- get { return mMinimum; }
- set
- {
- if (value > mLower)
- {
- mMinimum = mLower;
- }
- else
- {
- mMinimum = value;
- }
- this.Invalidate();
- }
- }
-
- [Category("Behavior"), DefaultValue(100), Description("The upper bound of the range this Tracker is working with.")]
- public int Maximum
- {
- get { return mMaximum; }
- set
- {
- if (value < mUpper)
- {
- mMaximum = mUpper;
- }
- else
- {
- mMaximum = value;
- }
-
- this.Invalidate();
- }
- }
-
- [Category("Behavior"), DefaultValue(75), Description("The upper value of the normal range.")]
- public int UpperRange
- {
- get { return mUpper; }
- set
- {
- if (value > mMaximum)
- {
- mUpper = mMaximum;
- }
- else if (value < mLower)
- {
- mUpper = mLower;
- }
- else
- {
- mUpper = value;
- }
- this.Invalidate();
- }
- }
-
- [Category("Behavior"), DefaultValue(25), Description("The lower value of the normal range.")]
- public int LowerRange
- {
- get { return mLower; }
- set
- {
- if (value > mUpper)
- {
- mLower = mUpper;
- }
- else if (value < mMinimum)
- {
- mLower = mMinimum;
- }
- else
- {
- mLower = value;
- }
- this.Invalidate();
- }
- }
-
- public void Draw()
- {
- if (this.mover >= this.mGrid - intDivision)
- {
- mover = 0;
- }
- else
- {
- mover += intDivision;
- }
-
- this.Refresh();
- }
-
- protected override void OnPaint(PaintEventArgs e)
- {
- e.Graphics.Clear(Color.Black);
- e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
-
- int width = this.Width;
- int height = this.Height;
-
- // draw grid
- using (Pen p = new Pen(Color.DarkGreen))
- {
- int pos;
-
- // X Axis
- for (int i = 0; i <= height / this.mGrid; i++)
- {
- pos = i * this.mGrid;
-
- e.Graphics.DrawLine(p, 0, pos, width, pos);
- }
- // Y Axis
- for (int i = 0; i <= width + 1 / this.mGrid; i++)
- {
- pos = i * this.mGrid - this.mover;
-
- e.Graphics.DrawLine(p, pos, 0, pos, height);
- }
- }
-
- if (this.values != null)
- {
- for (int i = 1; i <= this.values.Count - 1; i++)
- {
- int x = width - intDivision*(this.values.Count - i);
- int y = height*(this.Maximum - this.values[i])/(this.Maximum - this.Minimum);
-
- int xx = width - intDivision*(this.values.Count - i + 1);
- int yy = (height*(this.Maximum - this.values[i - 1])/(this.Maximum - this.Minimum));
-
- using (Pen p = new Pen(this.DrawColor))
- {
- p.Width = 2;
-
- using (SolidBrush b = new SolidBrush(Color.FromArgb(100, p.Color)))
- {
- // Fill in the area below the line.
- e.Graphics.FillPolygon(b, new[]
- {
- new Point(x, y),
- new Point(x + intDivision, yy),
- new Point(x + intDivision, height),
- new Point(x, height)
- });
-
- //draw first line
- e.Graphics.DrawLine(p, x, y, xx, yy);
- }
- }
- }
- }
-
-
- //todo: complete.
- if (this.UseSecondLine)
- {
- for (int i = 0; i <= this.values2.Count - 1; i++)
- {
- int x = width - intDivision*(values2.Count - i);
- int y = height*(value2Max - (int)values2[i])/(value2Max - this.Minimum);
-
- int xx = width - intDivision*(values2.Count - i + 1);
- int yy = (height*(value2Max - (int)values2[i - 1])/(value2Max - this.Minimum));
-
- using (Pen p = new Pen(Color.Pink))
- {
- // Fill in the area below the line.
- e.Graphics.FillPolygon(new SolidBrush(Color.FromArgb(100, p.Color)), new[]
- {
- new Point(x, y),
- new Point(x + intDivision, yy),
- new Point(x + intDivision, height),
- new Point(x, height)
- });
-
- //draw first line
- e.Graphics.DrawLine(p, x, y, xx, yy);
- }
- }
- }
-
- // Draw the text, if any.
- if (!string.IsNullOrEmpty(this.Text))
- {
- using (SolidBrush b = new SolidBrush(this._textBoxColor))
- {
- // Draw the background for the text.
- e.Graphics.FillRectangle(b, new Rectangle(this._boxPosition, this._boxSize));
- }
-
- // Draw the text.
- TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this._textPosition, _textColor);
- }
-
- //todo: Draw the Border?
- //ControlPaint.DrawBorder3D(e.Graphics, 0, 0, this.Width, this.Height, Border3DStyle.Sunken);
- }
-
- private Color _textBoxColor = Color.FromArgb(127, Color.Black);
- public Color TextBoxColor
- {
- get { return _textBoxColor; }
- set { _textBoxColor = value; }
- }
-
- private Color _textColor = Color.FromArgb(0, 255, 0);
- public Color TextColor
- {
- get { return _textColor; }
- set { _textColor = value; }
- }
-
- private Point _textPosition, _boxPosition;
- private Size _textSize, _boxSize;
-
- private Padding _textMargin = new Padding(3, 3, 3, 3);
- public Padding TextMargin
- {
- get { return _textMargin; }
- set { _textMargin = value; }
- }
-
- private Padding _textPadding = new Padding(3, 3, 3, 3);
- public Padding TextPadding
- {
- get { return _textPadding; }
- set { _textPadding = value; }
- }
-
- private ContentAlignment _textAlign = ContentAlignment.TopLeft;
- public ContentAlignment TextPosition
- {
- get { return _textAlign; }
- set { _textAlign = value; }
- }
-
- private string _text;
- public override string Text
- {
- get { return _text; }
- set
- {
- _text = value;
-
- _textSize = TextRenderer.MeasureText(this.Text, this.Font);
- _boxSize = new Size(_textSize.Width + _textPadding.Left + _textPadding.Right, _textSize.Height + _textPadding.Top + _textPadding.Bottom);
-
- // work out Y
- switch (_textAlign)
- {
- case ContentAlignment.BottomCenter:
- case ContentAlignment.BottomLeft:
- case ContentAlignment.BottomRight:
- {
- _boxPosition.Y = this.Size.Height - _boxSize.Height - _textMargin.Bottom;
- break;
- }
- case ContentAlignment.MiddleCenter:
- case ContentAlignment.MiddleLeft:
- case ContentAlignment.MiddleRight:
- {
- _boxPosition.Y = (this.Size.Height - _boxSize.Height) / 2;
- break;
- }
-
- case ContentAlignment.TopCenter:
- case ContentAlignment.TopLeft:
- case ContentAlignment.TopRight:
- {
- _boxPosition.Y = _textMargin.Top;
- break;
- }
- }
-
- // work out X
- switch (_textAlign)
- {
- case ContentAlignment.BottomLeft:
- case ContentAlignment.MiddleLeft:
- case ContentAlignment.TopLeft:
- {
- _boxPosition.X = _textMargin.Left;
- break;
- }
- case ContentAlignment.BottomCenter:
- case ContentAlignment.MiddleCenter:
- case ContentAlignment.TopCenter:
- {
- _boxPosition.X = (this.Size.Width - _boxSize.Width) / 2;
- break;
- }
- case ContentAlignment.BottomRight:
- case ContentAlignment.MiddleRight:
- case ContentAlignment.TopRight:
- {
- _boxPosition.X = this.Size.Width - _boxSize.Width - _textMargin.Right;
- break;
- }
- }
-
- _textPosition = new Point(_boxPosition.X + _textPadding.Left, _boxPosition.Y + _textPadding.Top);
- }
- }
-
-
- }
-}
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/PerformanceAnalyzer.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/PerformanceAnalyzer.cs
deleted file mode 100644
index 7d99ab48c..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/PerformanceAnalyzer.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Diagnostics;
-
-namespace Aga.Controls
-{
- ///
- /// Is used to analyze code performance
- ///
- public static class PerformanceAnalyzer
- {
- public class PerformanceInfo
- {
- public string Name { get; set; }
- public int Count { get; set; }
- public double TotalTime { get; set; }
-
- public Int64 Start { get; set; }
-
- public PerformanceInfo(string name)
- {
- this.Name = name;
- }
- }
-
- private static readonly Dictionary _performances = new Dictionary();
-
- public static IEnumerable Performances
- {
- get
- {
- return _performances.Values;
- }
- }
-
- [Conditional("DEBUG")]
- public static void Start(string pieceOfCode)
- {
- lock(_performances)
- {
- PerformanceInfo info;
-
- if (_performances.ContainsKey(pieceOfCode))
- info = _performances[pieceOfCode];
- else
- {
- info = new PerformanceInfo(pieceOfCode);
- _performances.Add(pieceOfCode, info);
- }
-
- info.Count++;
- info.Start = TimeCounter.GetStartValue();
- }
- }
-
- [Conditional("DEBUG")]
- public static void Finish(string pieceOfCode)
- {
- lock (_performances)
- {
- if (_performances.ContainsKey(pieceOfCode))
- {
- PerformanceInfo info = _performances[pieceOfCode];
- info.Count++;
- info.TotalTime += TimeCounter.Finish(info.Start);
- }
- }
- }
-
- public static void Reset()
- {
- _performances.Clear();
- }
-
- public static string GenerateReport()
- {
- return GenerateReport(0);
- }
-
- public static string GenerateReport(string mainPieceOfCode)
- {
- if (_performances.ContainsKey(mainPieceOfCode))
- return GenerateReport(_performances[mainPieceOfCode].TotalTime);
- else
- return GenerateReport(0);
- }
-
- public static string GenerateReport(double totalTime)
- {
- StringBuilder sb = new StringBuilder();
- int len = 0;
- foreach (PerformanceInfo info in Performances)
- len = Math.Max(info.Name.Length, len);
-
- sb.AppendLine("Name".PadRight(len) + " Count Total Time, ms Avg. Time, ms Percentage, %");
- sb.AppendLine("----------------------------------------------------------------------------------------------");
- foreach (PerformanceInfo info in Performances)
- {
- sb.Append(info.Name.PadRight(len));
- double p = 0;
- double avgt = 0;
- if (totalTime != 0)
- p = info.TotalTime / totalTime;
- if (info.Count > 0)
- avgt = info.TotalTime * 1000 / info.Count;
- string c = info.Count.ToString("0,0").PadRight(20);
- string tt = (info.TotalTime * 1000).ToString("0,0.00").PadRight(20);
- string t = avgt.ToString("0.0000").PadRight(20);
- string sp = (p * 100).ToString("###").PadRight(20);
- sb.AppendFormat(" " + c + tt + t + sp + "\n");
- }
- return sb.ToString();
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/TextHelper.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/TextHelper.cs
deleted file mode 100644
index 79f252391..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/TextHelper.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Windows.Forms;
-using System.Drawing;
-
-namespace Aga.Controls
-{
- public static class TextHelper
- {
- public static StringAlignment TranslateAligment(HorizontalAlignment aligment)
- {
- switch (aligment)
- {
- case HorizontalAlignment.Left:
- {
- return StringAlignment.Near;
- }
- case HorizontalAlignment.Right:
- {
- return StringAlignment.Far;
- }
- default:
- {
- return StringAlignment.Center;
- }
- }
- }
-
- public static TextFormatFlags TranslateAligmentToFlag(HorizontalAlignment aligment)
- {
- switch (aligment)
- {
- case HorizontalAlignment.Left:
- {
- return TextFormatFlags.Left;
- }
- case HorizontalAlignment.Right:
- {
- return TextFormatFlags.Right;
- }
- default:
- {
- return TextFormatFlags.HorizontalCenter;
- }
- }
- }
-
- public static TextFormatFlags TranslateTrimmingToFlag(StringTrimming trimming)
- {
- switch (trimming)
- {
- case StringTrimming.EllipsisCharacter:
- {
- return TextFormatFlags.EndEllipsis;
- }
- case StringTrimming.EllipsisPath:
- {
- return TextFormatFlags.PathEllipsis;
- }
- case StringTrimming.EllipsisWord:
- {
- return TextFormatFlags.WordEllipsis;
- }
- case StringTrimming.Word:
- {
- return TextFormatFlags.WordBreak;
- }
- default:
- {
- return TextFormatFlags.Default;
- }
- }
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/DrawContext.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/DrawContext.cs
deleted file mode 100644
index d3a352494..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/DrawContext.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System.Drawing;
-
-using Aga.Controls.Tree.NodeControls;
-
-namespace Aga.Controls.Tree
-{
- public struct DrawContext
- {
- public Graphics Graphics;
- public Rectangle Bounds;
- public Font Font;
- public DrawSelectionMode DrawSelection;
- public bool DrawFocus;
- public NodeControl CurrentEditorOwner;
- public bool Enabled;
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/IncrementalSearch.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/IncrementalSearch.cs
deleted file mode 100644
index 6010a1c67..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/IncrementalSearch.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Aga.Controls.Tree.NodeControls;
-
-namespace Aga.Controls.Tree
-{
- internal class IncrementalSearch
- {
- private const int SearchTimeout = 300; //end of incremental search timeot in msec
-
- private readonly TreeViewAdv _tree;
- private TreeNodeAdv _currentNode;
- private string _searchString = string.Empty;
- private DateTime _lastKeyPressed = DateTime.Now;
-
- public IncrementalSearch(TreeViewAdv tree)
- {
- _tree = tree;
- }
-
- public void Search(Char value)
- {
- if (!Char.IsControl(value))
- {
- Char ch = Char.ToLowerInvariant(value);
- DateTime dt = DateTime.Now;
- TimeSpan ts = dt - _lastKeyPressed;
- _lastKeyPressed = dt;
- if (ts.TotalMilliseconds < SearchTimeout)
- {
- if (_searchString == value.ToString())
- FirstCharSearch(ch);
- else
- ContinuousSearch(ch);
- }
- else
- {
- FirstCharSearch(ch);
- }
- }
- }
-
- private void ContinuousSearch(Char value)
- {
- if (value == ' ' && String.IsNullOrEmpty(_searchString))
- return; //Ingnore leading space
-
- _searchString += value;
- DoContinuousSearch();
- }
-
- private void FirstCharSearch(Char value)
- {
- if (value == ' ')
- return;
-
- _searchString = value.ToString();
- TreeNodeAdv node = null;
- if (_tree.SelectedNode != null)
- node = _tree.SelectedNode.NextVisibleNode;
- if (node == null)
- node = _tree.Root;
-
- foreach (string label in IterateNodeLabels(node))
- {
- if (label.StartsWith(_searchString))
- {
- _tree.SelectedNode = _currentNode;
- return;
- }
- }
- }
-
- public virtual void EndSearch()
- {
- _currentNode = null;
- _searchString = string.Empty;
- }
-
- protected IEnumerable IterateNodeLabels(TreeNodeAdv start)
- {
- _currentNode = start;
- while(_currentNode != null)
- {
- foreach (string label in GetNodeLabels(_currentNode))
- yield return label;
-
- _currentNode = _currentNode.NextVisibleNode;
- if (_currentNode == null)
- _currentNode = _tree.Root;
-
- if (start == _currentNode)
- break;
- }
- }
-
- private IEnumerable GetNodeLabels(TreeNodeAdv node)
- {
- foreach (NodeControl nc in _tree.NodeControls)
- {
- BindableControl bc = nc as BindableControl;
- if (bc != null && bc.IncrementalSearchEnabled)
- {
- object obj = bc.GetValue(node);
- if (obj != null)
- yield return obj.ToString().ToLowerInvariant();
- }
- }
- }
-
- private void DoContinuousSearch()
- {
- if (!string.IsNullOrEmpty(_searchString))
- {
- TreeNodeAdv node = null;
- if (_tree.SelectedNode != null)
- node = _tree.SelectedNode;
- if (node == null)
- node = _tree.Root.NextVisibleNode;
-
- if (!string.IsNullOrEmpty(_searchString))
- {
- foreach (string label in IterateNodeLabels(node))
- {
- if (label.StartsWith(_searchString))
- {
- _tree.SelectedNode = _currentNode;
- break;
- }
- }
- }
- }
- return;
- }
-
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/Input/ColumnState.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/Input/ColumnState.cs
deleted file mode 100644
index 676ef6e62..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/Input/ColumnState.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace Aga.Controls.Tree
-{
- internal abstract class ColumnState : InputState
- {
- public TreeColumn Column { get; private set; }
-
- protected ColumnState(TreeViewAdv tree, TreeColumn column)
- : base(tree)
- {
- this.Column = column;
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/Input/NormalInputState.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/Input/NormalInputState.cs
deleted file mode 100644
index 0c5a429ad..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/Input/NormalInputState.cs
+++ /dev/null
@@ -1,208 +0,0 @@
-using System;
-using System.Windows.Forms;
-
-namespace Aga.Controls.Tree
-{
- internal class NormalInputState : InputState
- {
- private bool _mouseDownFlag;
-
- public NormalInputState(TreeViewAdv tree) : base(tree)
- {
- }
-
- public override void KeyDown(KeyEventArgs args)
- {
- if (this.Tree.CurrentNode == null && this.Tree.Root.Nodes.Count > 0)
- this.Tree.CurrentNode = this.Tree.Root.Nodes[0];
-
- if (this.Tree.CurrentNode != null)
- {
- switch (args.KeyCode)
- {
- case Keys.Right:
- if (!this.Tree.CurrentNode.IsExpanded)
- {
- this.Tree.CurrentNode.IsExpanded = true;
- // by fliser
- this.Tree.FullUpdate();
- }
- else if (this.Tree.CurrentNode.Nodes.Count > 0)
- this.Tree.SelectedNode = this.Tree.CurrentNode.Nodes[0];
- args.Handled = true;
- break;
- case Keys.Left:
- if (this.Tree.CurrentNode.IsExpanded)
- {
- this.Tree.CurrentNode.IsExpanded = false;
- // by fliser
- this.Tree.FullUpdate();
- }
- else if (this.Tree.CurrentNode.Parent != this.Tree.Root)
- this.Tree.SelectedNode = this.Tree.CurrentNode.Parent;
- args.Handled = true;
- break;
- case Keys.Down:
- NavigateForward(1);
- args.Handled = true;
- break;
- case Keys.Up:
- NavigateBackward(1);
- args.Handled = true;
- break;
- case Keys.PageDown:
- NavigateForward(Math.Max(1, this.Tree.CurrentPageSize - 1));
- args.Handled = true;
- break;
- case Keys.PageUp:
- NavigateBackward(Math.Max(1, this.Tree.CurrentPageSize - 1));
- args.Handled = true;
- break;
- case Keys.Home:
- if (this.Tree.RowMap.Count > 0)
- FocusRow(this.Tree.RowMap[0]);
- args.Handled = true;
- break;
- case Keys.End:
- if (this.Tree.RowMap.Count > 0)
- FocusRow(this.Tree.RowMap[this.Tree.RowMap.Count-1]);
- args.Handled = true;
- break;
- case Keys.Subtract:
- this.Tree.CurrentNode.Collapse();
- // by fliser
- this.Tree.FullUpdate();
- args.Handled = true;
- args.SuppressKeyPress = true;
- break;
- case Keys.Add:
- this.Tree.CurrentNode.Expand();
- // by fliser
- this.Tree.FullUpdate();
- args.Handled = true;
- args.SuppressKeyPress = true;
- break;
- case Keys.Multiply:
- this.Tree.CurrentNode.ExpandAll();
- // by fliser
- this.Tree.FullUpdate();
- args.Handled = true;
- args.SuppressKeyPress = true;
- break;
- }
- }
- }
-
- public override void MouseDown(TreeNodeAdvMouseEventArgs args)
- {
- if (args.Node != null)
- {
- if (args.Button == MouseButtons.Left || args.Button == MouseButtons.Right)
- {
- this.Tree.BeginUpdate();
- try
- {
- this.Tree.CurrentNode = args.Node;
-
- if (args.Node.IsSelected)
- _mouseDownFlag = true;
- else
- {
- _mouseDownFlag = false;
- DoMouseOperation(args);
- }
- }
- finally
- {
- this.Tree.EndUpdate();
- }
- }
-
- }
- else
- {
- MouseDownAtEmptySpace(args);
- }
- }
-
- public override void MouseUp(TreeNodeAdvMouseEventArgs args)
- {
- if (_mouseDownFlag)
- {
- switch (args.Button)
- {
- case MouseButtons.Left:
- this.DoMouseOperation(args);
- break;
- case MouseButtons.Right:
- this.Tree.CurrentNode = args.Node;
- break;
- }
- }
- _mouseDownFlag = false;
- }
-
-
- private void NavigateBackward(int n)
- {
- int row = Math.Max(this.Tree.CurrentNode.Row - n, 0);
- if (row != this.Tree.CurrentNode.Row)
- FocusRow(this.Tree.RowMap[row]);
- }
-
- private void NavigateForward(int n)
- {
- int row = Math.Min(this.Tree.CurrentNode.Row + n, this.Tree.RowCount - 1);
- if (row != this.Tree.CurrentNode.Row)
- FocusRow(this.Tree.RowMap[row]);
- }
-
- protected virtual void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args)
- {
- this.Tree.ClearSelectionInternal();
- }
-
- protected virtual void FocusRow(TreeNodeAdv node)
- {
- this.Tree.SuspendSelectionEvent = true;
- try
- {
- this.Tree.ClearSelectionInternal();
- this.Tree.CurrentNode = node;
- this.Tree.SelectionStart = node;
- node.IsSelected = true;
- this.Tree.ScrollTo(node);
- }
- finally
- {
- this.Tree.SuspendSelectionEvent = false;
- }
- }
-
- protected bool CanSelect(TreeNodeAdv node)
- {
- if (this.Tree.SelectionMode == TreeSelectionMode.MultiSameParent)
- {
- return (this.Tree.SelectionStart == null || node.Parent == this.Tree.SelectionStart.Parent);
- }
-
- return true;
- }
-
- protected virtual void DoMouseOperation(TreeNodeAdvMouseEventArgs args)
- {
- this.Tree.SuspendSelectionEvent = true;
- try
- {
- this.Tree.ClearSelectionInternal();
- if (args.Node != null)
- args.Node.IsSelected = true;
- this.Tree.SelectionStart = args.Node;
- }
- finally
- {
- this.Tree.SuspendSelectionEvent = false;
- }
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControlInfo.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControlInfo.cs
deleted file mode 100644
index 25d772ea9..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControlInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using Aga.Controls.Tree.NodeControls;
-using System.Drawing;
-
-namespace Aga.Controls.Tree
-{
- public struct NodeControlInfo
- {
- public static readonly NodeControlInfo Empty = new NodeControlInfo(null, Rectangle.Empty, null);
-
- public NodeControl Control;
- public Rectangle Bounds;
- public TreeNodeAdv Node;
-
- public NodeControlInfo(NodeControl control, Rectangle bounds, TreeNodeAdv node) : this()
- {
- this.Control = control;
- this.Bounds = bounds;
- this.Node = node;
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/BindableControl.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/BindableControl.cs
deleted file mode 100644
index 2bc33036a..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/BindableControl.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-using System;
-using System.Reflection;
-using System.ComponentModel;
-
-namespace Aga.Controls.Tree.NodeControls
-{
- public abstract class BindableControl : NodeControl
- {
- private struct MemberAdapter
- {
- private object _obj;
- private PropertyInfo _pi;
- private FieldInfo _fi;
-
- public static readonly MemberAdapter Empty;
-
- public Type MemberType
- {
- get
- {
- if (_pi != null)
- return _pi.PropertyType;
-
- if (_fi != null)
- return _fi.FieldType;
-
- return null;
- }
- }
-
- public object Value
- {
- get
- {
- if (_pi != null && _pi.CanRead)
- return _pi.GetValue(_obj, null);
-
- if (_fi != null)
- return _fi.GetValue(_obj);
-
- return null;
- }
- set
- {
- if (_pi != null && _pi.CanWrite)
- _pi.SetValue(_obj, value, null);
- else if (_fi != null)
- _fi.SetValue(_obj, value);
- }
- }
-
- public MemberAdapter(object obj, PropertyInfo pi)
- {
- _obj = obj;
- _pi = pi;
- _fi = null;
- }
-
- public MemberAdapter(object obj, FieldInfo fi)
- {
- _obj = obj;
- _fi = fi;
- _pi = null;
- }
- }
-
- #region Properties
-
- [DefaultValue(false), Category("Data")]
- public bool VirtualMode { get; set; }
-
- protected BindableControl()
- {
- this.DataPropertyName = string.Empty;
- }
-
- [DefaultValue(""), Category("Data")]
- public string DataPropertyName { get; set; }
-
- [DefaultValue(false)]
- public bool IncrementalSearchEnabled { get; set; }
-
- #endregion
-
- public virtual object GetValue(TreeNodeAdv node)
- {
- if (this.VirtualMode)
- {
- NodeControlValueEventArgs args = new NodeControlValueEventArgs(node);
- OnValueNeeded(args);
- return args.Value;
- }
-
- return this.GetMemberAdapter(node).Value;
- }
-
- public virtual void SetValue(TreeNodeAdv node, object value)
- {
- if (this.VirtualMode)
- {
- NodeControlValueEventArgs args = new NodeControlValueEventArgs(node)
- {
- Value = value
- };
-
- OnValuePushed(args);
- }
- else
- {
- MemberAdapter ma = GetMemberAdapter(node);
-
- ma.Value = value;
- }
- }
-
- public Type GetPropertyType(TreeNodeAdv node)
- {
- return GetMemberAdapter(node).MemberType;
- }
-
- private MemberAdapter GetMemberAdapter(TreeNodeAdv node)
- {
-
- MemberAdapter adapter = MemberAdapter.Empty;
-
- if (node.Tag != null && !string.IsNullOrEmpty(this.DataPropertyName))
- {
- Type type = node.Tag.GetType();
- PropertyInfo pi = type.GetProperty(this.DataPropertyName);
-
- if (pi != null)
- {
- return new MemberAdapter(node.Tag, pi);
- }
-
- FieldInfo fi = type.GetField(this.DataPropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
-
- if (fi != null)
- return new MemberAdapter(node.Tag, fi);
- }
-
- return adapter;
- }
-
- public override string ToString()
- {
- if (string.IsNullOrEmpty(this.DataPropertyName))
- return GetType().Name;
-
- return this.GetType().Name + " (" + this.DataPropertyName + ")";
- }
-
- public event EventHandler ValueNeeded;
- private void OnValueNeeded(NodeControlValueEventArgs args)
- {
- if (this.ValueNeeded != null)
- this.ValueNeeded(this, args);
- }
-
- public event EventHandler ValuePushed;
- private void OnValuePushed(NodeControlValueEventArgs args)
- {
- if (this.ValuePushed != null)
- this.ValuePushed(this, args);
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/DrawEventArgs.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/DrawEventArgs.cs
deleted file mode 100644
index ce83c907b..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/DrawEventArgs.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.Drawing;
-
-namespace Aga.Controls.Tree.NodeControls
-{
- public class DrawEventArgs : NodeEventArgs
- {
- public DrawContext Context { get; private set; }
- public Brush BackgroundBrush { get; set; }
- public Font Font { get; set; }
- public Color TextColor { get; set; }
- public string Text { get; private set; }
-
- public DrawEventArgs(TreeNodeAdv node, DrawContext context, string text)
- : base(node)
- {
- this.Context = context;
- this.Text = text;
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/NodeControlValueEventArgs.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/NodeControlValueEventArgs.cs
deleted file mode 100644
index 64697454b..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/NodeControlValueEventArgs.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-namespace Aga.Controls.Tree.NodeControls
-{
- public class NodeControlValueEventArgs : NodeEventArgs
- {
- public object Value { get; set; }
-
- public NodeControlValueEventArgs(TreeNodeAdv node)
- :base(node)
- {
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/NodeEventArgs.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/NodeEventArgs.cs
deleted file mode 100644
index d5cd00d67..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/NodeControls/NodeEventArgs.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System;
-
-namespace Aga.Controls.Tree.NodeControls
-{
- public class NodeEventArgs : EventArgs
- {
- public TreeNodeAdv Node { get; private set; }
-
- public NodeEventArgs(TreeNodeAdv node)
- {
- this.Node = node;
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeNodeAdvMouseEventArgs.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeNodeAdvMouseEventArgs.cs
deleted file mode 100644
index f39706790..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeNodeAdvMouseEventArgs.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Windows.Forms;
-using System.Drawing;
-using Aga.Controls.Tree.NodeControls;
-
-namespace Aga.Controls.Tree
-{
- public class TreeNodeAdvMouseEventArgs : MouseEventArgs
- {
- public TreeNodeAdv Node { get; internal set; }
- public NodeControl Control { get; internal set; }
- public Point ViewLocation { get; internal set; }
- public Keys ModifierKeys { get; internal set; }
- public bool Handled { get; set; }
- public Rectangle ControlBounds { get; internal set; }
-
- public TreeNodeAdvMouseEventArgs(MouseEventArgs args)
- : base(args.Button, args.Clicks, args.X, args.Y, args.Delta)
- {
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdv.Draw.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdv.Draw.cs
deleted file mode 100644
index 451e7fa41..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdv.Draw.cs
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * Modified by wj32.
- */
-
-using System;
-using System.Windows.Forms;
-using System.Drawing;
-using System.Drawing.Drawing2D;
-
-namespace Aga.Controls.Tree
-{
- public sealed partial class TreeViewAdv
- {
- private void CreatePens()
- {
- CreateLinePen();
- }
-
- private void CreateLinePen()
- {
- _linePen = new Pen(_lineColor)
- {
- DashStyle = DashStyle.Dot
- };
- }
-
- protected override void OnPaint(PaintEventArgs e)
- {
-#if DEBUG
- this.BeginPerformanceCount();
-#endif
- DrawContext context = new DrawContext
- {
- Graphics = e.Graphics,
- Font = this.Font,
- Enabled = Enabled
- };
-
- this.DrawColumnHeaders(e.Graphics);
-
- int y = this.ColumnHeaderHeight;
-
- if (this.Columns.Count == 0 || e.ClipRectangle.Height <= y)
- return;
-
- int firstRowY = _rowLayout.GetRowBounds(this.FirstVisibleRow).Y;
-
- y -= firstRowY;
-
- e.Graphics.ResetTransform();
- e.Graphics.TranslateTransform(-OffsetX, y);
-
- Rectangle displayRect = e.ClipRectangle;
-
- for (int row = this.FirstVisibleRow; row < this.RowCount; row++)
- {
- Rectangle rowRect = _rowLayout.GetRowBounds(row);
-
- if (rowRect.Y + y > displayRect.Bottom)
- break;
-
- this.DrawRow(e, ref context, row, rowRect);
- }
-
- e.Graphics.ResetTransform();
-
- this.DrawScrollBarsBox(e.Graphics);
-
-#if DEBUG
- this.EndPerformanceCount(e);
-#endif
- }
-
- private void DrawRow(PaintEventArgs e, ref DrawContext context, int row, Rectangle rowRect)
- {
- TreeNodeAdv node = this.RowMap[row];
-
- context.DrawSelection = DrawSelectionMode.None;
- context.CurrentEditorOwner = _currentEditorOwner;
-
- bool focused = this.Focused;
-
- if (node.IsSelected && focused)
- {
- context.DrawSelection = DrawSelectionMode.Active;
- }
- else if (node.IsSelected && !focused && !this.HideSelection)
- {
- context.DrawSelection = DrawSelectionMode.Inactive;
- }
-
- Rectangle focusRect = new Rectangle(OffsetX, rowRect.Y, this.Width - (this._vScrollBar.Visible ? this._vScrollBar.Width : 0), rowRect.Height);
-
- context.DrawFocus = false;
-
- if (context.DrawSelection != DrawSelectionMode.Active)
- {
- using (SolidBrush b = new SolidBrush(node.BackColor))
- {
- e.Graphics.FillRectangle(b, focusRect);
- }
- }
-
- if (context.DrawSelection == DrawSelectionMode.Active || context.DrawSelection == DrawSelectionMode.Inactive)
- {
- if (context.DrawSelection == DrawSelectionMode.Active)
- {
- context.DrawSelection = DrawSelectionMode.FullRowSelect;
-
- if (ExplorerVisualStyle.VisualStylesEnabled)
- {
- ExplorerVisualStyle.TvItemSelectedRenderer.DrawBackground(context.Graphics, focusRect);
- }
- else
- {
- e.Graphics.FillRectangle(SystemBrushes.Highlight, focusRect);
- }
- }
- else
- {
- context.DrawSelection = DrawSelectionMode.None;
- }
- }
-
- this.DrawNode(node, context);
- }
-
- private void DrawColumnHeaders(Graphics gr)
- {
- ReorderColumnState reorder = this.Input as ReorderColumnState;
-
- int x = 0;
-
- TreeColumn.DrawBackground(gr, new Rectangle(0, 0, ClientRectangle.Width + 2, this.ColumnHeaderHeight - 1), false, false);
-
- gr.TranslateTransform(-OffsetX, 0);
-
- foreach (TreeColumn c in this.Columns)
- {
- if (!c.IsVisible)
- continue;
-
- if (x + c.Width >= this.OffsetX && x - this.OffsetX < this.Bounds.Width)// skip invisible columns (fixed by wj32)
- {
- Rectangle rect = new Rectangle(x, 0, c.Width, this.ColumnHeaderHeight - 1);
-
- gr.SetClip(rect);
-
- bool pressed = ((this.Input is ClickColumnState || reorder != null) && ((this.Input as ColumnState).Column == c));
-
- c.Draw(gr, rect, this.Font, pressed, this._hotColumn == c);
-
- gr.ResetClip();
-
- if (reorder != null && reorder.DropColumn == c)
- {
- TreeColumn.DrawDropMark(gr, rect);
- }
- }
- x += c.Width;
- }
-
- if (reorder != null)
- {
- if (reorder.DropColumn == null)
- {
- TreeColumn.DrawDropMark(gr, new Rectangle(x, 0, 0, this.ColumnHeaderHeight));
- }
-
- gr.DrawImage(reorder.GhostImage, new Point(reorder.Location.X + + reorder.DragOffset, reorder.Location.Y));
- }
- }
-
- public void DrawNode(TreeNodeAdv node, DrawContext context)
- {
- //todo, node collection needs locking.
- foreach (NodeControlInfo item in GetNodeControls(node))
- {
- if (item.Bounds.X + item.Bounds.Width >= OffsetX && item.Bounds.X - OffsetX < this.Bounds.Width)// skip invisible nodes (fixed by wj32)
- {
- context.Bounds = item.Bounds;
-
- context.Graphics.SetClip(context.Bounds);
-
- item.Control.Draw(node, context);
-
- context.Graphics.ResetClip();
- }
- }
- }
-
- private void DrawScrollBarsBox(Graphics gr)
- {
- Rectangle r1 = this.DisplayRectangle;
- Rectangle r2 = this.ClientRectangle;
-
- gr.FillRectangle(SystemBrushes.Control, new Rectangle(r1.Right, r1.Bottom, r2.Width - r1.Width, r2.Height - r1.Height));
- }
-
- private double _totalTime;
- private int _paintCount;
-
- private void BeginPerformanceCount()
- {
- _paintCount++;
- TimeCounter.Start();
- }
-
- private void EndPerformanceCount(PaintEventArgs e)
- {
- double time = TimeCounter.Finish();
- _totalTime += time;
-
- string debugText = string.Format("FPS {0:0.0}; Avg. FPS {1:0.0}", 1 / time, 1 / (_totalTime / _paintCount));
-
- e.Graphics.FillRectangle(Brushes.White, new Rectangle(this.DisplayRectangle.Width - 150, this.DisplayRectangle.Height - 20, 150, 20));
-
- TextRenderer.DrawText(e.Graphics, debugText, this.Font, new Point(this.DisplayRectangle.Width - 150, this.DisplayRectangle.Height - 20), Color.Black);
-
- //e.Graphics.DrawString(debugText, this.Font, Brushes.Gray, new PointF(DisplayRectangle.Width - 150, DisplayRectangle.Height - 20));
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdv.Properties.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdv.Properties.cs
deleted file mode 100644
index 32f2316b7..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdv.Properties.cs
+++ /dev/null
@@ -1,454 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.ComponentModel;
-using System.Drawing;
-using System.Windows.Forms;
-using System.Collections.ObjectModel;
-using System.Drawing.Design;
-
-using Aga.Controls.Tree.NodeControls;
-
-namespace Aga.Controls.Tree
-{
- public sealed partial class TreeViewAdv
- {
- private Cursor _innerCursor;
-
- public override Cursor Cursor
- {
- get
- {
- if (_innerCursor != null)
- return _innerCursor;
-
- return base.Cursor;
- }
- set { base.Cursor = value; }
- }
-
- #region Internal Properties
-
- private IRowLayout _rowLayout;
-
- public int ColumnHeaderHeight { get; private set; }
-
- ///
- /// returns all nodes, which parent is expanded
- ///
- private IEnumerable VisibleNodes
- {
- get
- {
- TreeNodeAdv node = this.Root;
-
- while (node != null)
- {
- node = node.NextVisibleNode;
-
- if (node != null)
- yield return node;
- }
- }
- }
-
- private bool _suspendSelectionEvent;
- internal bool SuspendSelectionEvent
- {
- get { return _suspendSelectionEvent; }
- set
- {
- if (value != _suspendSelectionEvent)
- {
- _suspendSelectionEvent = value;
- if (!_suspendSelectionEvent && _fireSelectionEvent)
- OnSelectionChanged();
- }
- }
- }
-
- internal List RowMap { get; private set; }
- internal TreeNodeAdv SelectionStart { get; set; }
- internal InputState Input { get; set; }
-
- ///
- /// Number of rows fits to the current page
- ///
- internal int CurrentPageSize
- {
- get { return _rowLayout.CurrentPageSize; }
- }
-
- ///
- /// Number of all visible nodes (which parent is expanded)
- ///
- internal int RowCount
- {
- get { return this.RowMap.Count; }
- }
-
- private int ContentWidth { get; set; }
-
- private int _firstVisibleRow;
- internal int FirstVisibleRow
- {
- get { return _firstVisibleRow; }
- set
- {
- HideEditor();
-
- _firstVisibleRow = value;
-
- UpdateView();
- }
- }
-
- private int _offsetX;
- internal int OffsetX
- {
- get { return _offsetX; }
- private set
- {
- HideEditor();
-
- _offsetX = value;
-
- UpdateView();
- }
- }
-
- public override Rectangle DisplayRectangle
- {
- get
- {
- Rectangle r = ClientRectangle;
- //r.Y += ColumnHeaderHeight;
- //r.Height -= ColumnHeaderHeight;
- int w = _vScrollBar.Visible ? _vScrollBar.Width : 0;
- int h = _hScrollBar.Visible ? _hScrollBar.Height : 0;
- return new Rectangle(r.X, r.Y, r.Width - w, r.Height - h);
- }
- }
-
- internal List Selection { get; private set; }
-
- #endregion
-
- #region Public Properties
-
- #region DesignTime
-
- private bool _showLines = true;
- [DefaultValue(true), Category("Behavior")]
- public bool ShowLines
- {
- get { return _showLines; }
- set
- {
- _showLines = value;
- UpdateView();
- }
- }
-
- private bool _showPlusMinus = true;
- [DefaultValue(true), Category("Behavior")]
- public bool ShowPlusMinus
- {
- get { return _showPlusMinus; }
- set
- {
- _showPlusMinus = value;
- FullUpdate();
- }
- }
-
- [DefaultValue(false), Category("Behavior")]
- public bool ShowNodeToolTips { get; set; }
-
- private ITreeModel _model;
- [Category("Data")]
- public ITreeModel Model
- {
- get { return _model; }
- set
- {
- if (_model != value)
- {
- if (_model != null)
- UnbindModelEvents();
-
- _model = value;
-
- CreateNodes();
- FullUpdate();
-
- if (_model != null)
- BindModelEvents();
- }
- }
- }
-
- // Font proprety for Tahoma as default font
- // wj32: Apparently some people don't have Tahoma...
- //private static Font _font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)), false);
- private static Font _font = DefaultFont;
- [Category("Appearance")]
- public override Font Font
- {
- get
- {
- return (base.Font);
- }
- set
- {
- if (value == null)
- base.Font = _font;
- else
- {
- if (value == Control.DefaultFont)
- base.Font = _font;
- else
- base.Font = value;
- }
- }
- }
- public override void ResetFont()
- {
- Font = null;
- }
- private bool ShouldSerializeFont()
- {
- return (!Font.Equals(_font));
- }
- // End font property
-
- private BorderStyle _borderStyle = BorderStyle.Fixed3D;
- [DefaultValue(BorderStyle.Fixed3D), Category("Appearance")]
- public BorderStyle BorderStyle
- {
- get { return this._borderStyle; }
- set
- {
- if (_borderStyle != value)
- {
- _borderStyle = value;
-
- this.RecreateHandle();
- this.Invalidate();
- }
- }
- }
-
- private bool _autoRowHeight;
- [DefaultValue(false), Category("Appearance")]
- public bool AutoRowHeight
- {
- get { return _autoRowHeight; }
- set
- {
- _autoRowHeight = value;
- if (value)
- _rowLayout = new AutoRowHeightLayout(this, RowHeight);
- else
- _rowLayout = new FixedRowHeightLayout(this, RowHeight);
- FullUpdate();
- }
- }
-
- private int _rowHeight = 16;
- [DefaultValue(16), Category("Appearance")]
- public int RowHeight
- {
- get
- {
- return _rowHeight;
- }
- set
- {
- if (value <= 0)
- throw new ArgumentOutOfRangeException("value");
-
- _rowHeight = value;
- _rowLayout.PreferredRowHeight = value;
- FullUpdate();
- }
- }
-
- private TreeSelectionMode _selectionMode = TreeSelectionMode.Single;
- [DefaultValue(TreeSelectionMode.Single), Category("Behavior")]
- public TreeSelectionMode SelectionMode
- {
- get { return _selectionMode; }
- set { _selectionMode = value; }
- }
-
- private bool _hideSelection;
- [DefaultValue(false), Category("Behavior")]
- public bool HideSelection
- {
- get { return _hideSelection; }
- set
- {
- _hideSelection = value;
- UpdateView();
- }
- }
-
- private float _topEdgeSensivity = 0.3f;
- [DefaultValue(0.3f), Category("Behavior")]
- public float TopEdgeSensivity
- {
- get { return _topEdgeSensivity; }
- set
- {
- if (value < 0 || value > 1)
- throw new ArgumentOutOfRangeException();
- _topEdgeSensivity = value;
- }
- }
-
- private float _bottomEdgeSensivity = 0.3f;
- [DefaultValue(0.3f), Category("Behavior")]
- public float BottomEdgeSensivity
- {
- get { return _bottomEdgeSensivity; }
- set
- {
- if (value < 0 || value > 1)
- throw new ArgumentOutOfRangeException("BottomEdgeSensivity", "value should be from 0 to 1");
- _bottomEdgeSensivity = value;
- }
- }
-
- [DefaultValue(false), Category("Behavior")]
- public bool LoadOnDemand { get; set; }
-
- private int _indent = 19;
- [DefaultValue(19), Category("Behavior")]
- public int Indent
- {
- get { return _indent; }
- set
- {
- _indent = value;
- UpdateView();
- }
- }
-
- private Color _lineColor = SystemColors.ControlDark;
- [Category("Behavior")]
- public Color LineColor
- {
- get { return _lineColor; }
- set
- {
- _lineColor = value;
- CreateLinePen();
- UpdateView();
- }
- }
-
- [Category("Behavior"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
- public TreeColumnCollection Columns { get; private set; }
-
- [Category("Behavior"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Editor(typeof(NodeControlCollectionEditor), typeof(UITypeEditor))]
- public NodeControlsCollection NodeControls { get; private set; }
-
- #endregion
-
- #region RunTime
-
- [Browsable(false)]
- public IToolTipProvider DefaultToolTipProvider { get; set; }
-
- [Browsable(false)]
- public IEnumerable AllNodes
- {
- get
- {
- if (this.Root.Nodes.Count > 0)
- {
- TreeNodeAdv node = this.Root.Nodes[0];
-
- while (node != null)
- {
- yield return node;
-
- if (node.Nodes.Count > 0)
- node = node.Nodes[0];
- else if (node.NextNode != null)
- node = node.NextNode;
- else
- node = node.BottomNode;
- }
- }
- }
- }
-
- [Browsable(false)]
- public TreeNodeAdv Root { get; private set; }
-
- [Browsable(false)]
- public ReadOnlyCollection SelectedNodes { get; private set; }
-
- [Browsable(false)]
- public TreeNodeAdv SelectedNode
- {
- get
- {
- if (this.Selection.Count > 0)
- {
- if (this.CurrentNode != null && this.CurrentNode.IsSelected)
- return this.CurrentNode;
-
- return this.Selection[0];
- }
-
- return null;
- }
- set
- {
- if (SelectedNode == value)
- return;
-
- BeginUpdate();
-
- try
- {
- if (value == null)
- {
- ClearSelectionInternal();
- }
- else
- {
- if (!IsMyNode(value))
- throw new ArgumentException();
-
- ClearSelectionInternal();
- value.IsSelected = true;
- this.CurrentNode = value;
- EnsureVisible(value);
- }
- }
- finally
- {
- EndUpdate();
- }
- }
- }
-
- [Browsable(false)]
- public TreeNodeAdv CurrentNode { get; internal set; }
-
- [Browsable(false)]
- public int ItemCount
- {
- get { return this.RowMap.Count; }
- }
-
- #endregion
-
- #endregion
-
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdvEventArgs.cs b/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdvEventArgs.cs
deleted file mode 100644
index a2e88438e..000000000
--- a/1.x/trunk/ProcessHacker/Components/TreeViewAdv/Tree/TreeViewAdvEventArgs.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System;
-
-namespace Aga.Controls.Tree
-{
- public class TreeViewAdvEventArgs : EventArgs
- {
- public TreeNodeAdv Node { get; private set; }
-
- public TreeViewAdvEventArgs(TreeNodeAdv node)
- {
- this.Node = node;
- }
- }
-}
diff --git a/1.x/trunk/ProcessHacker/Components/VerticleProgressBar.cs b/1.x/trunk/ProcessHacker/Components/VerticleProgressBar.cs
index ddde1dcaa..45693bae4 100644
--- a/1.x/trunk/ProcessHacker/Components/VerticleProgressBar.cs
+++ b/1.x/trunk/ProcessHacker/Components/VerticleProgressBar.cs
@@ -20,7 +20,12 @@
* along with Process Hacker. If not, see .
*/
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
using System.Drawing;
+using System.Data;
+using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
diff --git a/1.x/trunk/ProcessHacker/Components/VistaMenu/OwnerDrawnMenu.cs b/1.x/trunk/ProcessHacker/Components/VistaMenu/OwnerDrawnMenu.cs
new file mode 100644
index 000000000..10cab6d31
--- /dev/null
+++ b/1.x/trunk/ProcessHacker/Components/VistaMenu/OwnerDrawnMenu.cs
@@ -0,0 +1,235 @@
+using System.ComponentModel;
+using System.ComponentModel.Design;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Windows.Forms;
+
+
+namespace wyDay.Controls
+{
+ public partial class VistaMenu
+ {
+ ContainerControl ownerForm;
+
+ //conditionally draw the little lines under menu items with keyboard accelators on Win 2000+
+ private bool isUsingKeyboardAccel;
+
+
+ public VistaMenu(ContainerControl parentControl)
+ : this()
+ {
+ ownerForm = parentControl;
+ }
+ public ContainerControl ContainerControl
+ {
+ get { return ownerForm; }
+ set { ownerForm = value; }
+ }
+ public override ISite Site
+ {
+ set
+ {
+ // Runs at design time, ensures designer initializes ContainerControl
+ base.Site = value;
+ if (value == null) return;
+ IDesignerHost service = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
+ if (service == null) return;
+ IComponent rootComponent = service.RootComponent;
+ ContainerControl = rootComponent as ContainerControl;
+ }
+ }
+
+
+ void ownerForm_ChangeUICues(object sender, UICuesEventArgs e)
+ {
+ isUsingKeyboardAccel = e.ShowKeyboard;
+ }
+
+
+ const int SEPARATOR_HEIGHT = 9;
+ const int BORDER_VERTICAL = 4;
+ const int LEFT_MARGIN = 4;
+ const int RIGHT_MARGIN = 6;
+ const int SHORTCUT_MARGIN = 20;
+ const int ARROW_MARGIN = 12;
+ const int ICON_SIZE = 16;
+
+
+ static void MenuItem_MeasureItem(object sender, MeasureItemEventArgs e)
+ {
+ Font font = ((MenuItem)sender).DefaultItem
+ ? new Font(SystemFonts.MenuFont, FontStyle.Bold)
+ : SystemFonts.MenuFont;
+
+ if (((MenuItem)sender).Text == "-")
+ e.ItemHeight = SEPARATOR_HEIGHT;
+ else
+ {
+ e.ItemHeight = ((SystemFonts.MenuFont.Height > ICON_SIZE) ? SystemFonts.MenuFont.Height : ICON_SIZE)
+ + BORDER_VERTICAL;
+
+ e.ItemWidth = LEFT_MARGIN + ICON_SIZE + RIGHT_MARGIN
+
+ //item text width
+ + TextRenderer.MeasureText(((MenuItem)sender).Text, font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoClipping).Width
+ + SHORTCUT_MARGIN
+
+ //shortcut text width
+ + TextRenderer.MeasureText(ShortcutToString(((MenuItem)sender).Shortcut), font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoClipping).Width
+
+ //arrow width
+ + ((((MenuItem)sender).IsParent) ? ARROW_MARGIN : 0);
+ }
+ }
+
+ void MenuItem_DrawItem(object sender, DrawItemEventArgs e)
+ {
+ e.Graphics.CompositingQuality = CompositingQuality.HighSpeed;
+ e.Graphics.InterpolationMode = InterpolationMode.Low;
+
+ bool menuSelected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
+
+ if (menuSelected)
+ e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
+ else
+ e.Graphics.FillRectangle(SystemBrushes.Menu, e.Bounds);
+
+ if (((MenuItem)sender).Text == "-")
+ {
+ //draw the separator
+ int yCenter = e.Bounds.Top + (e.Bounds.Height / 2) - 1;
+
+ e.Graphics.DrawLine(SystemPens.ControlDark, e.Bounds.Left + 1, yCenter, (e.Bounds.Left + e.Bounds.Width - 2), yCenter);
+ e.Graphics.DrawLine(SystemPens.ControlLightLight, e.Bounds.Left + 1, yCenter + 1, (e.Bounds.Left + e.Bounds.Width - 2), yCenter + 1);
+ }
+ else //regular menu items
+ {
+ //draw the item text
+ DrawText(sender, e, menuSelected);
+
+ if (((MenuItem)sender).Checked)
+ {
+ if (((MenuItem)sender).RadioCheck)
+ {
+ //draw the bullet
+ ControlPaint.DrawMenuGlyph(e.Graphics,
+ e.Bounds.Left + (LEFT_MARGIN + ICON_SIZE + RIGHT_MARGIN - SystemInformation.MenuCheckSize.Width) / 2,
+ e.Bounds.Top + (e.Bounds.Height - SystemInformation.MenuCheckSize.Height) / 2 + 1,
+ SystemInformation.MenuCheckSize.Width,
+ SystemInformation.MenuCheckSize.Height,
+ MenuGlyph.Bullet,
+ menuSelected ? SystemColors.HighlightText : SystemColors.MenuText,
+ menuSelected ? SystemColors.Highlight : SystemColors.Menu);
+ }
+ else
+ {
+ //draw the check mark
+ ControlPaint.DrawMenuGlyph(e.Graphics,
+ e.Bounds.Left + (LEFT_MARGIN + ICON_SIZE + RIGHT_MARGIN - SystemInformation.MenuCheckSize.Width) / 2,
+ e.Bounds.Top + (e.Bounds.Height - SystemInformation.MenuCheckSize.Height) / 2 + 1,
+ SystemInformation.MenuCheckSize.Width,
+ SystemInformation.MenuCheckSize.Height,
+ MenuGlyph.Checkmark,
+ menuSelected ? SystemColors.HighlightText : SystemColors.MenuText,
+ menuSelected ? SystemColors.Highlight : SystemColors.Menu);
+ }
+ }
+ else
+ {
+ Image drawImg = EnsurePropertiesExists((MenuItem)sender).PreVistaBitmap;
+
+ if (drawImg != null)
+ {
+ //draw the image
+ if (((MenuItem)sender).Enabled)
+ e.Graphics.DrawImage(drawImg, e.Bounds.Left + LEFT_MARGIN,
+ e.Bounds.Top + ((e.Bounds.Height - ICON_SIZE) / 2),
+ ICON_SIZE, ICON_SIZE);
+ else
+ ControlPaint.DrawImageDisabled(e.Graphics, drawImg,
+ e.Bounds.Left + LEFT_MARGIN,
+ e.Bounds.Top + ((e.Bounds.Height - ICON_SIZE) / 2),
+ SystemColors.Menu);
+ }
+ }
+ }
+ }
+
+
+ private static string ShortcutToString(Shortcut shortcut)
+ {
+ if (shortcut != Shortcut.None)
+ {
+ Keys keys = (Keys)shortcut;
+ return TypeDescriptor.GetConverter(keys.GetType()).ConvertToString(keys);
+ }
+
+ return null;
+ }
+
+ private void DrawText(object sender, DrawItemEventArgs e, bool isSelected)
+ {
+ string shortcutText = ShortcutToString(((MenuItem)sender).Shortcut);
+
+ int yPos = e.Bounds.Top + (e.Bounds.Height - SystemFonts.MenuFont.Height) / 2;
+
+ Font font = ((MenuItem)sender).DefaultItem
+ ? new Font(SystemFonts.MenuFont, FontStyle.Bold)
+ : SystemFonts.MenuFont;
+
+ Size textSize = TextRenderer.MeasureText(((MenuItem)sender).Text,
+ font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoClipping);
+
+ Rectangle textRect = new Rectangle(e.Bounds.Left + LEFT_MARGIN + ICON_SIZE + RIGHT_MARGIN, yPos,
+ textSize.Width, textSize.Height);
+
+ if (!((MenuItem)sender).Enabled && !isSelected) // disabled and not selected
+ {
+ textRect.Offset(1, 1);
+
+ TextRenderer.DrawText(e.Graphics, ((MenuItem)sender).Text, font,
+ textRect,
+ SystemColors.ControlLightLight,
+ TextFormatFlags.SingleLine | (isUsingKeyboardAccel ? 0 : TextFormatFlags.HidePrefix) | TextFormatFlags.NoClipping);
+
+ textRect.Offset(-1, -1);
+ }
+
+ //Draw the menu item text
+ TextRenderer.DrawText(e.Graphics, ((MenuItem)sender).Text, font,
+ textRect,
+ ((MenuItem)sender).Enabled ? (isSelected ? SystemColors.HighlightText : SystemColors.MenuText) : SystemColors.GrayText,
+ TextFormatFlags.SingleLine | (isUsingKeyboardAccel ? 0 : TextFormatFlags.HidePrefix) | TextFormatFlags.NoClipping);
+
+
+
+ //Draw the shortcut text
+ if (shortcutText != null)
+ {
+ textSize = TextRenderer.MeasureText(shortcutText,
+ font, Size.Empty, TextFormatFlags.SingleLine | TextFormatFlags.NoClipping);
+
+
+ textRect = new Rectangle(e.Bounds.Width - textSize.Width - ARROW_MARGIN, yPos, textSize.Width,
+ textSize.Height);
+
+ if (!((MenuItem)sender).Enabled && !isSelected) // disabled and not selected
+ {
+ textRect.Offset(1, 1);
+
+ TextRenderer.DrawText(e.Graphics, shortcutText, font,
+ textRect,
+ SystemColors.ControlLightLight,
+ TextFormatFlags.SingleLine | (isUsingKeyboardAccel ? 0 : TextFormatFlags.HidePrefix) | TextFormatFlags.NoClipping);
+
+ textRect.Offset(-1, -1);
+ }
+
+ TextRenderer.DrawText(e.Graphics, shortcutText, font,
+ textRect,
+ ((MenuItem)sender).Enabled ? (isSelected ? SystemColors.HighlightText : SystemColors.MenuText) : SystemColors.GrayText,
+ TextFormatFlags.SingleLine | TextFormatFlags.NoClipping);
+ }
+ }
+ }
+}
diff --git a/1.x/trunk/ProcessHacker/Components/VistaMenu/VistaMenu.cs b/1.x/trunk/ProcessHacker/Components/VistaMenu/VistaMenu.cs
new file mode 100644
index 000000000..60c06b132
--- /dev/null
+++ b/1.x/trunk/ProcessHacker/Components/VistaMenu/VistaMenu.cs
@@ -0,0 +1,411 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Drawing;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows.Forms;
+using ProcessHacker.Native;
+
+
+//VistaMenu v1.7, created by Wyatt O'Day
+//Visit: http://wyday.com/vistamenu/
+
+namespace wyDay.Controls
+{
+ //Properties for the MenuItem
+ internal class Properties
+ {
+ public Image Image;
+ public IntPtr renderBmpHbitmap = IntPtr.Zero;
+ public Bitmap PreVistaBitmap;
+ }
+
+ //enum WindowsType { VistaOrLater, XP, PreXP }
+
+ [ProvideProperty("Image", typeof(MenuItem))]
+ public partial class VistaMenu : Component, IExtenderProvider, ISupportInitialize
+ {
+ private Container components;
+ private readonly Hashtable properties = new Hashtable();
+ private readonly Hashtable menuParents = new Hashtable();
+
+ private bool formHasBeenIntialized;
+
+ // performance hacks
+ private Queue> _pendingSetImageCalls =
+ new Queue>();
+
+ private static bool _firstVistaMenu = true;
+ private bool _delaySetImageCalls = false;
+
+ public bool DelaySetImageCalls
+ {
+ get { return _delaySetImageCalls; }
+ set { _delaySetImageCalls = value; }
+ }
+
+ #region Imports
+
+ [DllImport("user32.dll", CharSet = CharSet.Auto)]
+ public static extern bool SetMenuItemInfo(HandleRef hMenu, int uItem, bool fByPosition, MENUITEMINFO_T_RW lpmii);
+
+ [DllImport("user32.dll", CharSet = CharSet.Auto)]
+ public static extern bool SetMenuInfo(HandleRef hMenu, MENUINFO lpcmi);
+
+ [DllImport("gdi32.dll")]
+ public static extern bool DeleteObject(IntPtr hObject);
+
+ #endregion
+
+
+ public VistaMenu()
+ {
+ InitializeComponent();
+ }
+
+ public VistaMenu(IContainer container)
+ : this()
+ {
+ container.Add(this);
+
+ if (_firstVistaMenu)
+ {
+ _delaySetImageCalls = true;
+ _firstVistaMenu = false;
+ }
+ }
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent()
+ {
+ components = new Container();
+ }
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ //release all the HBitmap handles created
+ foreach (DictionaryEntry de in properties)
+ {
+ if (((Properties)de.Value).renderBmpHbitmap != IntPtr.Zero)
+ DeleteObject(((Properties)de.Value).renderBmpHbitmap);
+ if (((Properties)de.Value).PreVistaBitmap != null)
+ ((Properties)de.Value).PreVistaBitmap.Dispose();
+ }
+
+
+ if (components != null)
+ {
+ components.Dispose();
+ }
+ }
+ base.Dispose(disposing);
+ }
+
+ bool IExtenderProvider.CanExtend(object o)
+ {
+ if (o is MenuItem)
+ {
+ // reject the menuitem if it's a top level element on a MainMenu bar
+ if (((MenuItem)o).Parent != null)
+ return ((MenuItem)o).Parent.GetType() != typeof(MainMenu);
+
+ // parent is null - meaning it's a context menu
+ return true;
+ }
+
+ if (o is Form)
+ return true;
+
+ return false;
+ }
+
+ private Properties EnsurePropertiesExists(MenuItem key)
+ {
+ Properties p = (Properties)properties[key];
+
+ if (p == null)
+ {
+ p = new Properties();
+
+ properties[key] = p;
+ }
+
+ return p;
+ }
+
+
+ #region MenuItem.Image
+
+ [DefaultValue(null)]
+ [Description("The Image for the MenuItem")]
+ [Category("Appearance")]
+ public Image GetImage(MenuItem mnuItem)
+ {
+ return EnsurePropertiesExists(mnuItem).Image;
+ }
+
+ [DefaultValue(null)]
+ public void SetImage(MenuItem mnuItem, Image value)
+ {
+ this.SetImage(mnuItem, value, false);
+ }
+
+ public void SetImage(MenuItem mnuItem, Image value, bool ignorePending)
+ {
+ if (_delaySetImageCalls && !ignorePending)
+ {
+ _pendingSetImageCalls.Enqueue(new KeyValuePair
private void InitializeComponent()
{
+ this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DumpHackerWindow));
this.treeProcesses = new ProcessHacker.ProcessTree();
this.tabControl = new System.Windows.Forms.TabControl();
@@ -38,6 +39,7 @@ private void InitializeComponent()
this.propertiesMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.copyMenuItem = new System.Windows.Forms.MenuItem();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
this.goToProcessServiceMenuItem = new System.Windows.Forms.MenuItem();
this.propertiesServiceMenuItem = new System.Windows.Forms.MenuItem();
this.copyServiceMenuItem = new System.Windows.Forms.MenuItem();
@@ -46,6 +48,7 @@ private void InitializeComponent()
this.tabControl.SuspendLayout();
this.tabProcesses.SuspendLayout();
this.tabServices.SuspendLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
// treeProcesses
@@ -100,6 +103,7 @@ private void InitializeComponent()
// listServices
//
this.listServices.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.listServices.DoubleBuffered = true;
this.listServices.Location = new System.Drawing.Point(3, 3);
this.listServices.Name = "listServices";
this.listServices.Provider = null;
@@ -117,6 +121,7 @@ private void InitializeComponent()
// propertiesMenuItem
//
this.propertiesMenuItem.DefaultItem = true;
+ this.vistaMenu.SetImage(this.propertiesMenuItem, global::ProcessHacker.Properties.Resources.application_form_magnify);
this.propertiesMenuItem.Index = 0;
this.propertiesMenuItem.Text = "Properties";
this.propertiesMenuItem.Click += new System.EventHandler(this.propertiesMenuItem_Click);
@@ -128,11 +133,18 @@ private void InitializeComponent()
//
// copyMenuItem
//
+ this.vistaMenu.SetImage(this.copyMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyMenuItem.Index = 2;
this.copyMenuItem.Text = "Copy";
//
+ // vistaMenu
+ //
+ this.vistaMenu.ContainerControl = this;
+ this.vistaMenu.DelaySetImageCalls = false;
+ //
// goToProcessServiceMenuItem
//
+ this.vistaMenu.SetImage(this.goToProcessServiceMenuItem, global::ProcessHacker.Properties.Resources.arrow_right);
this.goToProcessServiceMenuItem.Index = 0;
this.goToProcessServiceMenuItem.Text = "Go to Process";
this.goToProcessServiceMenuItem.Click += new System.EventHandler(this.goToProcessServiceMenuItem_Click);
@@ -140,12 +152,14 @@ private void InitializeComponent()
// propertiesServiceMenuItem
//
this.propertiesServiceMenuItem.DefaultItem = true;
+ this.vistaMenu.SetImage(this.propertiesServiceMenuItem, global::ProcessHacker.Properties.Resources.application_form_magnify);
this.propertiesServiceMenuItem.Index = 1;
this.propertiesServiceMenuItem.Text = "Properties";
this.propertiesServiceMenuItem.Click += new System.EventHandler(this.propertiesServiceMenuItem_Click);
//
// copyServiceMenuItem
//
+ this.vistaMenu.SetImage(this.copyServiceMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
this.copyServiceMenuItem.Index = 3;
this.copyServiceMenuItem.Text = "Copy";
//
@@ -167,17 +181,17 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(903, 525);
this.Controls.Add(this.tabControl);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "DumpHackerWindow";
this.Text = "Dump Viewer";
- this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DumpHackerWindow_FormClosing);
this.Load += new System.EventHandler(this.DumpHackerWindow_Load);
+ this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DumpHackerWindow_FormClosing);
this.tabControl.ResumeLayout(false);
this.tabProcesses.ResumeLayout(false);
this.tabServices.ResumeLayout(false);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
}
@@ -191,7 +205,7 @@ private void InitializeComponent()
private ProcessHacker.Components.ServiceList listServices;
private System.Windows.Forms.ContextMenu menuProcess;
private System.Windows.Forms.MenuItem propertiesMenuItem;
-
+ private wyDay.Controls.VistaMenu vistaMenu;
private System.Windows.Forms.MenuItem copyMenuItem;
private System.Windows.Forms.ContextMenu menuService;
private System.Windows.Forms.MenuItem goToProcessServiceMenuItem;
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.cs b/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.cs
index 8c214fdec..a3bcbf82d 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.cs
+++ b/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.cs
@@ -27,22 +27,23 @@
using ProcessHacker.Native;
using ProcessHacker.Native.Api;
using ProcessHacker.Native.Mfs;
+using ProcessHacker.Native.Objects;
using ProcessHacker.UI;
namespace ProcessHacker
{
public partial class DumpHackerWindow : Form
{
- private readonly MemoryFileSystem _mfs;
+ private MemoryFileSystem _mfs;
private MemoryObject _processesMo;
private MemoryObject _servicesMo;
private string _phVersion;
private string _osVersion;
private OSArch _architecture;
private string _userName;
- private readonly Dictionary _processes = new Dictionary();
- private readonly Dictionary _services = new Dictionary();
- private readonly Dictionary> _processServices = new Dictionary>();
+ private Dictionary _processes = new Dictionary();
+ private Dictionary _services = new Dictionary();
+ private Dictionary> _processServices = new Dictionary>();
public DumpHackerWindow(string fileName)
{
@@ -54,7 +55,7 @@ public DumpHackerWindow(string fileName)
ColumnSettings.LoadSettings(Settings.Instance.ProcessTreeColumns, treeProcesses.Tree);
ColumnSettings.LoadSettings(Settings.Instance.ServiceListViewColumns, listServices.List);
- listServices.DoubleClick += this.listServices_DoubleClick;
+ listServices.DoubleClick += new EventHandler(listServices_DoubleClick);
}
private void DumpHackerWindow_Load(object sender, EventArgs e)
@@ -105,7 +106,9 @@ public Dictionary Processes
private void LoadSystemInformation()
{
- MemoryObject sysInfoMo = this._mfs.RootObject.GetChild("SystemInformation");
+ MemoryObject sysInfoMo;
+
+ sysInfoMo = _mfs.RootObject.GetChild("SystemInformation");
if (sysInfoMo == null)
{
@@ -114,7 +117,7 @@ private void LoadSystemInformation()
return;
}
- IDictionary dict = Dump.GetDictionary(sysInfoMo);
+ var dict = Dump.GetDictionary(sysInfoMo);
sysInfoMo.Dispose();
@@ -133,27 +136,30 @@ private void LoadSystemInformation()
private void LoadProcesses()
{
- MemoryObject processesMo = this._mfs.RootObject.GetChild("Processes");
+ MemoryObject processesMo;
+
+ processesMo = _mfs.RootObject.GetChild("Processes");
_processesMo = processesMo;
if (processesMo == null)
{
- PhUtils.ShowWarning("The dump file does not contain process information. This most likely means the file is corrupt.");
+ PhUtils.ShowWarning("The dump file does not contain process information. This most likely " +
+ "means the file is corrupt.");
return;
}
- processesMo.EnumChildren(childMo =>
- {
- using (childMo)
- this.LoadProcess(childMo);
+ processesMo.EnumChildren((childMo) =>
+ {
+ using (childMo)
+ this.LoadProcess(childMo);
- return true;
- });
+ return true;
+ });
}
private void LoadProcess(MemoryObject mo)
{
- var names = mo.ChildNames;
+ var names = mo.GetChildNames();
ProcessItem pitem;
if (!names.Contains("General"))
@@ -161,15 +167,13 @@ private void LoadProcess(MemoryObject mo)
IDictionary generalDict;
- using (MemoryObject general = mo.GetChild("General"))
+ using (var general = mo.GetChild("General"))
generalDict = Dump.GetDictionary(general);
- pitem = new ProcessItem
- {
- Pid = Dump.ParseInt32(generalDict["ProcessId"]),
- Name = generalDict["Name"],
- ParentPid = Dump.ParseInt32(generalDict["ParentPid"])
- };
+ pitem = new ProcessItem();
+ pitem.Pid = Dump.ParseInt32(generalDict["ProcessId"]);
+ pitem.Name = generalDict["Name"];
+ pitem.ParentPid = Dump.ParseInt32(generalDict["ParentPid"]);
if (generalDict.ContainsKey("HasParent"))
pitem.HasParent = Dump.ParseBool(generalDict["HasParent"]);
@@ -183,13 +187,11 @@ private void LoadProcess(MemoryObject mo)
if (generalDict.ContainsKey("FileDescription"))
{
- pitem.VersionInfo = new ImageVersionInfo
- {
- FileDescription = generalDict["FileDescription"],
- CompanyName = generalDict["FileCompanyName"],
- FileVersion = generalDict["FileVersion"],
- FileName = pitem.FileName
- };
+ pitem.VersionInfo = new ImageVersionInfo();
+ pitem.VersionInfo.FileDescription = generalDict["FileDescription"];
+ pitem.VersionInfo.CompanyName = generalDict["FileCompanyName"];
+ pitem.VersionInfo.FileVersion = generalDict["FileVersion"];
+ pitem.VersionInfo.FileName = pitem.FileName;
}
if (generalDict.ContainsKey("CommandLine"))
@@ -266,7 +268,7 @@ private void LoadServices()
return;
}
- servicesMo.EnumChildren(childMo =>
+ servicesMo.EnumChildren((childMo) =>
{
using (childMo)
this.LoadService(childMo);
@@ -363,17 +365,18 @@ private void treeProcesses_NodeMouseDoubleClick(object sender, Aga.Controls.Tree
private void menuProcess_Popup(object sender, EventArgs e)
{
- switch (this.treeProcesses.SelectedTreeNodes.Count)
+ if (treeProcesses.SelectedTreeNodes.Count == 0)
+ {
+ menuProcess.DisableAll();
+ }
+ else if (treeProcesses.SelectedTreeNodes.Count == 1)
+ {
+ menuProcess.EnableAll();
+ }
+ else
{
- case 0:
- break;
- case 1:
- this.menuProcess.EnableAll();
- break;
- default:
- this.menuProcess.EnableAll();
- this.propertiesMenuItem.Enabled = false;
- break;
+ menuProcess.EnableAll();
+ propertiesMenuItem.Enabled = false;
}
}
@@ -396,7 +399,7 @@ private void menuService_Popup(object sender, EventArgs e)
{
if (listServices.SelectedItems.Count == 0)
{
- //menuService.DisableAll();
+ menuService.DisableAll();
}
else if (listServices.SelectedItems.Count == 1)
{
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.resx b/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.resx
index 09cc1a538..a5532164d 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.resx
+++ b/1.x/trunk/ProcessHacker/Forms/DumpHackerWindow.resx
@@ -112,18 +112,18 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
17, 17
-
- 249, 17
+
+ 141, 17
-
+
AAABAA8AMDAQAAEABABoBgAA9gAAACAgEAABAAQA6AIAAF4HAAAQEBAAAQAEACgBAABGCgAAAAAAAAEA
@@ -912,4 +912,7 @@
QQAArEEAAKxBAACsQXAArEFwAKxBcACsQXAArEFwAKxBAACsQQ==
+
+ 249, 17
+
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.Designer.cs b/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.Designer.cs
index cab4ac1ca..d9bb00827 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.Designer.cs
@@ -1,6 +1,6 @@
namespace ProcessHacker
{
- sealed partial class DumpProcessWindow
+ partial class DumpProcessWindow
{
///
/// Required designer variable.
@@ -34,6 +34,13 @@ private void InitializeComponent()
{
this.tabControl = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
+ this.tabToken = new System.Windows.Forms.TabPage();
+ this.tabModules = new System.Windows.Forms.TabPage();
+ this.tabEnvironment = new System.Windows.Forms.TabPage();
+ this.listEnvironment = new System.Windows.Forms.ListView();
+ this.columnVarName = new System.Windows.Forms.ColumnHeader();
+ this.columnVarValue = new System.Windows.Forms.ColumnHeader();
+ this.tabHandles = new System.Windows.Forms.TabPage();
this.groupProcess = new System.Windows.Forms.GroupBox();
this.labelProcessTypeValue = new System.Windows.Forms.Label();
this.labelProcessType = new System.Windows.Forms.Label();
@@ -46,7 +53,6 @@ private void InitializeComponent()
this.label4 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textStartTime = new System.Windows.Forms.TextBox();
- this.textCurrentDirectory = new System.Windows.Forms.TextBox();
this.textCmdLine = new System.Windows.Forms.TextBox();
this.groupFile = new System.Windows.Forms.GroupBox();
this.pictureIcon = new System.Windows.Forms.PictureBox();
@@ -54,25 +60,19 @@ private void InitializeComponent()
this.textFileCompany = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
- this.textFileName = new System.Windows.Forms.TextBox();
this.textFileVersion = new System.Windows.Forms.TextBox();
- this.tabToken = new System.Windows.Forms.TabPage();
- this.tabModules = new System.Windows.Forms.TabPage();
+ this.textFileName = new System.Windows.Forms.TextBox();
+ this.textCurrentDirectory = new System.Windows.Forms.TextBox();
this.listModules = new ProcessHacker.Components.ModuleList();
- this.tabEnvironment = new System.Windows.Forms.TabPage();
- this.listEnvironment = new ProcessHacker.Components.ExtendedListView();
- this.columnVarName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.columnVarValue = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
- this.tabHandles = new System.Windows.Forms.TabPage();
this.listHandles = new ProcessHacker.Components.HandleList();
this.tabControl.SuspendLayout();
this.tabGeneral.SuspendLayout();
- this.groupProcess.SuspendLayout();
- this.groupFile.SuspendLayout();
- ((System.ComponentModel.ISupportInitialize)(this.pictureIcon)).BeginInit();
this.tabModules.SuspendLayout();
this.tabEnvironment.SuspendLayout();
this.tabHandles.SuspendLayout();
+ this.groupProcess.SuspendLayout();
+ this.groupFile.SuspendLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.pictureIcon)).BeginInit();
this.SuspendLayout();
//
// tabControl
@@ -101,11 +101,80 @@ private void InitializeComponent()
this.tabGeneral.Text = "General";
this.tabGeneral.UseVisualStyleBackColor = true;
//
+ // tabToken
+ //
+ this.tabToken.Location = new System.Drawing.Point(4, 22);
+ this.tabToken.Name = "tabToken";
+ this.tabToken.Size = new System.Drawing.Size(469, 441);
+ this.tabToken.TabIndex = 4;
+ this.tabToken.Text = "Token";
+ this.tabToken.UseVisualStyleBackColor = true;
+ //
+ // tabModules
+ //
+ this.tabModules.Controls.Add(this.listModules);
+ this.tabModules.Location = new System.Drawing.Point(4, 22);
+ this.tabModules.Name = "tabModules";
+ this.tabModules.Padding = new System.Windows.Forms.Padding(3);
+ this.tabModules.Size = new System.Drawing.Size(469, 441);
+ this.tabModules.TabIndex = 1;
+ this.tabModules.Text = "Modules";
+ this.tabModules.UseVisualStyleBackColor = true;
+ //
+ // tabEnvironment
+ //
+ this.tabEnvironment.Controls.Add(this.listEnvironment);
+ this.tabEnvironment.Location = new System.Drawing.Point(4, 22);
+ this.tabEnvironment.Name = "tabEnvironment";
+ this.tabEnvironment.Padding = new System.Windows.Forms.Padding(3);
+ this.tabEnvironment.Size = new System.Drawing.Size(469, 441);
+ this.tabEnvironment.TabIndex = 3;
+ this.tabEnvironment.Text = "Environment";
+ this.tabEnvironment.UseVisualStyleBackColor = true;
+ //
+ // listEnvironment
+ //
+ this.listEnvironment.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
+ this.columnVarName,
+ this.columnVarValue});
+ this.listEnvironment.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.listEnvironment.FullRowSelect = true;
+ this.listEnvironment.HideSelection = false;
+ this.listEnvironment.Location = new System.Drawing.Point(3, 3);
+ this.listEnvironment.Name = "listEnvironment";
+ this.listEnvironment.ShowItemToolTips = true;
+ this.listEnvironment.Size = new System.Drawing.Size(463, 435);
+ this.listEnvironment.Sorting = System.Windows.Forms.SortOrder.Ascending;
+ this.listEnvironment.TabIndex = 1;
+ this.listEnvironment.UseCompatibleStateImageBehavior = false;
+ this.listEnvironment.View = System.Windows.Forms.View.Details;
+ //
+ // columnVarName
+ //
+ this.columnVarName.Text = "Name";
+ this.columnVarName.Width = 150;
+ //
+ // columnVarValue
+ //
+ this.columnVarValue.Text = "Value";
+ this.columnVarValue.Width = 250;
+ //
+ // tabHandles
+ //
+ this.tabHandles.Controls.Add(this.listHandles);
+ this.tabHandles.Location = new System.Drawing.Point(4, 22);
+ this.tabHandles.Name = "tabHandles";
+ this.tabHandles.Padding = new System.Windows.Forms.Padding(3);
+ this.tabHandles.Size = new System.Drawing.Size(469, 441);
+ this.tabHandles.TabIndex = 2;
+ this.tabHandles.Text = "Handles";
+ this.tabHandles.UseVisualStyleBackColor = true;
+ //
// groupProcess
//
- this.groupProcess.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupProcess.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.groupProcess.Controls.Add(this.labelProcessTypeValue);
this.groupProcess.Controls.Add(this.labelProcessType);
this.groupProcess.Controls.Add(this.label26);
@@ -141,7 +210,7 @@ private void InitializeComponent()
this.labelProcessType.AutoSize = true;
this.labelProcessType.Location = new System.Drawing.Point(6, 157);
this.labelProcessType.Name = "labelProcessType";
- this.labelProcessType.Size = new System.Drawing.Size(74, 13);
+ this.labelProcessType.Size = new System.Drawing.Size(75, 13);
this.labelProcessType.TabIndex = 19;
this.labelProcessType.Text = "Process Type:";
this.labelProcessType.Visible = false;
@@ -151,19 +220,19 @@ private void InitializeComponent()
this.label26.AutoSize = true;
this.label26.Location = new System.Drawing.Point(6, 22);
this.label26.Name = "label26";
- this.label26.Size = new System.Drawing.Size(47, 13);
+ this.label26.Size = new System.Drawing.Size(44, 13);
this.label26.TabIndex = 12;
this.label26.Text = "Started:";
//
// textDEP
//
- this.textDEP.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textDEP.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textDEP.BackColor = System.Drawing.SystemColors.Control;
this.textDEP.Location = new System.Drawing.Point(101, 128);
this.textDEP.Name = "textDEP";
this.textDEP.ReadOnly = true;
- this.textDEP.Size = new System.Drawing.Size(348, 22);
+ this.textDEP.Size = new System.Drawing.Size(348, 20);
this.textDEP.TabIndex = 8;
//
// labelDEP
@@ -171,7 +240,7 @@ private void InitializeComponent()
this.labelDEP.AutoSize = true;
this.labelDEP.Location = new System.Drawing.Point(6, 131);
this.labelDEP.Name = "labelDEP";
- this.labelDEP.Size = new System.Drawing.Size(30, 13);
+ this.labelDEP.Size = new System.Drawing.Size(32, 13);
this.labelDEP.TabIndex = 17;
this.labelDEP.Text = "DEP:";
//
@@ -191,19 +260,19 @@ private void InitializeComponent()
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(6, 105);
this.label5.Name = "label5";
- this.label5.Size = new System.Drawing.Size(43, 13);
+ this.label5.Size = new System.Drawing.Size(41, 13);
this.label5.TabIndex = 16;
this.label5.Text = "Parent:";
//
// textParent
//
- this.textParent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textParent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textParent.BackColor = System.Drawing.SystemColors.Control;
this.textParent.Location = new System.Drawing.Point(101, 102);
this.textParent.Name = "textParent";
this.textParent.ReadOnly = true;
- this.textParent.Size = new System.Drawing.Size(318, 22);
+ this.textParent.Size = new System.Drawing.Size(318, 20);
this.textParent.TabIndex = 6;
//
// label4
@@ -211,7 +280,7 @@ private void InitializeComponent()
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 76);
this.label4.Name = "label4";
- this.label4.Size = new System.Drawing.Size(98, 13);
+ this.label4.Size = new System.Drawing.Size(89, 13);
this.label4.TabIndex = 14;
this.label4.Text = "Current Directory:";
//
@@ -220,44 +289,34 @@ private void InitializeComponent()
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 48);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(86, 13);
+ this.label2.Size = new System.Drawing.Size(80, 13);
this.label2.TabIndex = 13;
this.label2.Text = "Command Line:";
//
// textStartTime
//
- this.textStartTime.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textStartTime.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textStartTime.Location = new System.Drawing.Point(101, 19);
this.textStartTime.Name = "textStartTime";
this.textStartTime.ReadOnly = true;
- this.textStartTime.Size = new System.Drawing.Size(348, 22);
+ this.textStartTime.Size = new System.Drawing.Size(348, 20);
this.textStartTime.TabIndex = 0;
//
- // textCurrentDirectory
- //
- this.textCurrentDirectory.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textCurrentDirectory.Location = new System.Drawing.Point(101, 73);
- this.textCurrentDirectory.Name = "textCurrentDirectory";
- this.textCurrentDirectory.ReadOnly = true;
- this.textCurrentDirectory.Size = new System.Drawing.Size(348, 22);
- this.textCurrentDirectory.TabIndex = 2;
- //
// textCmdLine
//
- this.textCmdLine.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textCmdLine.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textCmdLine.Location = new System.Drawing.Point(101, 45);
this.textCmdLine.Name = "textCmdLine";
this.textCmdLine.ReadOnly = true;
- this.textCmdLine.Size = new System.Drawing.Size(348, 22);
+ this.textCmdLine.Size = new System.Drawing.Size(348, 20);
this.textCmdLine.TabIndex = 2;
//
// groupFile
//
- this.groupFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.groupFile.Controls.Add(this.pictureIcon);
this.groupFile.Controls.Add(this.textFileDescription);
this.groupFile.Controls.Add(this.textFileCompany);
@@ -283,27 +342,27 @@ private void InitializeComponent()
//
// textFileDescription
//
- this.textFileDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textFileDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textFileDescription.BackColor = System.Drawing.SystemColors.Window;
this.textFileDescription.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textFileDescription.Location = new System.Drawing.Point(44, 20);
this.textFileDescription.Name = "textFileDescription";
this.textFileDescription.ReadOnly = true;
- this.textFileDescription.Size = new System.Drawing.Size(407, 15);
+ this.textFileDescription.Size = new System.Drawing.Size(407, 13);
this.textFileDescription.TabIndex = 2;
this.textFileDescription.Text = "File Description";
//
// textFileCompany
//
- this.textFileCompany.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textFileCompany.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textFileCompany.BackColor = System.Drawing.SystemColors.Window;
this.textFileCompany.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textFileCompany.Location = new System.Drawing.Point(44, 38);
this.textFileCompany.Name = "textFileCompany";
this.textFileCompany.ReadOnly = true;
- this.textFileCompany.Size = new System.Drawing.Size(407, 15);
+ this.textFileCompany.Size = new System.Drawing.Size(407, 13);
this.textFileCompany.TabIndex = 3;
this.textFileCompany.Text = "File Company";
//
@@ -312,7 +371,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 60);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(83, 13);
+ this.label1.Size = new System.Drawing.Size(77, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Image Version:";
//
@@ -321,112 +380,54 @@ private void InitializeComponent()
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 88);
this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(94, 13);
+ this.label3.Size = new System.Drawing.Size(89, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Image File Name:";
//
- // textFileName
- //
- this.textFileName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textFileName.Location = new System.Drawing.Point(103, 85);
- this.textFileName.Name = "textFileName";
- this.textFileName.ReadOnly = true;
- this.textFileName.Size = new System.Drawing.Size(348, 22);
- this.textFileName.TabIndex = 0;
- //
// textFileVersion
//
- this.textFileVersion.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textFileVersion.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textFileVersion.Location = new System.Drawing.Point(103, 57);
this.textFileVersion.Name = "textFileVersion";
this.textFileVersion.ReadOnly = true;
- this.textFileVersion.Size = new System.Drawing.Size(348, 22);
+ this.textFileVersion.Size = new System.Drawing.Size(348, 20);
this.textFileVersion.TabIndex = 0;
//
- // tabToken
+ // textFileName
//
- this.tabToken.Location = new System.Drawing.Point(4, 22);
- this.tabToken.Name = "tabToken";
- this.tabToken.Size = new System.Drawing.Size(469, 441);
- this.tabToken.TabIndex = 4;
- this.tabToken.Text = "Token";
- this.tabToken.UseVisualStyleBackColor = true;
+ this.textFileName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textFileName.Location = new System.Drawing.Point(103, 85);
+ this.textFileName.Name = "textFileName";
+ this.textFileName.ReadOnly = true;
+ this.textFileName.Size = new System.Drawing.Size(348, 20);
+ this.textFileName.TabIndex = 0;
//
- // tabModules
+ // textCurrentDirectory
//
- this.tabModules.Controls.Add(this.listModules);
- this.tabModules.Location = new System.Drawing.Point(4, 22);
- this.tabModules.Name = "tabModules";
- this.tabModules.Padding = new System.Windows.Forms.Padding(3);
- this.tabModules.Size = new System.Drawing.Size(469, 441);
- this.tabModules.TabIndex = 1;
- this.tabModules.Text = "Modules";
- this.tabModules.UseVisualStyleBackColor = true;
+ this.textCurrentDirectory.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textCurrentDirectory.Location = new System.Drawing.Point(101, 73);
+ this.textCurrentDirectory.Name = "textCurrentDirectory";
+ this.textCurrentDirectory.ReadOnly = true;
+ this.textCurrentDirectory.Size = new System.Drawing.Size(348, 20);
+ this.textCurrentDirectory.TabIndex = 2;
//
// listModules
//
this.listModules.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.listModules.DoubleBuffered = true;
this.listModules.Location = new System.Drawing.Point(3, 3);
this.listModules.Name = "listModules";
this.listModules.Provider = null;
this.listModules.Size = new System.Drawing.Size(463, 435);
this.listModules.TabIndex = 0;
//
- // tabEnvironment
- //
- this.tabEnvironment.Controls.Add(this.listEnvironment);
- this.tabEnvironment.Location = new System.Drawing.Point(4, 22);
- this.tabEnvironment.Name = "tabEnvironment";
- this.tabEnvironment.Padding = new System.Windows.Forms.Padding(3);
- this.tabEnvironment.Size = new System.Drawing.Size(469, 441);
- this.tabEnvironment.TabIndex = 3;
- this.tabEnvironment.Text = "Environment";
- this.tabEnvironment.UseVisualStyleBackColor = true;
- //
- // listEnvironment
- //
- this.listEnvironment.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
- this.columnVarName,
- this.columnVarValue});
- this.listEnvironment.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listEnvironment.DoubleClickChecks = true;
- this.listEnvironment.FullRowSelect = true;
- this.listEnvironment.HideSelection = false;
- this.listEnvironment.Location = new System.Drawing.Point(3, 3);
- this.listEnvironment.Name = "listEnvironment";
- this.listEnvironment.ShowItemToolTips = true;
- this.listEnvironment.Size = new System.Drawing.Size(463, 435);
- this.listEnvironment.Sorting = System.Windows.Forms.SortOrder.Ascending;
- this.listEnvironment.TabIndex = 1;
- this.listEnvironment.UseCompatibleStateImageBehavior = false;
- this.listEnvironment.View = System.Windows.Forms.View.Details;
- //
- // columnVarName
- //
- this.columnVarName.Text = "Name";
- this.columnVarName.Width = 150;
- //
- // columnVarValue
- //
- this.columnVarValue.Text = "Value";
- this.columnVarValue.Width = 250;
- //
- // tabHandles
- //
- this.tabHandles.Controls.Add(this.listHandles);
- this.tabHandles.Location = new System.Drawing.Point(4, 22);
- this.tabHandles.Name = "tabHandles";
- this.tabHandles.Padding = new System.Windows.Forms.Padding(3);
- this.tabHandles.Size = new System.Drawing.Size(469, 441);
- this.tabHandles.TabIndex = 2;
- this.tabHandles.Text = "Handles";
- this.tabHandles.UseVisualStyleBackColor = true;
- //
// listHandles
//
this.listHandles.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.listHandles.DoubleBuffered = true;
this.listHandles.Location = new System.Drawing.Point(3, 3);
this.listHandles.Name = "listHandles";
this.listHandles.Provider = null;
@@ -437,24 +438,23 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(483, 473);
this.Controls.Add(this.tabControl);
this.Name = "DumpProcessWindow";
this.Padding = new System.Windows.Forms.Padding(3);
this.Text = "Process";
- this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DumpProcessWindow_FormClosing);
this.Load += new System.EventHandler(this.DumpProcessWindow_Load);
+ this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DumpProcessWindow_FormClosing);
this.tabControl.ResumeLayout(false);
this.tabGeneral.ResumeLayout(false);
+ this.tabModules.ResumeLayout(false);
+ this.tabEnvironment.ResumeLayout(false);
+ this.tabHandles.ResumeLayout(false);
this.groupProcess.ResumeLayout(false);
this.groupProcess.PerformLayout();
this.groupFile.ResumeLayout(false);
this.groupFile.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureIcon)).EndInit();
- this.tabModules.ResumeLayout(false);
- this.tabEnvironment.ResumeLayout(false);
- this.tabHandles.ResumeLayout(false);
this.ResumeLayout(false);
}
@@ -469,7 +469,7 @@ private void InitializeComponent()
private System.Windows.Forms.TabPage tabEnvironment;
private ProcessHacker.Components.ModuleList listModules;
private ProcessHacker.Components.HandleList listHandles;
- private ProcessHacker.Components.ExtendedListView listEnvironment;
+ private System.Windows.Forms.ListView listEnvironment;
private System.Windows.Forms.ColumnHeader columnVarName;
private System.Windows.Forms.ColumnHeader columnVarValue;
private System.Windows.Forms.GroupBox groupProcess;
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.cs b/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.cs
index de9275d00..171e72bc1 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.cs
+++ b/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.cs
@@ -21,7 +21,6 @@
*/
using System;
-using System.Collections.Generic;
using System.Windows.Forms;
using ProcessHacker.Common;
using ProcessHacker.Components;
@@ -33,11 +32,11 @@
namespace ProcessHacker
{
- public sealed partial class DumpProcessWindow : Form
+ public partial class DumpProcessWindow : Form
{
- private readonly DumpHackerWindow _hw;
- private readonly ProcessItem _item;
- private readonly MemoryObject _processMo;
+ private DumpHackerWindow _hw;
+ private ProcessItem _item;
+ private MemoryObject _processMo;
private TokenProperties _tokenProps;
@@ -66,10 +65,8 @@ private void DumpProcessWindow_Load(object sender, EventArgs e)
{
this.LoadProperties();
- _tokenProps = new TokenProperties(null)
- {
- Dock = DockStyle.Fill
- };
+ _tokenProps = new TokenProperties(null);
+ _tokenProps.Dock = DockStyle.Fill;
tabToken.Controls.Add(_tokenProps);
_tokenProps.DumpInitialize();
this.LoadToken();
@@ -77,6 +74,7 @@ private void DumpProcessWindow_Load(object sender, EventArgs e)
// Modules
if (_item.FileName != null)
listModules.DumpSetMainModule(_item.FileName);
+ listModules.List.SetTheme("explorer");
listModules.List.AddShortcuts();
listModules.List.ContextMenu = listModules.List.GetCopyMenu();
@@ -84,6 +82,7 @@ private void DumpProcessWindow_Load(object sender, EventArgs e)
listModules.UpdateItems();
// Environment
+ listEnvironment.SetTheme("explorer");
listEnvironment.AddShortcuts();
listEnvironment.ContextMenu = listEnvironment.GetCopyMenu();
@@ -91,6 +90,7 @@ private void DumpProcessWindow_Load(object sender, EventArgs e)
// Handles
listHandles.DumpDisableEvents();
+ listHandles.List.SetTheme("explorer");
listHandles.List.AddShortcuts();
listHandles.List.ContextMenu = listHandles.List.GetCopyMenu();
@@ -110,7 +110,7 @@ private void DumpProcessWindow_FormClosing(object sender, FormClosingEventArgs e
private void LoadProperties()
{
- var names = _processMo.ChildNames;
+ var names = _processMo.GetChildNames();
if (names.Contains("LargeIcon"))
{
@@ -131,8 +131,8 @@ private void LoadProperties()
else
{
textFileDescription.Text = _item.Name;
- textFileCompany.Text = string.Empty;
- textFileVersion.Text = string.Empty;
+ textFileCompany.Text = "";
+ textFileVersion.Text = "";
}
textFileName.Text = _item.FileName;
@@ -297,7 +297,7 @@ private void LoadModules()
if (modulesMo == null)
return;
- modulesMo.EnumChildren(childMo =>
+ modulesMo.EnumChildren((childMo) =>
{
using (childMo)
this.LoadModule(childMo);
@@ -331,17 +331,17 @@ private void LoadModule(MemoryObject mo)
private void LoadEnvironment()
{
- MemoryObject env = _processMo.GetChild("Environment");
+ var env = _processMo.GetChild("Environment");
if (env == null)
return;
- IDictionary dict = Dump.GetDictionary(env);
+ var dict = Dump.GetDictionary(env);
foreach (var kvp in dict)
{
if (!string.IsNullOrEmpty(kvp.Key))
- listEnvironment.Items.Add(new ListViewItem(new[] { kvp.Key, kvp.Value }));
+ listEnvironment.Items.Add(new ListViewItem(new string[] { kvp.Key, kvp.Value }));
}
env.Dispose();
@@ -356,7 +356,7 @@ private void LoadHandles()
if (handlesMo == null)
return;
- handlesMo.EnumChildren(childMo =>
+ handlesMo.EnumChildren((childMo) =>
{
using (childMo)
this.LoadHandles(childMo);
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.resx b/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.resx
+++ b/1.x/trunk/ProcessHacker/Forms/DumpProcessWindow.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.Designer.cs b/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.Designer.cs
index 96c14100f..eab5689bc 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.Designer.cs
@@ -50,127 +50,126 @@ private void InitializeComponent()
//
// textServiceDll
//
- this.textServiceDll.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textServiceDll.Location = new System.Drawing.Point(91, 230);
+ this.textServiceDll.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textServiceDll.Location = new System.Drawing.Point(93, 200);
this.textServiceDll.Name = "textServiceDll";
this.textServiceDll.ReadOnly = true;
- this.textServiceDll.Size = new System.Drawing.Size(303, 22);
+ this.textServiceDll.Size = new System.Drawing.Size(303, 20);
this.textServiceDll.TabIndex = 43;
//
// label8
//
this.label8.AutoSize = true;
- this.label8.Location = new System.Drawing.Point(10, 233);
+ this.label8.Location = new System.Drawing.Point(12, 203);
this.label8.Name = "label8";
- this.label8.Size = new System.Drawing.Size(66, 13);
+ this.label8.Size = new System.Drawing.Size(69, 13);
this.label8.TabIndex = 42;
this.label8.Text = "Service DLL:";
//
// textDescription
//
- this.textDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textDescription.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
- this.textDescription.Location = new System.Drawing.Point(13, 44);
+ this.textDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textDescription.BorderStyle = System.Windows.Forms.BorderStyle.None;
+ this.textDescription.Location = new System.Drawing.Point(12, 51);
this.textDescription.Multiline = true;
this.textDescription.Name = "textDescription";
this.textDescription.ReadOnly = true;
this.textDescription.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
- this.textDescription.Size = new System.Drawing.Size(384, 75);
+ this.textDescription.Size = new System.Drawing.Size(384, 38);
this.textDescription.TabIndex = 38;
- this.textDescription.TextChanged += new System.EventHandler(this.textDescription_TextChanged);
//
// textLoadOrderGroup
//
- this.textLoadOrderGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textLoadOrderGroup.Location = new System.Drawing.Point(244, 152);
+ this.textLoadOrderGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textLoadOrderGroup.Location = new System.Drawing.Point(246, 122);
this.textLoadOrderGroup.Name = "textLoadOrderGroup";
this.textLoadOrderGroup.ReadOnly = true;
- this.textLoadOrderGroup.Size = new System.Drawing.Size(150, 22);
+ this.textLoadOrderGroup.Size = new System.Drawing.Size(150, 20);
this.textLoadOrderGroup.TabIndex = 37;
//
// label6
//
this.label6.AutoSize = true;
- this.label6.Location = new System.Drawing.Point(199, 128);
+ this.label6.Location = new System.Drawing.Point(201, 98);
this.label6.Name = "label6";
- this.label6.Size = new System.Drawing.Size(60, 13);
+ this.label6.Size = new System.Drawing.Size(59, 13);
this.label6.TabIndex = 33;
this.label6.Text = "Start Type:";
//
// label5
//
this.label5.AutoSize = true;
- this.label5.Location = new System.Drawing.Point(10, 155);
+ this.label5.Location = new System.Drawing.Point(12, 125);
this.label5.Name = "label5";
- this.label5.Size = new System.Drawing.Size(77, 13);
+ this.label5.Size = new System.Drawing.Size(68, 13);
this.label5.TabIndex = 32;
this.label5.Text = "Error Control:";
//
// label4
//
this.label4.AutoSize = true;
- this.label4.Location = new System.Drawing.Point(10, 128);
+ this.label4.Location = new System.Drawing.Point(12, 98);
this.label4.Name = "label4";
- this.label4.Size = new System.Drawing.Size(33, 13);
+ this.label4.Size = new System.Drawing.Size(34, 13);
this.label4.TabIndex = 31;
this.label4.Text = "Type:";
//
// label3
//
this.label3.AutoSize = true;
- this.label3.Location = new System.Drawing.Point(199, 155);
+ this.label3.Location = new System.Drawing.Point(201, 125);
this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(43, 13);
+ this.label3.Size = new System.Drawing.Size(39, 13);
this.label3.TabIndex = 30;
this.label3.Text = "Group:";
//
// label2
//
this.label2.AutoSize = true;
- this.label2.Location = new System.Drawing.Point(10, 181);
+ this.label2.Location = new System.Drawing.Point(12, 151);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(68, 13);
+ this.label2.Size = new System.Drawing.Size(64, 13);
this.label2.TabIndex = 29;
this.label2.Text = "Binary Path:";
//
// textUserAccount
//
- this.textUserAccount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textUserAccount.Location = new System.Drawing.Point(91, 204);
+ this.textUserAccount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textUserAccount.Location = new System.Drawing.Point(93, 174);
this.textUserAccount.Name = "textUserAccount";
this.textUserAccount.ReadOnly = true;
- this.textUserAccount.Size = new System.Drawing.Size(303, 22);
+ this.textUserAccount.Size = new System.Drawing.Size(303, 20);
this.textUserAccount.TabIndex = 28;
//
// label1
//
this.label1.AutoSize = true;
- this.label1.Location = new System.Drawing.Point(10, 207);
+ this.label1.Location = new System.Drawing.Point(12, 177);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(78, 13);
+ this.label1.Size = new System.Drawing.Size(75, 13);
this.label1.TabIndex = 27;
this.label1.Text = "User Account:";
//
// textServiceBinaryPath
//
- this.textServiceBinaryPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textServiceBinaryPath.Location = new System.Drawing.Point(91, 178);
+ this.textServiceBinaryPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textServiceBinaryPath.Location = new System.Drawing.Point(93, 148);
this.textServiceBinaryPath.Name = "textServiceBinaryPath";
this.textServiceBinaryPath.ReadOnly = true;
- this.textServiceBinaryPath.Size = new System.Drawing.Size(303, 22);
+ this.textServiceBinaryPath.Size = new System.Drawing.Size(303, 20);
this.textServiceBinaryPath.TabIndex = 26;
//
// labelServiceDisplayName
//
this.labelServiceDisplayName.AutoSize = true;
- this.labelServiceDisplayName.Location = new System.Drawing.Point(12, 28);
+ this.labelServiceDisplayName.Location = new System.Drawing.Point(12, 30);
this.labelServiceDisplayName.Name = "labelServiceDisplayName";
- this.labelServiceDisplayName.Size = new System.Drawing.Size(114, 13);
+ this.labelServiceDisplayName.Size = new System.Drawing.Size(111, 13);
this.labelServiceDisplayName.TabIndex = 25;
this.labelServiceDisplayName.Text = "Service Display Name";
//
@@ -188,7 +187,7 @@ private void InitializeComponent()
//
this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.buttonClose.Location = new System.Drawing.Point(321, 272);
+ this.buttonClose.Location = new System.Drawing.Point(321, 232);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(75, 23);
this.buttonClose.TabIndex = 44;
@@ -198,40 +197,39 @@ private void InitializeComponent()
//
// textServiceType
//
- this.textServiceType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textServiceType.Location = new System.Drawing.Point(50, 125);
+ this.textServiceType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textServiceType.Location = new System.Drawing.Point(52, 95);
this.textServiceType.Name = "textServiceType";
this.textServiceType.ReadOnly = true;
- this.textServiceType.Size = new System.Drawing.Size(143, 22);
+ this.textServiceType.Size = new System.Drawing.Size(143, 20);
this.textServiceType.TabIndex = 37;
//
// textStartType
//
- this.textStartType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textStartType.Location = new System.Drawing.Point(264, 125);
+ this.textStartType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textStartType.Location = new System.Drawing.Point(266, 95);
this.textStartType.Name = "textStartType";
this.textStartType.ReadOnly = true;
- this.textStartType.Size = new System.Drawing.Size(130, 22);
+ this.textStartType.Size = new System.Drawing.Size(130, 20);
this.textStartType.TabIndex = 37;
//
// textErrorControl
//
- this.textErrorControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.textErrorControl.Location = new System.Drawing.Point(84, 152);
+ this.textErrorControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textErrorControl.Location = new System.Drawing.Point(86, 122);
this.textErrorControl.Name = "textErrorControl";
this.textErrorControl.ReadOnly = true;
- this.textErrorControl.Size = new System.Drawing.Size(109, 22);
+ this.textErrorControl.Size = new System.Drawing.Size(109, 20);
this.textErrorControl.TabIndex = 37;
//
// DumpServiceWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
- this.ClientSize = new System.Drawing.Size(408, 307);
+ this.ClientSize = new System.Drawing.Size(408, 267);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.textServiceDll);
this.Controls.Add(this.label8);
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.cs b/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.cs
index 2aa10ddd6..544c5a8d5 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.cs
+++ b/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.cs
@@ -29,7 +29,7 @@ namespace ProcessHacker
{
public partial class DumpServiceWindow : Form
{
- private readonly MemoryObject _serviceMo;
+ private MemoryObject _serviceMo;
public DumpServiceWindow(ServiceItem item, MemoryObject serviceMo)
{
@@ -76,10 +76,5 @@ private void buttonClose_Click(object sender, EventArgs e)
{
this.Close();
}
-
- private void textDescription_TextChanged(object sender, EventArgs e)
- {
-
- }
}
}
diff --git a/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.resx b/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.resx
+++ b/1.x/trunk/ProcessHacker/Forms/DumpServiceWindow.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.Designer.cs b/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.Designer.cs
index 81cbf9b4c..003cd449a 100644
--- a/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.Designer.cs
@@ -40,14 +40,14 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 15);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(68, 13);
+ this.label1.Size = new System.Drawing.Size(65, 13);
this.label1.TabIndex = 0;
this.label1.Text = "New Status:";
//
// comboStatus
//
- this.comboStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.comboStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.comboStatus.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboStatus.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.comboStatus.FormattingEnabled = true;
@@ -90,7 +90,7 @@ private void InitializeComponent()
this.checkPermanent.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkPermanent.Location = new System.Drawing.Point(12, 39);
this.checkPermanent.Name = "checkPermanent";
- this.checkPermanent.Size = new System.Drawing.Size(87, 18);
+ this.checkPermanent.Size = new System.Drawing.Size(83, 18);
this.checkPermanent.TabIndex = 2;
this.checkPermanent.Text = "Permanent";
this.checkPermanent.UseVisualStyleBackColor = true;
@@ -101,7 +101,6 @@ private void InitializeComponent()
this.AcceptButton = this.buttonOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(315, 104);
this.Controls.Add(this.checkPermanent);
this.Controls.Add(this.buttonCancel);
diff --git a/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.cs b/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.cs
index 96202ba6b..62d29908a 100644
--- a/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.cs
+++ b/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.cs
@@ -32,12 +32,11 @@ namespace ProcessHacker
{
public partial class EditDEPWindow : Form
{
- private readonly int _pid;
+ private int _pid;
public EditDEPWindow(int PID)
{
InitializeComponent();
-
this.AddEscapeToClose();
this.SetTopMost();
@@ -45,9 +44,10 @@ public EditDEPWindow(int PID)
try
{
- using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation))
+ using (ProcessHandle phandle
+ = new ProcessHandle(_pid, ProcessAccess.QueryInformation))
{
- var depStatus = phandle.DepStatus;
+ var depStatus = phandle.GetDepStatus();
string str;
if ((depStatus & DepStatus.Enabled) != 0)
@@ -64,7 +64,7 @@ public EditDEPWindow(int PID)
comboStatus.SelectedItem = str;
- if (KProcessHacker2.Instance.KphIsConnected)
+ if (KProcessHacker.Instance != null)
checkPermanent.Visible = true;
}
}
@@ -74,7 +74,7 @@ public EditDEPWindow(int PID)
private void buttonOK_Click(object sender, EventArgs e)
{
- if (KProcessHacker2.Instance.KphIsConnected)
+ if (KProcessHacker.Instance != null)
this.SetDepStatusKph();
else
this.SetDepStatusNoKph();
@@ -82,22 +82,18 @@ private void buttonOK_Click(object sender, EventArgs e)
private void SetDepStatusKph()
{
- DepStatus depStatus;
+ DepStatus depStatus = DepStatus.Enabled;
- switch (this.comboStatus.SelectedItem.ToString())
+ if (comboStatus.SelectedItem.ToString() == "Disabled")
+ depStatus = 0;
+ else if (comboStatus.SelectedItem.ToString() == "Enabled")
+ depStatus = DepStatus.Enabled;
+ else if (comboStatus.SelectedItem.ToString() == "Enabled, DEP-ATL thunk emulation disabled")
+ depStatus = DepStatus.Enabled | DepStatus.AtlThunkEmulationDisabled;
+ else
{
- case "Disabled":
- depStatus = 0;
- break;
- case "Enabled":
- depStatus = DepStatus.Enabled;
- break;
- case "Enabled, DEP-ATL thunk emulation disabled":
- depStatus = DepStatus.Enabled | DepStatus.AtlThunkEmulationDisabled;
- break;
- default:
- PhUtils.ShowError("Invalid value.");
- return;
+ PhUtils.ShowError("Invalid value.");
+ return;
}
if (checkPermanent.Checked)
@@ -105,8 +101,8 @@ private void SetDepStatusKph()
try
{
- using (ProcessHandle phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
- phandle.DepStatus = depStatus;
+ using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
+ phandle.SetDepStatus(depStatus);
this.DialogResult = DialogResult.OK;
this.Close();
@@ -119,15 +115,13 @@ private void SetDepStatusKph()
private void SetDepStatusNoKph()
{
- if (comboStatus.SelectedItem.ToString().StartsWith("Enabled", StringComparison.OrdinalIgnoreCase))
- {
+ if (comboStatus.SelectedItem.ToString().StartsWith("Enabled"))
if (!PhUtils.ShowConfirmMessage(
"set",
"the DEP status",
"Enabling DEP in a process is a permanent action.",
false))
return;
- }
DepFlags flags = DepFlags.Enable;
diff --git a/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.resx b/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.resx
+++ b/1.x/trunk/ProcessHacker/Forms/EditDEPWindow.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Forms/ErrorDialog.Designer.cs b/1.x/trunk/ProcessHacker/Forms/ErrorDialog.Designer.cs
index 63d062393..d894fef35 100644
--- a/1.x/trunk/ProcessHacker/Forms/ErrorDialog.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Forms/ErrorDialog.Designer.cs
@@ -39,15 +39,15 @@ private void InitializeComponent()
//
// labelIntro
//
- this.labelIntro.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.labelIntro.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.labelIntro.Location = new System.Drawing.Point(12, 26);
this.labelIntro.Name = "labelIntro";
this.labelIntro.Size = new System.Drawing.Size(484, 32);
this.labelIntro.TabIndex = 0;
this.labelIntro.Text = "Please report this error to the Process Hacker team via our bug tracker hosted at" +
- " SourceForge by clicking Send Report. You will recieve a tracker item for keeing" +
- " track of its resolution status.";
+ " SourceForge by clicking Send Report. You will recieve a tracker item for keeing" +
+ " track of its resolution status.";
//
// buttonContinue
//
@@ -75,9 +75,9 @@ private void InitializeComponent()
//
// textException
//
- this.textException.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textException.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textException.BackColor = System.Drawing.SystemColors.Control;
this.textException.Location = new System.Drawing.Point(12, 61);
this.textException.Multiline = true;
@@ -106,7 +106,7 @@ private void InitializeComponent()
this.statusLinkLabel.Enabled = false;
this.statusLinkLabel.Location = new System.Drawing.Point(12, 336);
this.statusLinkLabel.Name = "statusLinkLabel";
- this.statusLinkLabel.Size = new System.Drawing.Size(210, 13);
+ this.statusLinkLabel.Size = new System.Drawing.Size(199, 13);
this.statusLinkLabel.TabIndex = 6;
this.statusLinkLabel.TabStop = true;
this.statusLinkLabel.Text = "Please Wait, Reporting to Bug Tracker...";
@@ -128,7 +128,7 @@ private void InitializeComponent()
this.AcceptButton = this.buttonQuit;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
+ this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(508, 366);
this.Controls.Add(this.labelIntro);
this.Controls.Add(this.label1);
diff --git a/1.x/trunk/ProcessHacker/Forms/ErrorDialog.cs b/1.x/trunk/ProcessHacker/Forms/ErrorDialog.cs
index 3ebc7552a..651e5ef8e 100644
--- a/1.x/trunk/ProcessHacker/Forms/ErrorDialog.cs
+++ b/1.x/trunk/ProcessHacker/Forms/ErrorDialog.cs
@@ -27,14 +27,13 @@
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ProcessHacker.Common;
-using ProcessHacker.Native;
using ProcessHacker.Native.Api;
namespace ProcessHacker
{
public partial class ErrorDialog : Form
{
- private readonly Exception _exception;
+ private Exception _exception;
private string _trackerItem;
public ErrorDialog(Exception ex, bool terminating)
@@ -79,12 +78,12 @@ private void buttonQuit_Click(object sender, EventArgs e)
Settings.Instance.Save();
// Remove the icons or they remain in the system try.
- Program.HackerWindow.ExecuteOnIcons(icon => icon.Visible = false);
- Program.HackerWindow.ExecuteOnIcons(icon => icon.Dispose());
+ Program.HackerWindow.ExecuteOnIcons((icon) => icon.Visible = false);
+ Program.HackerWindow.ExecuteOnIcons((icon) => icon.Dispose());
// Make sure KPH connection is closed.
- if (KProcessHacker2.Instance != null)
- KProcessHacker2.Instance.Dispose();
+ if (ProcessHacker.Native.KProcessHacker.Instance != null)
+ ProcessHacker.Native.KProcessHacker.Instance.Close();
}
catch (Exception ex)
{
@@ -102,8 +101,8 @@ private void submitReportButton_Click(object sender, EventArgs e)
this.statusLinkLabel.Visible = true;
SFBugReporter wc = new SFBugReporter();
- wc.DownloadProgressChanged += wc_DownloadProgressChanged;
- wc.DownloadStringCompleted += wc_DownloadStringCompleted;
+ wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
+ wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
NameValueCollection qc = new NameValueCollection();
qc.Add("group_id", "242527"); //PH BugTracker ID: Required Do Not Change!
@@ -136,7 +135,7 @@ private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEv
buttonContinue.Enabled = true;
buttonQuit.Enabled = true;
- if (e.Error != null || this.GetTitle(e.Result).Contains("ERROR", StringComparison.OrdinalIgnoreCase))
+ if (e.Error != null || this.GetTitle(e.Result).Contains("ERROR"))
{
buttonSubmitReport.Enabled = true;
statusLinkLabel.Visible = false;
@@ -170,8 +169,10 @@ private string GetTitle(string data)
{
return m.Groups[1].Value;
}
-
- return string.Empty;
+ else
+ {
+ return "";
+ }
}
private string GetResult(string data)
@@ -182,8 +183,10 @@ private string GetResult(string data)
{
return m.Groups[1].Value;
}
-
- return string.Empty;
+ else
+ {
+ return "";
+ }
}
private string GetUrl(string data)
@@ -194,15 +197,17 @@ private string GetUrl(string data)
{
return m.Value;
}
-
- return string.Empty;
+ else
+ {
+ return "";
+ }
}
- public class SFBugReporter : WebClient
+ public partial class SFBugReporter : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
- HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);
+ System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
webRequest.UserAgent = "Process Hacker " + Application.ProductVersion;
webRequest.Timeout = System.Threading.Timeout.Infinite;
webRequest.ServicePoint.Expect100Continue = true; //fix for Sourceforge's lighttpd Server
diff --git a/1.x/trunk/ProcessHacker/Forms/ErrorDialog.resx b/1.x/trunk/ProcessHacker/Forms/ErrorDialog.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Forms/ErrorDialog.resx
+++ b/1.x/trunk/ProcessHacker/Forms/ErrorDialog.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.Designer.cs b/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.Designer.cs
index fbe53d50e..042fd6062 100644
--- a/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.Designer.cs
@@ -41,7 +41,7 @@ private void InitializeComponent()
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 15);
this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(118, 13);
+ this.label1.Size = new System.Drawing.Size(109, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Export Name/Ordinal:";
//
@@ -50,29 +50,29 @@ private void InitializeComponent()
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 41);
this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(51, 13);
+ this.label2.Size = new System.Drawing.Size(48, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Address:";
//
// textProcName
//
- this.textProcName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textProcName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textProcName.Location = new System.Drawing.Point(127, 12);
this.textProcName.Name = "textProcName";
- this.textProcName.Size = new System.Drawing.Size(255, 22);
+ this.textProcName.Size = new System.Drawing.Size(255, 20);
this.textProcName.TabIndex = 0;
- this.textProcName.Enter += new System.EventHandler(this.textProcName_Enter);
this.textProcName.Leave += new System.EventHandler(this.textProcName_Leave);
+ this.textProcName.Enter += new System.EventHandler(this.textProcName_Enter);
//
// textProcAddress
//
- this.textProcAddress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
+ this.textProcAddress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.textProcAddress.Location = new System.Drawing.Point(127, 38);
this.textProcAddress.Name = "textProcAddress";
this.textProcAddress.ReadOnly = true;
- this.textProcAddress.Size = new System.Drawing.Size(255, 22);
+ this.textProcAddress.Size = new System.Drawing.Size(255, 20);
this.textProcAddress.TabIndex = 1;
//
// buttonLookup
@@ -103,7 +103,6 @@ private void InitializeComponent()
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(394, 99);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.buttonLookup);
diff --git a/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.cs b/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.cs
index 196dd5453..fccbc20c6 100644
--- a/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.cs
+++ b/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.cs
@@ -29,7 +29,7 @@ namespace ProcessHacker
{
public partial class GetProcAddressWindow : Form
{
- private readonly string _fileName;
+ private string _fileName;
public GetProcAddressWindow(string fileName)
{
@@ -45,7 +45,7 @@ public GetProcAddressWindow(string fileName)
private void buttonLookup_Click(object sender, EventArgs e)
{
IntPtr module = Win32.LoadLibraryEx(_fileName, IntPtr.Zero, Win32.DontResolveDllReferences);
- IntPtr address;
+ IntPtr address = IntPtr.Zero;
int ordinal = 0;
if (module == IntPtr.Zero)
diff --git a/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.resx b/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.resx
index c7e0d4bdf..ff31a6db5 100644
--- a/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.resx
+++ b/1.x/trunk/ProcessHacker/Forms/GetProcAddressWindow.resx
@@ -112,9 +112,9 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/1.x/trunk/ProcessHacker/Forms/HackerWindow.Designer.cs b/1.x/trunk/ProcessHacker/Forms/HackerWindow.Designer.cs
index 105cfb5a0..5841ae453 100644
--- a/1.x/trunk/ProcessHacker/Forms/HackerWindow.Designer.cs
+++ b/1.x/trunk/ProcessHacker/Forms/HackerWindow.Designer.cs
@@ -30,6 +30,54 @@ private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HackerWindow));
+ this.menuProcess = new System.Windows.Forms.ContextMenu();
+ this.terminateMenuItem = new System.Windows.Forms.MenuItem();
+ this.terminateProcessTreeMenuItem = new System.Windows.Forms.MenuItem();
+ this.suspendMenuItem = new System.Windows.Forms.MenuItem();
+ this.resumeMenuItem = new System.Windows.Forms.MenuItem();
+ this.restartProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.reduceWorkingSetProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.virtualizationProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem5 = new System.Windows.Forms.MenuItem();
+ this.affinityProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.createDumpFileProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.terminatorProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.miscellaneousProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.analyzeWaitChainProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.detachFromDebuggerProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.heapsProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.injectDllProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.ioPriorityThreadMenuItem = new System.Windows.Forms.MenuItem();
+ this.ioPriority0ThreadMenuItem = new System.Windows.Forms.MenuItem();
+ this.ioPriority1ThreadMenuItem = new System.Windows.Forms.MenuItem();
+ this.ioPriority2ThreadMenuItem = new System.Windows.Forms.MenuItem();
+ this.ioPriority3ThreadMenuItem = new System.Windows.Forms.MenuItem();
+ this.protectionProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.setTokenProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.VirusTotalMenuItem = new System.Windows.Forms.MenuItem();
+ this.priorityMenuItem = new System.Windows.Forms.MenuItem();
+ this.realTimeMenuItem = new System.Windows.Forms.MenuItem();
+ this.highMenuItem = new System.Windows.Forms.MenuItem();
+ this.aboveNormalMenuItem = new System.Windows.Forms.MenuItem();
+ this.normalMenuItem = new System.Windows.Forms.MenuItem();
+ this.belowNormalMenuItem = new System.Windows.Forms.MenuItem();
+ this.idleMenuItem = new System.Windows.Forms.MenuItem();
+ this.runAsProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.launchAsUserProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.launchAsThisUserProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.windowProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.bringToFrontProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.restoreProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.minimizeProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.maximizeProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem15 = new System.Windows.Forms.MenuItem();
+ this.closeProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.propertiesProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem7 = new System.Windows.Forms.MenuItem();
+ this.searchProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.reanalyzeProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.copyProcessMenuItem = new System.Windows.Forms.MenuItem();
+ this.selectAllProcessMenuItem = new System.Windows.Forms.MenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem10 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem11 = new System.Windows.Forms.ToolStripMenuItem();
@@ -37,170 +85,464 @@ private void InitializeComponent()
this.toolStripMenuItem13 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem14 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem15 = new System.Windows.Forms.ToolStripMenuItem();
+ this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
+ this.hackerMenuItem = new System.Windows.Forms.MenuItem();
+ this.runMenuItem = new System.Windows.Forms.MenuItem();
+ this.runAsAdministratorMenuItem = new System.Windows.Forms.MenuItem();
+ this.runAsMenuItem = new System.Windows.Forms.MenuItem();
+ this.runAsServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.showDetailsForAllProcessesMenuItem = new System.Windows.Forms.MenuItem();
+ this.uacSeparatorMenuItem = new System.Windows.Forms.MenuItem();
+ this.openMenuItem = new System.Windows.Forms.MenuItem();
+ this.saveMenuItem = new System.Windows.Forms.MenuItem();
+ this.findHandlesMenuItem = new System.Windows.Forms.MenuItem();
+ this.inspectPEFileMenuItem = new System.Windows.Forms.MenuItem();
+ this.reloadStructsMenuItem = new System.Windows.Forms.MenuItem();
+ this.optionsMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem2 = new System.Windows.Forms.MenuItem();
+ this.shutdownMenuItem = new System.Windows.Forms.MenuItem();
+ this.exitMenuItem = new System.Windows.Forms.MenuItem();
+ this.viewMenuItem = new System.Windows.Forms.MenuItem();
+ this.toolbarMenuItem = new System.Windows.Forms.MenuItem();
+ this.sysInfoMenuItem = new System.Windows.Forms.MenuItem();
+ this.trayIconsMenuItem = new System.Windows.Forms.MenuItem();
+ this.cpuHistoryMenuItem = new System.Windows.Forms.MenuItem();
+ this.cpuUsageMenuItem = new System.Windows.Forms.MenuItem();
+ this.ioHistoryMenuItem = new System.Windows.Forms.MenuItem();
+ this.commitHistoryMenuItem = new System.Windows.Forms.MenuItem();
+ this.physMemHistoryMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem3 = new System.Windows.Forms.MenuItem();
+ this.updateNowMenuItem = new System.Windows.Forms.MenuItem();
+ this.updateProcessesMenuItem = new System.Windows.Forms.MenuItem();
+ this.updateServicesMenuItem = new System.Windows.Forms.MenuItem();
+ this.toolsMenuItem = new System.Windows.Forms.MenuItem();
+ this.createServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.hiddenProcessesMenuItem = new System.Windows.Forms.MenuItem();
+ this.verifyFileSignatureMenuItem = new System.Windows.Forms.MenuItem();
+ this.usersMenuItem = new System.Windows.Forms.MenuItem();
+ this.windowMenuItem = new System.Windows.Forms.MenuItem();
+ this.helpMenu = new System.Windows.Forms.MenuItem();
+ this.freeMemoryMenuItem = new System.Windows.Forms.MenuItem();
+ this.checkForUpdatesMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem1 = new System.Windows.Forms.MenuItem();
+ this.logMenuItem = new System.Windows.Forms.MenuItem();
+ this.helpMenuItem = new System.Windows.Forms.MenuItem();
+ this.donateMenuItem = new System.Windows.Forms.MenuItem();
+ this.aboutMenuItem = new System.Windows.Forms.MenuItem();
+ this.statusBar = new System.Windows.Forms.StatusBar();
+ this.statusGeneral = new System.Windows.Forms.StatusBarPanel();
+ this.statusCPU = new System.Windows.Forms.StatusBarPanel();
+ this.statusMemory = new System.Windows.Forms.StatusBarPanel();
this.tabControl = new System.Windows.Forms.TabControl();
this.tabProcesses = new System.Windows.Forms.TabPage();
this.treeProcesses = new ProcessHacker.ProcessTree();
- this.contextMenuStripProcess = new System.Windows.Forms.ContextMenuStrip(this.components);
- this.terminateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.terminateProcessTreeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.suspendToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.resumeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.restartToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.reduceWorkingSetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.virtualizationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator();
- this.affinityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.createDumpFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.terminatorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.miscellaneousToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.analyzeWaitChainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.detachFromDebuggerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.heapsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.injectDLLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.iOPriorityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.ioPriority0ThreadMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.ioPriority1ThreadMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.ioPriority3ThreadMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
- this.protectionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.setTokenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.uploadToVirusTotalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.priorityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.realTimeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.highToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.aboveNormalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.normalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.belowNormalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.idleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.runAsToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
- this.launchAsUserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.launchAsThisUserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.windowToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
- this.bringToFrontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.restoreToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.minimizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.maximizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator();
- this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator();
- this.searchOnlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.reanalyzeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.copyProcessMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator();
- this.propertiesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.tabServices = new System.Windows.Forms.TabPage();
this.listServices = new ProcessHacker.Components.ServiceList();
- this.contextMenuStripService = new System.Windows.Forms.ContextMenuStrip(this.components);
- this.goToProcessServiceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
- this.startToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.pauseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.continueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.stopToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator();
- this.copyToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
- this.selectAllServiceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator();
- this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tabNetwork = new System.Windows.Forms.TabPage();
this.listNetwork = new ProcessHacker.Components.NetworkList();
- this.contextMenuStripNetwork = new System.Windows.Forms.ContextMenuStrip(this.components);
- this.goToProcessNetworkMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolsToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
- this.whoisNetworkMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.tracertNetworkMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.pingNetworkMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.closeNetworkMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
- this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.selectAllNetworkMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStrip = new System.ToolStripEx();
+ this.toolStrip = new System.Windows.Forms.ToolStrip();
this.refreshToolStripButton = new System.Windows.Forms.ToolStripButton();
this.optionsToolStripButton = new System.Windows.Forms.ToolStripButton();
this.shutDownToolStripMenuItem = new System.Windows.Forms.ToolStripDropDownButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.findHandlesToolStripButton = new System.Windows.Forms.ToolStripButton();
this.sysInfoToolStripButton = new System.Windows.Forms.ToolStripButton();
- this.toolStripTextBox2 = new ProcessHacker.HackerWindow.ToolStripSearchBox();
- this.statusStrip1 = new System.Windows.Forms.StatusStrip();
- this.statusMemory = new System.Windows.Forms.ToolStripStatusLabel();
- this.statusCPU = new System.Windows.Forms.ToolStripStatusLabel();
- this.statusGeneral = new System.Windows.Forms.ToolStripStatusLabel();
- this.menuStripEx1 = new System.MenuStripEx();
- this.hackerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.runToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.runAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.runAsAdministratorMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.showDetailsForAllProcessesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
- this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
- this.findHandlesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.inspectPEFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.optionsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
- this.shutdownMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolbarMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.sysInfoMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.trayIconsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.cpuHistoryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.cpuUsageMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.ioHistoryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.commitHistoryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.physMemHistoryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
- this.refreshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.updateProcessesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.updateServicesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.createServiceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.hiddenProcessesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.verifyFileSignatureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.usersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.checkForUpdatesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
- this.logToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.helpToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
- this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.contextMenuStripTray = new System.Windows.Forms.ContextMenuStrip(this.components);
- this.showHideProcessHackerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.systemInformationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.networkInfomationMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
- this.processesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.notificationsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.enableAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.disableAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
- this.newProcessesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.terminatedProcessesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.newServicesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.startedServicesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.stoppedServicesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.deletedServicesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
- this.shutdownTrayMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
+ this.menuService = new System.Windows.Forms.ContextMenu();
+ this.goToProcessServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.startServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.continueServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.pauseServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.stopServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.deleteServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.propertiesServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem8 = new System.Windows.Forms.MenuItem();
+ this.copyServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.selectAllServiceMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuIcon = new System.Windows.Forms.ContextMenu();
+ this.showHideMenuItem = new System.Windows.Forms.MenuItem();
+ this.sysInformationIconMenuItem = new System.Windows.Forms.MenuItem();
+ this.networkInfomationMenuItem = new System.Windows.Forms.MenuItem();
+ this.notificationsMenuItem = new System.Windows.Forms.MenuItem();
+ this.enableAllNotificationsMenuItem = new System.Windows.Forms.MenuItem();
+ this.disableAllNotificationsMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem4 = new System.Windows.Forms.MenuItem();
+ this.NPMenuItem = new System.Windows.Forms.MenuItem();
+ this.TPMenuItem = new System.Windows.Forms.MenuItem();
+ this.NSMenuItem = new System.Windows.Forms.MenuItem();
+ this.startedSMenuItem = new System.Windows.Forms.MenuItem();
+ this.stoppedSMenuItem = new System.Windows.Forms.MenuItem();
+ this.DSMenuItem = new System.Windows.Forms.MenuItem();
+ this.processesMenuItem = new System.Windows.Forms.MenuItem();
+ this.shutdownTrayMenuItem = new System.Windows.Forms.MenuItem();
+ this.exitTrayMenuItem = new System.Windows.Forms.MenuItem();
+ this.goToProcessNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.copyNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.closeNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuNetwork = new System.Windows.Forms.ContextMenu();
+ this.toolsNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.whoisNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.tracertNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.pingNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.menuItem6 = new System.Windows.Forms.MenuItem();
+ this.selectAllNetworkMenuItem = new System.Windows.Forms.MenuItem();
+ this.vistaMenu = new wyDay.Controls.VistaMenu(this.components);
+ ((System.ComponentModel.ISupportInitialize)(this.statusGeneral)).BeginInit();
+ ((System.ComponentModel.ISupportInitialize)(this.statusCPU)).BeginInit();
+ ((System.ComponentModel.ISupportInitialize)(this.statusMemory)).BeginInit();
this.tabControl.SuspendLayout();
this.tabProcesses.SuspendLayout();
- this.contextMenuStripProcess.SuspendLayout();
this.tabServices.SuspendLayout();
- this.contextMenuStripService.SuspendLayout();
this.tabNetwork.SuspendLayout();
- this.contextMenuStripNetwork.SuspendLayout();
this.toolStrip.SuspendLayout();
- this.statusStrip1.SuspendLayout();
- this.menuStripEx1.SuspendLayout();
- this.contextMenuStripTray.SuspendLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).BeginInit();
this.SuspendLayout();
//
+ // menuProcess
+ //
+ this.menuProcess.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.terminateMenuItem,
+ this.terminateProcessTreeMenuItem,
+ this.suspendMenuItem,
+ this.resumeMenuItem,
+ this.restartProcessMenuItem,
+ this.reduceWorkingSetProcessMenuItem,
+ this.virtualizationProcessMenuItem,
+ this.menuItem5,
+ this.affinityProcessMenuItem,
+ this.createDumpFileProcessMenuItem,
+ this.terminatorProcessMenuItem,
+ this.miscellaneousProcessMenuItem,
+ this.priorityMenuItem,
+ this.runAsProcessMenuItem,
+ this.windowProcessMenuItem,
+ this.propertiesProcessMenuItem,
+ this.menuItem7,
+ this.searchProcessMenuItem,
+ this.reanalyzeProcessMenuItem,
+ this.copyProcessMenuItem,
+ this.selectAllProcessMenuItem});
+ this.menuProcess.Popup += new System.EventHandler(this.menuProcess_Popup);
+ //
+ // terminateMenuItem
+ //
+ this.vistaMenu.SetImage(this.terminateMenuItem, global::ProcessHacker.Properties.Resources.cross);
+ this.terminateMenuItem.Index = 0;
+ this.terminateMenuItem.Shortcut = System.Windows.Forms.Shortcut.Del;
+ this.terminateMenuItem.Text = "&Terminate";
+ this.terminateMenuItem.Click += new System.EventHandler(this.terminateMenuItem_Click);
+ //
+ // terminateProcessTreeMenuItem
+ //
+ this.terminateProcessTreeMenuItem.Index = 1;
+ this.terminateProcessTreeMenuItem.Text = "Terminate Process Tree";
+ this.terminateProcessTreeMenuItem.Click += new System.EventHandler(this.terminateProcessTreeMenuItem_Click);
+ //
+ // suspendMenuItem
+ //
+ this.vistaMenu.SetImage(this.suspendMenuItem, global::ProcessHacker.Properties.Resources.control_pause_blue);
+ this.suspendMenuItem.Index = 2;
+ this.suspendMenuItem.Text = "&Suspend";
+ this.suspendMenuItem.Click += new System.EventHandler(this.suspendMenuItem_Click);
+ //
+ // resumeMenuItem
+ //
+ this.vistaMenu.SetImage(this.resumeMenuItem, global::ProcessHacker.Properties.Resources.control_play_blue);
+ this.resumeMenuItem.Index = 3;
+ this.resumeMenuItem.Text = "&Resume";
+ this.resumeMenuItem.Click += new System.EventHandler(this.resumeMenuItem_Click);
+ //
+ // restartProcessMenuItem
+ //
+ this.restartProcessMenuItem.Index = 4;
+ this.restartProcessMenuItem.Text = "Restart";
+ this.restartProcessMenuItem.Click += new System.EventHandler(this.restartProcessMenuItem_Click);
+ //
+ // reduceWorkingSetProcessMenuItem
+ //
+ this.reduceWorkingSetProcessMenuItem.Index = 5;
+ this.reduceWorkingSetProcessMenuItem.Text = "Reduce Working Set";
+ this.reduceWorkingSetProcessMenuItem.Click += new System.EventHandler(this.reduceWorkingSetProcessMenuItem_Click);
+ //
+ // virtualizationProcessMenuItem
+ //
+ this.virtualizationProcessMenuItem.Index = 6;
+ this.virtualizationProcessMenuItem.Text = "Virtualization";
+ this.virtualizationProcessMenuItem.Click += new System.EventHandler(this.virtualizationProcessMenuItem_Click);
+ //
+ // menuItem5
+ //
+ this.menuItem5.Index = 7;
+ this.menuItem5.Text = "-";
+ //
+ // affinityProcessMenuItem
+ //
+ this.affinityProcessMenuItem.Index = 8;
+ this.affinityProcessMenuItem.Text = "Affinity...";
+ this.affinityProcessMenuItem.Click += new System.EventHandler(this.affinityProcessMenuItem_Click);
+ //
+ // createDumpFileProcessMenuItem
+ //
+ this.createDumpFileProcessMenuItem.Index = 9;
+ this.createDumpFileProcessMenuItem.Text = "Create Dump File...";
+ this.createDumpFileProcessMenuItem.Click += new System.EventHandler(this.createDumpFileProcessMenuItem_Click);
+ //
+ // terminatorProcessMenuItem
+ //
+ this.terminatorProcessMenuItem.Index = 10;
+ this.terminatorProcessMenuItem.Text = "Terminator";
+ this.terminatorProcessMenuItem.Click += new System.EventHandler(this.terminatorProcessMenuItem_Click);
+ //
+ // miscellaneousProcessMenuItem
+ //
+ this.miscellaneousProcessMenuItem.Index = 11;
+ this.miscellaneousProcessMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.analyzeWaitChainProcessMenuItem,
+ this.detachFromDebuggerProcessMenuItem,
+ this.heapsProcessMenuItem,
+ this.injectDllProcessMenuItem,
+ this.ioPriorityThreadMenuItem,
+ this.protectionProcessMenuItem,
+ this.setTokenProcessMenuItem,
+ this.VirusTotalMenuItem});
+ this.miscellaneousProcessMenuItem.Text = "Miscellaneous";
+ //
+ // analyzeWaitChainProcessMenuItem
+ //
+ this.analyzeWaitChainProcessMenuItem.Index = 0;
+ this.analyzeWaitChainProcessMenuItem.Text = "Analyze Wait Chain";
+ this.analyzeWaitChainProcessMenuItem.Click += new System.EventHandler(this.analyzeWaitChainProcessMenuItem_Click);
+ //
+ // detachFromDebuggerProcessMenuItem
+ //
+ this.detachFromDebuggerProcessMenuItem.Index = 1;
+ this.detachFromDebuggerProcessMenuItem.Text = "Detach from Debugger";
+ this.detachFromDebuggerProcessMenuItem.Click += new System.EventHandler(this.detachFromDebuggerProcessMenuItem_Click);
+ //
+ // heapsProcessMenuItem
+ //
+ this.heapsProcessMenuItem.Index = 2;
+ this.heapsProcessMenuItem.Text = "Heaps";
+ this.heapsProcessMenuItem.Click += new System.EventHandler(this.heapsProcessMenuItem_Click);
+ //
+ // injectDllProcessMenuItem
+ //
+ this.injectDllProcessMenuItem.Index = 3;
+ this.injectDllProcessMenuItem.Text = "Inject DLL...";
+ this.injectDllProcessMenuItem.Click += new System.EventHandler(this.injectDllProcessMenuItem_Click);
+ //
+ // ioPriorityThreadMenuItem
+ //
+ this.ioPriorityThreadMenuItem.Index = 4;
+ this.ioPriorityThreadMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.ioPriority0ThreadMenuItem,
+ this.ioPriority1ThreadMenuItem,
+ this.ioPriority2ThreadMenuItem,
+ this.ioPriority3ThreadMenuItem});
+ this.ioPriorityThreadMenuItem.Text = "I/O Priority";
+ //
+ // ioPriority0ThreadMenuItem
+ //
+ this.ioPriority0ThreadMenuItem.Index = 0;
+ this.ioPriority0ThreadMenuItem.Text = "0";
+ this.ioPriority0ThreadMenuItem.Click += new System.EventHandler(this.ioPriority0ThreadMenuItem_Click);
+ //
+ // ioPriority1ThreadMenuItem
+ //
+ this.ioPriority1ThreadMenuItem.Index = 1;
+ this.ioPriority1ThreadMenuItem.Text = "1";
+ this.ioPriority1ThreadMenuItem.Click += new System.EventHandler(this.ioPriority1ThreadMenuItem_Click);
+ //
+ // ioPriority2ThreadMenuItem
+ //
+ this.ioPriority2ThreadMenuItem.Index = 2;
+ this.ioPriority2ThreadMenuItem.Text = "2";
+ this.ioPriority2ThreadMenuItem.Click += new System.EventHandler(this.ioPriority2ThreadMenuItem_Click);
+ //
+ // ioPriority3ThreadMenuItem
+ //
+ this.ioPriority3ThreadMenuItem.Index = 3;
+ this.ioPriority3ThreadMenuItem.Text = "3";
+ this.ioPriority3ThreadMenuItem.Click += new System.EventHandler(this.ioPriority3ThreadMenuItem_Click);
+ //
+ // protectionProcessMenuItem
+ //
+ this.protectionProcessMenuItem.Index = 5;
+ this.protectionProcessMenuItem.Text = "Protection";
+ this.protectionProcessMenuItem.Click += new System.EventHandler(this.protectionProcessMenuItem_Click);
+ //
+ // setTokenProcessMenuItem
+ //
+ this.setTokenProcessMenuItem.Index = 6;
+ this.setTokenProcessMenuItem.Text = "Set Token...";
+ this.setTokenProcessMenuItem.Click += new System.EventHandler(this.setTokenProcessMenuItem_Click);
+ //
+ // VirusTotalMenuItem
+ //
+ this.VirusTotalMenuItem.Index = 7;
+ this.VirusTotalMenuItem.Text = "Upload to VirusTotal";
+ this.VirusTotalMenuItem.Click += new System.EventHandler(this.virusTotalMenuItem_Click);
+ //
+ // priorityMenuItem
+ //
+ this.vistaMenu.SetImage(this.priorityMenuItem, global::ProcessHacker.Properties.Resources.control_equalizer_blue);
+ this.priorityMenuItem.Index = 12;
+ this.priorityMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.realTimeMenuItem,
+ this.highMenuItem,
+ this.aboveNormalMenuItem,
+ this.normalMenuItem,
+ this.belowNormalMenuItem,
+ this.idleMenuItem});
+ this.priorityMenuItem.Text = "&Priority";
+ //
+ // realTimeMenuItem
+ //
+ this.realTimeMenuItem.Index = 0;
+ this.realTimeMenuItem.RadioCheck = true;
+ this.realTimeMenuItem.Text = "Real Time";
+ this.realTimeMenuItem.Click += new System.EventHandler(this.realTimeMenuItem_Click);
+ //
+ // highMenuItem
+ //
+ this.highMenuItem.Index = 1;
+ this.highMenuItem.RadioCheck = true;
+ this.highMenuItem.Text = "High";
+ this.highMenuItem.Click += new System.EventHandler(this.highMenuItem_Click);
+ //
+ // aboveNormalMenuItem
+ //
+ this.aboveNormalMenuItem.Index = 2;
+ this.aboveNormalMenuItem.RadioCheck = true;
+ this.aboveNormalMenuItem.Text = "Above Normal";
+ this.aboveNormalMenuItem.Click += new System.EventHandler(this.aboveNormalMenuItem_Click);
+ //
+ // normalMenuItem
+ //
+ this.normalMenuItem.Index = 3;
+ this.normalMenuItem.RadioCheck = true;
+ this.normalMenuItem.Text = "Normal";
+ this.normalMenuItem.Click += new System.EventHandler(this.normalMenuItem_Click);
+ //
+ // belowNormalMenuItem
+ //
+ this.belowNormalMenuItem.Index = 4;
+ this.belowNormalMenuItem.RadioCheck = true;
+ this.belowNormalMenuItem.Text = "Below Normal";
+ this.belowNormalMenuItem.Click += new System.EventHandler(this.belowNormalMenuItem_Click);
+ //
+ // idleMenuItem
+ //
+ this.idleMenuItem.Index = 5;
+ this.idleMenuItem.RadioCheck = true;
+ this.idleMenuItem.Text = "Idle";
+ this.idleMenuItem.Click += new System.EventHandler(this.idleMenuItem_Click);
+ //
+ // runAsProcessMenuItem
+ //
+ this.runAsProcessMenuItem.Index = 13;
+ this.runAsProcessMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.launchAsUserProcessMenuItem,
+ this.launchAsThisUserProcessMenuItem});
+ this.runAsProcessMenuItem.Text = "Run As";
+ //
+ // launchAsUserProcessMenuItem
+ //
+ this.launchAsUserProcessMenuItem.Index = 0;
+ this.launchAsUserProcessMenuItem.Text = "Launch As User...";
+ this.launchAsUserProcessMenuItem.Click += new System.EventHandler(this.launchAsUserProcessMenuItem_Click);
+ //
+ // launchAsThisUserProcessMenuItem
+ //
+ this.launchAsThisUserProcessMenuItem.Index = 1;
+ this.launchAsThisUserProcessMenuItem.Text = "Launch As This User...";
+ this.launchAsThisUserProcessMenuItem.Click += new System.EventHandler(this.launchAsThisUserProcessMenuItem_Click);
+ //
+ // windowProcessMenuItem
+ //
+ this.windowProcessMenuItem.Index = 14;
+ this.windowProcessMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.bringToFrontProcessMenuItem,
+ this.restoreProcessMenuItem,
+ this.minimizeProcessMenuItem,
+ this.maximizeProcessMenuItem,
+ this.menuItem15,
+ this.closeProcessMenuItem});
+ this.windowProcessMenuItem.Text = "&Window";
+ //
+ // bringToFrontProcessMenuItem
+ //
+ this.bringToFrontProcessMenuItem.Index = 0;
+ this.bringToFrontProcessMenuItem.Text = "&Bring to Front";
+ this.bringToFrontProcessMenuItem.Click += new System.EventHandler(this.bringToFrontProcessMenuItem_Click);
+ //
+ // restoreProcessMenuItem
+ //
+ this.restoreProcessMenuItem.Index = 1;
+ this.restoreProcessMenuItem.Text = "&Restore";
+ this.restoreProcessMenuItem.Click += new System.EventHandler(this.restoreProcessMenuItem_Click);
+ //
+ // minimizeProcessMenuItem
+ //
+ this.minimizeProcessMenuItem.Index = 2;
+ this.minimizeProcessMenuItem.Text = "&Minimize";
+ this.minimizeProcessMenuItem.Click += new System.EventHandler(this.minimizeProcessMenuItem_Click);
+ //
+ // maximizeProcessMenuItem
+ //
+ this.maximizeProcessMenuItem.Index = 3;
+ this.maximizeProcessMenuItem.Text = "Ma&ximize";
+ this.maximizeProcessMenuItem.Click += new System.EventHandler(this.maximizeProcessMenuItem_Click);
+ //
+ // menuItem15
+ //
+ this.menuItem15.Index = 4;
+ this.menuItem15.Text = "-";
+ //
+ // closeProcessMenuItem
+ //
+ this.closeProcessMenuItem.Index = 5;
+ this.closeProcessMenuItem.Text = "&Close";
+ this.closeProcessMenuItem.Click += new System.EventHandler(this.closeProcessMenuItem_Click);
+ //
+ // propertiesProcessMenuItem
+ //
+ this.propertiesProcessMenuItem.DefaultItem = true;
+ this.vistaMenu.SetImage(this.propertiesProcessMenuItem, global::ProcessHacker.Properties.Resources.application_form_magnify);
+ this.propertiesProcessMenuItem.Index = 15;
+ this.propertiesProcessMenuItem.Text = "&Properties";
+ this.propertiesProcessMenuItem.Click += new System.EventHandler(this.propertiesProcessMenuItem_Click);
+ //
+ // menuItem7
+ //
+ this.menuItem7.Index = 16;
+ this.menuItem7.Text = "-";
+ //
+ // searchProcessMenuItem
+ //
+ this.searchProcessMenuItem.Index = 17;
+ this.searchProcessMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlM;
+ this.searchProcessMenuItem.Text = "&Search Online";
+ this.searchProcessMenuItem.Click += new System.EventHandler(this.searchProcessMenuItem_Click);
+ //
+ // reanalyzeProcessMenuItem
+ //
+ this.reanalyzeProcessMenuItem.Index = 18;
+ this.reanalyzeProcessMenuItem.Text = "Re-analyze";
+ this.reanalyzeProcessMenuItem.Click += new System.EventHandler(this.reanalyzeProcessMenuItem_Click);
+ //
+ // copyProcessMenuItem
+ //
+ this.vistaMenu.SetImage(this.copyProcessMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
+ this.copyProcessMenuItem.Index = 19;
+ this.copyProcessMenuItem.Text = "&Copy";
+ //
+ // selectAllProcessMenuItem
+ //
+ this.selectAllProcessMenuItem.Index = 20;
+ this.selectAllProcessMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
+ this.selectAllProcessMenuItem.Text = "Select &All";
+ this.selectAllProcessMenuItem.Click += new System.EventHandler(this.selectAllProcessMenuItem_Click);
+ //
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
@@ -243,409 +585,391 @@ private void InitializeComponent()
this.toolStripMenuItem15.Size = new System.Drawing.Size(151, 22);
this.toolStripMenuItem15.Text = "Idle";
//
- // tabControl
- //
- this.tabControl.Controls.Add(this.tabProcesses);
- this.tabControl.Controls.Add(this.tabServices);
- this.tabControl.Controls.Add(this.tabNetwork);
- this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
- this.tabControl.Location = new System.Drawing.Point(0, 52);
- this.tabControl.Name = "tabControl";
- this.tabControl.SelectedIndex = 0;
- this.tabControl.Size = new System.Drawing.Size(804, 494);
- this.tabControl.TabIndex = 6;
- this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabControlBig_SelectedIndexChanged);
+ // mainMenu
//
- // tabProcesses
+ this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.hackerMenuItem,
+ this.viewMenuItem,
+ this.toolsMenuItem,
+ this.usersMenuItem,
+ this.windowMenuItem,
+ this.helpMenu});
//
- this.tabProcesses.Controls.Add(this.treeProcesses);
- this.tabProcesses.Location = new System.Drawing.Point(4, 22);
- this.tabProcesses.Name = "tabProcesses";
- this.tabProcesses.Padding = new System.Windows.Forms.Padding(3);
- this.tabProcesses.Size = new System.Drawing.Size(796, 468);
- this.tabProcesses.TabIndex = 0;
- this.tabProcesses.Text = "Processes";
- this.tabProcesses.UseVisualStyleBackColor = true;
+ // hackerMenuItem
//
- // treeProcesses
+ this.hackerMenuItem.Index = 0;
+ this.hackerMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.runMenuItem,
+ this.runAsAdministratorMenuItem,
+ this.runAsMenuItem,
+ this.runAsServiceMenuItem,
+ this.showDetailsForAllProcessesMenuItem,
+ this.uacSeparatorMenuItem,
+ this.openMenuItem,
+ this.saveMenuItem,
+ this.findHandlesMenuItem,
+ this.inspectPEFileMenuItem,
+ this.reloadStructsMenuItem,
+ this.optionsMenuItem,
+ this.menuItem2,
+ this.shutdownMenuItem,
+ this.exitMenuItem});
+ this.hackerMenuItem.Text = "&Hacker";
//
- this.treeProcesses.ContextMenuStrip = this.contextMenuStripProcess;
- this.treeProcesses.Dock = System.Windows.Forms.DockStyle.Fill;
- this.treeProcesses.Draw = true;
- this.treeProcesses.DumpMode = false;
- this.treeProcesses.DumpProcesses = null;
- this.treeProcesses.DumpProcessServices = null;
- this.treeProcesses.DumpServices = null;
- this.treeProcesses.DumpUserName = null;
- this.treeProcesses.Location = new System.Drawing.Point(3, 3);
- this.treeProcesses.Name = "treeProcesses";
- this.treeProcesses.Provider = null;
- this.treeProcesses.Size = new System.Drawing.Size(790, 462);
- this.treeProcesses.TabIndex = 4;
- this.treeProcesses.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeProcesses_KeyDown);
- this.treeProcesses.SelectionChanged += new System.EventHandler(this.treeProcesses_SelectionChanged);
- this.treeProcesses.NodeMouseDoubleClick += new System.EventHandler(this.treeProcesses_NodeMouseDoubleClick);
+ // runMenuItem
//
- // contextMenuStripProcess
- //
- this.contextMenuStripProcess.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.terminateToolStripMenuItem,
- this.terminateProcessTreeToolStripMenuItem,
- this.suspendToolStripMenuItem,
- this.resumeToolStripMenuItem,
- this.restartToolStripMenuItem,
- this.reduceWorkingSetToolStripMenuItem,
- this.virtualizationToolStripMenuItem,
- this.toolStripSeparator14,
- this.affinityToolStripMenuItem,
- this.createDumpFileToolStripMenuItem,
- this.terminatorToolStripMenuItem,
- this.miscellaneousToolStripMenuItem,
- this.priorityToolStripMenuItem,
- this.runAsToolStripMenuItem1,
- this.windowToolStripMenuItem1,
- this.toolStripSeparator15,
- this.searchOnlineToolStripMenuItem,
- this.reanalyzeToolStripMenuItem,
- this.copyProcessMenuItem,
- this.selectAllToolStripMenuItem,
- this.toolStripSeparator16,
- this.propertiesToolStripMenuItem1});
- this.contextMenuStripProcess.Name = "contextMenuStripProcess";
- this.contextMenuStripProcess.Size = new System.Drawing.Size(198, 462);
+ this.runMenuItem.Index = 0;
+ this.runMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlR;
+ this.runMenuItem.Text = "&Run...";
+ this.runMenuItem.Click += new System.EventHandler(this.runMenuItem_Click);
//
- // terminateToolStripMenuItem
+ // runAsAdministratorMenuItem
//
- this.terminateToolStripMenuItem.Name = "terminateToolStripMenuItem";
- this.terminateToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.terminateToolStripMenuItem.Text = "&Terminate";
- this.terminateToolStripMenuItem.Click += new System.EventHandler(this.terminateMenuItem_Click);
+ this.runAsAdministratorMenuItem.Index = 1;
+ this.runAsAdministratorMenuItem.Text = "Run As Administrator...";
+ this.runAsAdministratorMenuItem.Click += new System.EventHandler(this.runAsAdministratorMenuItem_Click);
//
- // terminateProcessTreeToolStripMenuItem
+ // runAsMenuItem
//
- this.terminateProcessTreeToolStripMenuItem.Name = "terminateProcessTreeToolStripMenuItem";
- this.terminateProcessTreeToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.terminateProcessTreeToolStripMenuItem.Text = "Terminate Process Tree";
- this.terminateProcessTreeToolStripMenuItem.Click += new System.EventHandler(this.terminateProcessTreeMenuItem_Click);
+ this.runAsMenuItem.Index = 2;
+ this.runAsMenuItem.Text = "Run As...";
+ this.runAsMenuItem.Visible = false;
+ this.runAsMenuItem.Click += new System.EventHandler(this.runAsMenuItem_Click);
//
- // suspendToolStripMenuItem
+ // runAsServiceMenuItem
//
- this.suspendToolStripMenuItem.Name = "suspendToolStripMenuItem";
- this.suspendToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.suspendToolStripMenuItem.Text = "&Suspend";
- this.suspendToolStripMenuItem.Click += new System.EventHandler(this.suspendMenuItem_Click);
+ this.runAsServiceMenuItem.Index = 3;
+ this.runAsServiceMenuItem.Text = "Run As...";
+ this.runAsServiceMenuItem.Click += new System.EventHandler(this.runAsServiceMenuItem_Click);
//
- // resumeToolStripMenuItem
+ // showDetailsForAllProcessesMenuItem
//
- this.resumeToolStripMenuItem.Name = "resumeToolStripMenuItem";
- this.resumeToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.resumeToolStripMenuItem.Text = "&Resume";
- this.resumeToolStripMenuItem.Click += new System.EventHandler(this.resumeMenuItem_Click);
+ this.showDetailsForAllProcessesMenuItem.Index = 4;
+ this.showDetailsForAllProcessesMenuItem.Text = "Show Details for All Processes";
+ this.showDetailsForAllProcessesMenuItem.Click += new System.EventHandler(this.showDetailsForAllProcessesMenuItem_Click);
//
- // restartToolStripMenuItem
+ // uacSeparatorMenuItem
//
- this.restartToolStripMenuItem.Name = "restartToolStripMenuItem";
- this.restartToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.restartToolStripMenuItem.Text = "Restart";
- this.restartToolStripMenuItem.Click += new System.EventHandler(this.restartProcessMenuItem_Click);
+ this.uacSeparatorMenuItem.Index = 5;
+ this.uacSeparatorMenuItem.Text = "-";
//
- // reduceWorkingSetToolStripMenuItem
+ // openMenuItem
//
- this.reduceWorkingSetToolStripMenuItem.Name = "reduceWorkingSetToolStripMenuItem";
- this.reduceWorkingSetToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.reduceWorkingSetToolStripMenuItem.Text = "Reduce Working Set";
- this.reduceWorkingSetToolStripMenuItem.Click += new System.EventHandler(this.reduceWorkingSetProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.openMenuItem, global::ProcessHacker.Properties.Resources.folder);
+ this.openMenuItem.Index = 6;
+ this.openMenuItem.Text = "Open...";
+ this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
//
- // virtualizationToolStripMenuItem
+ // saveMenuItem
//
- this.virtualizationToolStripMenuItem.Name = "virtualizationToolStripMenuItem";
- this.virtualizationToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.virtualizationToolStripMenuItem.Text = "Virtualization";
- this.virtualizationToolStripMenuItem.Click += new System.EventHandler(this.virtualizationProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.saveMenuItem, global::ProcessHacker.Properties.Resources.disk);
+ this.saveMenuItem.Index = 7;
+ this.saveMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
+ this.saveMenuItem.Text = "Save...";
+ this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click);
//
- // toolStripSeparator14
+ // findHandlesMenuItem
//
- this.toolStripSeparator14.Name = "toolStripSeparator14";
- this.toolStripSeparator14.Size = new System.Drawing.Size(194, 6);
+ this.vistaMenu.SetImage(this.findHandlesMenuItem, global::ProcessHacker.Properties.Resources.find);
+ this.findHandlesMenuItem.Index = 8;
+ this.findHandlesMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF;
+ this.findHandlesMenuItem.Text = "&Find Handles or DLLs...";
+ this.findHandlesMenuItem.Click += new System.EventHandler(this.findHandlesMenuItem_Click);
//
- // affinityToolStripMenuItem
+ // inspectPEFileMenuItem
//
- this.affinityToolStripMenuItem.Name = "affinityToolStripMenuItem";
- this.affinityToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.affinityToolStripMenuItem.Text = "Affinity...";
- this.affinityToolStripMenuItem.Click += new System.EventHandler(this.affinityProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.inspectPEFileMenuItem, global::ProcessHacker.Properties.Resources.application_form_magnify);
+ this.inspectPEFileMenuItem.Index = 9;
+ this.inspectPEFileMenuItem.Text = "Inspect &PE File...";
+ this.inspectPEFileMenuItem.Click += new System.EventHandler(this.inspectPEFileMenuItem_Click);
//
- // createDumpFileToolStripMenuItem
+ // reloadStructsMenuItem
//
- this.createDumpFileToolStripMenuItem.Name = "createDumpFileToolStripMenuItem";
- this.createDumpFileToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.createDumpFileToolStripMenuItem.Text = "Create Dump File...";
- this.createDumpFileToolStripMenuItem.Click += new System.EventHandler(this.createDumpFileProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.reloadStructsMenuItem, global::ProcessHacker.Properties.Resources.arrow_refresh);
+ this.reloadStructsMenuItem.Index = 10;
+ this.reloadStructsMenuItem.Text = "Reload Struct Definitions";
+ this.reloadStructsMenuItem.Click += new System.EventHandler(this.reloadStructsMenuItem_Click);
//
- // terminatorToolStripMenuItem
+ // optionsMenuItem
//
- this.terminatorToolStripMenuItem.Name = "terminatorToolStripMenuItem";
- this.terminatorToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.terminatorToolStripMenuItem.Text = "Terminator";
- this.terminatorToolStripMenuItem.Click += new System.EventHandler(this.terminatorProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.optionsMenuItem, global::ProcessHacker.Properties.Resources.page_gear);
+ this.optionsMenuItem.Index = 11;
+ this.optionsMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
+ this.optionsMenuItem.Text = "&Options...";
+ this.optionsMenuItem.Click += new System.EventHandler(this.optionsMenuItem_Click);
//
- // miscellaneousToolStripMenuItem
+ // menuItem2
//
- this.miscellaneousToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.analyzeWaitChainToolStripMenuItem,
- this.detachFromDebuggerToolStripMenuItem,
- this.heapsToolStripMenuItem,
- this.injectDLLToolStripMenuItem,
- this.iOPriorityToolStripMenuItem,
- this.protectionToolStripMenuItem,
- this.setTokenToolStripMenuItem,
- this.uploadToVirusTotalToolStripMenuItem});
- this.miscellaneousToolStripMenuItem.Name = "miscellaneousToolStripMenuItem";
- this.miscellaneousToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.miscellaneousToolStripMenuItem.Text = "Miscellaneous";
+ this.menuItem2.Index = 12;
+ this.menuItem2.Text = "-";
//
- // analyzeWaitChainToolStripMenuItem
+ // shutdownMenuItem
//
- this.analyzeWaitChainToolStripMenuItem.Name = "analyzeWaitChainToolStripMenuItem";
- this.analyzeWaitChainToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.analyzeWaitChainToolStripMenuItem.Text = "Analyze Wait Chain";
+ this.shutdownMenuItem.Index = 13;
+ this.shutdownMenuItem.Text = "Shutdown";
//
- // detachFromDebuggerToolStripMenuItem
+ // exitMenuItem
//
- this.detachFromDebuggerToolStripMenuItem.Name = "detachFromDebuggerToolStripMenuItem";
- this.detachFromDebuggerToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.detachFromDebuggerToolStripMenuItem.Text = "Detach from Debugger";
+ this.vistaMenu.SetImage(this.exitMenuItem, global::ProcessHacker.Properties.Resources.door_out);
+ this.exitMenuItem.Index = 14;
+ this.exitMenuItem.Text = "E&xit";
+ this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click);
//
- // heapsToolStripMenuItem
+ // viewMenuItem
//
- this.heapsToolStripMenuItem.Name = "heapsToolStripMenuItem";
- this.heapsToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.heapsToolStripMenuItem.Text = "Heaps";
+ this.viewMenuItem.Index = 1;
+ this.viewMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.toolbarMenuItem,
+ this.sysInfoMenuItem,
+ this.trayIconsMenuItem,
+ this.menuItem3,
+ this.updateNowMenuItem,
+ this.updateProcessesMenuItem,
+ this.updateServicesMenuItem});
+ this.viewMenuItem.Text = "&View";
//
- // injectDLLToolStripMenuItem
+ // toolbarMenuItem
//
- this.injectDLLToolStripMenuItem.Name = "injectDLLToolStripMenuItem";
- this.injectDLLToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.injectDLLToolStripMenuItem.Text = "Inject DLL...";
+ this.toolbarMenuItem.Index = 0;
+ this.toolbarMenuItem.Text = "Toolbar";
+ this.toolbarMenuItem.Click += new System.EventHandler(this.toolbarMenuItem_Click);
//
- // iOPriorityToolStripMenuItem
+ // sysInfoMenuItem
//
- this.iOPriorityToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.ioPriority0ThreadMenuItem,
- this.ioPriority1ThreadMenuItem,
- this.ioPriority3ThreadMenuItem,
- this.toolStripMenuItem5});
- this.iOPriorityToolStripMenuItem.Name = "iOPriorityToolStripMenuItem";
- this.iOPriorityToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.iOPriorityToolStripMenuItem.Text = "I/O Priority";
+ this.sysInfoMenuItem.Index = 1;
+ this.sysInfoMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlI;
+ this.sysInfoMenuItem.Text = "System &Information";
+ this.sysInfoMenuItem.Click += new System.EventHandler(this.sysInfoMenuItem_Click);
//
- // ioPriority0ThreadMenuItem
+ // trayIconsMenuItem
//
- this.ioPriority0ThreadMenuItem.Name = "ioPriority0ThreadMenuItem";
- this.ioPriority0ThreadMenuItem.Size = new System.Drawing.Size(80, 22);
- this.ioPriority0ThreadMenuItem.Text = "0";
+ this.trayIconsMenuItem.Index = 2;
+ this.trayIconsMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.cpuHistoryMenuItem,
+ this.cpuUsageMenuItem,
+ this.ioHistoryMenuItem,
+ this.commitHistoryMenuItem,
+ this.physMemHistoryMenuItem});
+ this.trayIconsMenuItem.Text = "Tray Icons";
//
- // ioPriority1ThreadMenuItem
+ // cpuHistoryMenuItem
//
- this.ioPriority1ThreadMenuItem.Name = "ioPriority1ThreadMenuItem";
- this.ioPriority1ThreadMenuItem.Size = new System.Drawing.Size(80, 22);
- this.ioPriority1ThreadMenuItem.Text = "1";
+ this.cpuHistoryMenuItem.Index = 0;
+ this.cpuHistoryMenuItem.Text = "CPU History";
+ this.cpuHistoryMenuItem.Click += new System.EventHandler(this.cpuHistoryMenuItem_Click);
//
- // ioPriority3ThreadMenuItem
+ // cpuUsageMenuItem
//
- this.ioPriority3ThreadMenuItem.Name = "ioPriority3ThreadMenuItem";
- this.ioPriority3ThreadMenuItem.Size = new System.Drawing.Size(80, 22);
- this.ioPriority3ThreadMenuItem.Text = "2";
+ this.cpuUsageMenuItem.Index = 1;
+ this.cpuUsageMenuItem.Text = "CPU Usage";
+ this.cpuUsageMenuItem.Click += new System.EventHandler(this.cpuUsageMenuItem_Click);
//
- // toolStripMenuItem5
+ // ioHistoryMenuItem
//
- this.toolStripMenuItem5.Name = "toolStripMenuItem5";
- this.toolStripMenuItem5.Size = new System.Drawing.Size(80, 22);
- this.toolStripMenuItem5.Text = "3";
+ this.ioHistoryMenuItem.Index = 2;
+ this.ioHistoryMenuItem.Text = "I/O History";
+ this.ioHistoryMenuItem.Click += new System.EventHandler(this.ioHistoryMenuItem_Click);
//
- // protectionToolStripMenuItem
+ // commitHistoryMenuItem
//
- this.protectionToolStripMenuItem.Name = "protectionToolStripMenuItem";
- this.protectionToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.protectionToolStripMenuItem.Text = "Protection";
+ this.commitHistoryMenuItem.Index = 3;
+ this.commitHistoryMenuItem.Text = "Commit History";
+ this.commitHistoryMenuItem.Click += new System.EventHandler(this.commitHistoryMenuItem_Click);
//
- // setTokenToolStripMenuItem
+ // physMemHistoryMenuItem
//
- this.setTokenToolStripMenuItem.Name = "setTokenToolStripMenuItem";
- this.setTokenToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.setTokenToolStripMenuItem.Text = "Set Token...";
+ this.physMemHistoryMenuItem.Index = 4;
+ this.physMemHistoryMenuItem.Text = "Physical Memory History";
+ this.physMemHistoryMenuItem.Click += new System.EventHandler(this.physMemHistoryMenuItem_Click);
//
- // uploadToVirusTotalToolStripMenuItem
+ // menuItem3
//
- this.uploadToVirusTotalToolStripMenuItem.Name = "uploadToVirusTotalToolStripMenuItem";
- this.uploadToVirusTotalToolStripMenuItem.Size = new System.Drawing.Size(195, 22);
- this.uploadToVirusTotalToolStripMenuItem.Text = "Upload to VirusTotal";
+ this.menuItem3.Index = 3;
+ this.menuItem3.Text = "-";
//
- // priorityToolStripMenuItem
+ // updateNowMenuItem
//
- this.priorityToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.realTimeToolStripMenuItem,
- this.highToolStripMenuItem,
- this.aboveNormalToolStripMenuItem,
- this.normalToolStripMenuItem,
- this.belowNormalToolStripMenuItem,
- this.idleToolStripMenuItem});
- this.priorityToolStripMenuItem.Name = "priorityToolStripMenuItem";
- this.priorityToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.priorityToolStripMenuItem.Text = "&Priority";
+ this.vistaMenu.SetImage(this.updateNowMenuItem, global::ProcessHacker.Properties.Resources.arrow_refresh);
+ this.updateNowMenuItem.Index = 4;
+ this.updateNowMenuItem.Shortcut = System.Windows.Forms.Shortcut.F5;
+ this.updateNowMenuItem.Text = "&Refresh";
+ this.updateNowMenuItem.Click += new System.EventHandler(this.updateNowMenuItem_Click);
//
- // realTimeToolStripMenuItem
+ // updateProcessesMenuItem
//
- this.realTimeToolStripMenuItem.Name = "realTimeToolStripMenuItem";
- this.realTimeToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
- this.realTimeToolStripMenuItem.Text = "Real Time";
+ this.updateProcessesMenuItem.Index = 5;
+ this.updateProcessesMenuItem.Text = "Update &Processes";
+ this.updateProcessesMenuItem.Click += new System.EventHandler(this.updateProcessesMenuItem_Click);
//
- // highToolStripMenuItem
+ // updateServicesMenuItem
//
- this.highToolStripMenuItem.Name = "highToolStripMenuItem";
- this.highToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
- this.highToolStripMenuItem.Text = "High";
+ this.updateServicesMenuItem.Index = 6;
+ this.updateServicesMenuItem.Text = "Update &Services";
+ this.updateServicesMenuItem.Click += new System.EventHandler(this.updateServicesMenuItem_Click);
//
- // aboveNormalToolStripMenuItem
+ // toolsMenuItem
//
- this.aboveNormalToolStripMenuItem.Name = "aboveNormalToolStripMenuItem";
- this.aboveNormalToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
- this.aboveNormalToolStripMenuItem.Text = "Above Normal";
+ this.toolsMenuItem.Index = 2;
+ this.toolsMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.createServiceMenuItem,
+ this.hiddenProcessesMenuItem,
+ this.verifyFileSignatureMenuItem});
+ this.toolsMenuItem.Text = "&Tools";
//
- // normalToolStripMenuItem
+ // createServiceMenuItem
//
- this.normalToolStripMenuItem.Name = "normalToolStripMenuItem";
- this.normalToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
- this.normalToolStripMenuItem.Text = "Normal";
+ this.createServiceMenuItem.Index = 0;
+ this.createServiceMenuItem.Text = "Create &Service...";
+ this.createServiceMenuItem.Click += new System.EventHandler(this.createServiceMenuItem_Click);
//
- // belowNormalToolStripMenuItem
+ // hiddenProcessesMenuItem
//
- this.belowNormalToolStripMenuItem.Name = "belowNormalToolStripMenuItem";
- this.belowNormalToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
- this.belowNormalToolStripMenuItem.Text = "Below Normal";
+ this.hiddenProcessesMenuItem.Index = 1;
+ this.hiddenProcessesMenuItem.Text = "&Hidden Processes";
+ this.hiddenProcessesMenuItem.Click += new System.EventHandler(this.hiddenProcessesMenuItem_Click);
//
- // idleToolStripMenuItem
+ // verifyFileSignatureMenuItem
//
- this.idleToolStripMenuItem.Name = "idleToolStripMenuItem";
- this.idleToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
- this.idleToolStripMenuItem.Text = "Idle";
+ this.verifyFileSignatureMenuItem.Index = 2;
+ this.verifyFileSignatureMenuItem.Text = "&Verify File Signature...";
+ this.verifyFileSignatureMenuItem.Click += new System.EventHandler(this.verifyFileSignatureMenuItem_Click);
//
- // runAsToolStripMenuItem1
+ // usersMenuItem
//
- this.runAsToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.launchAsUserToolStripMenuItem,
- this.launchAsThisUserToolStripMenuItem});
- this.runAsToolStripMenuItem1.Name = "runAsToolStripMenuItem1";
- this.runAsToolStripMenuItem1.Size = new System.Drawing.Size(197, 22);
- this.runAsToolStripMenuItem1.Text = "Run As";
+ this.usersMenuItem.Index = 3;
+ this.usersMenuItem.Text = "&Users";
//
- // launchAsUserToolStripMenuItem
+ // windowMenuItem
//
- this.launchAsUserToolStripMenuItem.Name = "launchAsUserToolStripMenuItem";
- this.launchAsUserToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.launchAsUserToolStripMenuItem.Text = "Launch As User...";
+ this.windowMenuItem.Index = 4;
+ this.windowMenuItem.Text = "&Window";
//
- // launchAsThisUserToolStripMenuItem
+ // helpMenu
//
- this.launchAsThisUserToolStripMenuItem.Name = "launchAsThisUserToolStripMenuItem";
- this.launchAsThisUserToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.launchAsThisUserToolStripMenuItem.Text = "Launch As This User...";
+ this.helpMenu.Index = 5;
+ this.helpMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.freeMemoryMenuItem,
+ this.checkForUpdatesMenuItem,
+ this.menuItem1,
+ this.logMenuItem,
+ this.helpMenuItem,
+ this.donateMenuItem,
+ this.aboutMenuItem});
+ this.helpMenu.Text = "H&elp";
//
- // windowToolStripMenuItem1
+ // freeMemoryMenuItem
//
- this.windowToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.bringToFrontToolStripMenuItem,
- this.restoreToolStripMenuItem,
- this.minimizeToolStripMenuItem,
- this.maximizeToolStripMenuItem,
- this.toolStripSeparator17,
- this.closeToolStripMenuItem});
- this.windowToolStripMenuItem1.Name = "windowToolStripMenuItem1";
- this.windowToolStripMenuItem1.Size = new System.Drawing.Size(197, 22);
- this.windowToolStripMenuItem1.Text = "&Window";
+ this.freeMemoryMenuItem.Index = 0;
+ this.freeMemoryMenuItem.Text = "Free Memory";
+ this.freeMemoryMenuItem.Click += new System.EventHandler(this.freeMemoryMenuItem_Click);
//
- // bringToFrontToolStripMenuItem
+ // checkForUpdatesMenuItem
//
- this.bringToFrontToolStripMenuItem.Name = "bringToFrontToolStripMenuItem";
- this.bringToFrontToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
- this.bringToFrontToolStripMenuItem.Text = "&Bring to Front";
+ this.checkForUpdatesMenuItem.Index = 1;
+ this.checkForUpdatesMenuItem.Text = "Check for Updates";
+ this.checkForUpdatesMenuItem.Click += new System.EventHandler(this.checkForUpdatesMenuItem_Click);
//
- // restoreToolStripMenuItem
+ // menuItem1
//
- this.restoreToolStripMenuItem.Name = "restoreToolStripMenuItem";
- this.restoreToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
- this.restoreToolStripMenuItem.Text = "&Restore";
- this.restoreToolStripMenuItem.Click += new System.EventHandler(this.restoreProcessMenuItem_Click);
+ this.menuItem1.Index = 2;
+ this.menuItem1.Text = "-";
//
- // minimizeToolStripMenuItem
+ // logMenuItem
//
- this.minimizeToolStripMenuItem.Name = "minimizeToolStripMenuItem";
- this.minimizeToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
- this.minimizeToolStripMenuItem.Text = "&Minimize";
- this.minimizeToolStripMenuItem.Click += new System.EventHandler(this.minimizeProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.logMenuItem, global::ProcessHacker.Properties.Resources.page_white_text);
+ this.logMenuItem.Index = 3;
+ this.logMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlL;
+ this.logMenuItem.Text = "&Log";
+ this.logMenuItem.Click += new System.EventHandler(this.logMenuItem_Click);
//
- // maximizeToolStripMenuItem
+ // helpMenuItem
//
- this.maximizeToolStripMenuItem.Name = "maximizeToolStripMenuItem";
- this.maximizeToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
- this.maximizeToolStripMenuItem.Text = "Ma&ximize";
- this.maximizeToolStripMenuItem.Click += new System.EventHandler(this.maximizeProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.helpMenuItem, global::ProcessHacker.Properties.Resources.help);
+ this.helpMenuItem.Index = 4;
+ this.helpMenuItem.Shortcut = System.Windows.Forms.Shortcut.F1;
+ this.helpMenuItem.Text = "&Help";
+ this.helpMenuItem.Click += new System.EventHandler(this.helpMenuItem_Click);
//
- // toolStripSeparator17
+ // donateMenuItem
//
- this.toolStripSeparator17.Name = "toolStripSeparator17";
- this.toolStripSeparator17.Size = new System.Drawing.Size(144, 6);
+ this.vistaMenu.SetImage(this.donateMenuItem, global::ProcessHacker.Properties.Resources.money);
+ this.donateMenuItem.Index = 5;
+ this.donateMenuItem.Text = "Donate";
+ this.donateMenuItem.Click += new System.EventHandler(this.donateMenuItem_Click);
//
- // closeToolStripMenuItem
+ // aboutMenuItem
//
- this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
- this.closeToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
- this.closeToolStripMenuItem.Text = "&Close";
- this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeProcessMenuItem_Click);
+ this.vistaMenu.SetImage(this.aboutMenuItem, global::ProcessHacker.Properties.Resources.information);
+ this.aboutMenuItem.Index = 6;
+ this.aboutMenuItem.Text = "&About";
+ this.aboutMenuItem.Click += new System.EventHandler(this.aboutMenuItem_Click);
//
- // toolStripSeparator15
+ // statusBar
//
- this.toolStripSeparator15.Name = "toolStripSeparator15";
- this.toolStripSeparator15.Size = new System.Drawing.Size(194, 6);
+ this.statusBar.Location = new System.Drawing.Point(0, 350);
+ this.statusBar.Name = "statusBar";
+ this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
+ this.statusGeneral,
+ this.statusCPU,
+ this.statusMemory});
+ this.statusBar.ShowPanels = true;
+ this.statusBar.Size = new System.Drawing.Size(804, 22);
+ this.statusBar.TabIndex = 5;
//
- // searchOnlineToolStripMenuItem
+ // statusGeneral
//
- this.searchOnlineToolStripMenuItem.Name = "searchOnlineToolStripMenuItem";
- this.searchOnlineToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.searchOnlineToolStripMenuItem.Text = "&Search Online";
- this.searchOnlineToolStripMenuItem.Click += new System.EventHandler(this.searchProcessMenuItem_Click);
+ this.statusGeneral.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
+ this.statusGeneral.Name = "statusGeneral";
+ this.statusGeneral.Width = 10;
//
- // reanalyzeToolStripMenuItem
+ // statusCPU
//
- this.reanalyzeToolStripMenuItem.Name = "reanalyzeToolStripMenuItem";
- this.reanalyzeToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.reanalyzeToolStripMenuItem.Text = "Re-analyze";
- this.reanalyzeToolStripMenuItem.Click += new System.EventHandler(this.reanalyzeProcessMenuItem_Click);
+ this.statusCPU.Name = "statusCPU";
+ this.statusCPU.Text = "CPU: 99.99%";
+ this.statusCPU.Width = 80;
//
- // copyProcessMenuItem
+ // statusMemory
//
- this.copyProcessMenuItem.Name = "copyProcessMenuItem";
- this.copyProcessMenuItem.Size = new System.Drawing.Size(197, 22);
- this.copyProcessMenuItem.Text = "&Copy";
+ this.statusMemory.Name = "statusMemory";
+ this.statusMemory.Text = "Phys. Memory: 50%";
+ this.statusMemory.Width = 120;
//
- // selectAllToolStripMenuItem
+ // tabControl
//
- this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
- this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
- this.selectAllToolStripMenuItem.Text = "Select All";
- this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllProcessMenuItem_Click);
+ this.tabControl.Controls.Add(this.tabProcesses);
+ this.tabControl.Controls.Add(this.tabServices);
+ this.tabControl.Controls.Add(this.tabNetwork);
+ this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.tabControl.Location = new System.Drawing.Point(0, 25);
+ this.tabControl.Name = "tabControl";
+ this.tabControl.SelectedIndex = 0;
+ this.tabControl.Size = new System.Drawing.Size(804, 325);
+ this.tabControl.TabIndex = 6;
+ this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabControlBig_SelectedIndexChanged);
//
- // toolStripSeparator16
+ // tabProcesses
//
- this.toolStripSeparator16.Name = "toolStripSeparator16";
- this.toolStripSeparator16.Size = new System.Drawing.Size(194, 6);
+ this.tabProcesses.Controls.Add(this.treeProcesses);
+ this.tabProcesses.Location = new System.Drawing.Point(4, 22);
+ this.tabProcesses.Name = "tabProcesses";
+ this.tabProcesses.Padding = new System.Windows.Forms.Padding(3);
+ this.tabProcesses.Size = new System.Drawing.Size(796, 299);
+ this.tabProcesses.TabIndex = 0;
+ this.tabProcesses.Text = "Processes";
+ this.tabProcesses.UseVisualStyleBackColor = true;
//
- // propertiesToolStripMenuItem1
+ // treeProcesses
//
- this.propertiesToolStripMenuItem1.Name = "propertiesToolStripMenuItem1";
- this.propertiesToolStripMenuItem1.Size = new System.Drawing.Size(197, 22);
- this.propertiesToolStripMenuItem1.Text = "&Properties";
- this.propertiesToolStripMenuItem1.Click += new System.EventHandler(this.propertiesProcessMenuItem_Click);
+ this.treeProcesses.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.treeProcesses.Draw = true;
+ this.treeProcesses.Location = new System.Drawing.Point(3, 3);
+ this.treeProcesses.Name = "treeProcesses";
+ this.treeProcesses.Provider = null;
+ this.treeProcesses.Size = new System.Drawing.Size(790, 293);
+ this.treeProcesses.TabIndex = 4;
+ this.treeProcesses.SelectionChanged += new System.EventHandler(this.treeProcesses_SelectionChanged);
+ this.treeProcesses.NodeMouseDoubleClick += new System.EventHandler(this.treeProcesses_NodeMouseDoubleClick);
+ this.treeProcesses.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeProcesses_KeyDown);
//
// tabServices
//
@@ -653,118 +977,22 @@ private void InitializeComponent()
this.tabServices.Location = new System.Drawing.Point(4, 22);
this.tabServices.Name = "tabServices";
this.tabServices.Padding = new System.Windows.Forms.Padding(3);
- this.tabServices.Size = new System.Drawing.Size(796, 468);
+ this.tabServices.Size = new System.Drawing.Size(796, 299);
this.tabServices.TabIndex = 1;
this.tabServices.Text = "Services";
this.tabServices.UseVisualStyleBackColor = true;
//
// listServices
//
- this.listServices.ContextMenuStrip = this.contextMenuStripService;
this.listServices.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.listServices.DoubleBuffered = true;
this.listServices.Location = new System.Drawing.Point(3, 3);
this.listServices.Name = "listServices";
this.listServices.Provider = null;
- this.listServices.Size = new System.Drawing.Size(790, 462);
+ this.listServices.Size = new System.Drawing.Size(790, 293);
this.listServices.TabIndex = 0;
- this.listServices.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listServices_KeyDown);
this.listServices.DoubleClick += new System.EventHandler(this.listServices_DoubleClick);
- //
- // contextMenuStripService
- //
- this.contextMenuStripService.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.goToProcessServiceMenuItem,
- this.toolStripSeparator11,
- this.startToolStripMenuItem,
- this.pauseToolStripMenuItem,
- this.continueToolStripMenuItem,
- this.stopToolStripMenuItem,
- this.deleteToolStripMenuItem,
- this.toolStripSeparator12,
- this.copyToolStripMenuItem1,
- this.selectAllServiceMenuItem,
- this.toolStripSeparator13,
- this.propertiesToolStripMenuItem});
- this.contextMenuStripService.Name = "contextMenuStripService";
- this.contextMenuStripService.Size = new System.Drawing.Size(147, 220);
- this.contextMenuStripService.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStripService_Opening);
- //
- // goToProcessServiceMenuItem
- //
- this.goToProcessServiceMenuItem.Name = "goToProcessServiceMenuItem";
- this.goToProcessServiceMenuItem.Size = new System.Drawing.Size(146, 22);
- this.goToProcessServiceMenuItem.Text = "&Go to Process";
- this.goToProcessServiceMenuItem.Click += new System.EventHandler(this.goToProcessServiceMenuItem_Click);
- //
- // toolStripSeparator11
- //
- this.toolStripSeparator11.Name = "toolStripSeparator11";
- this.toolStripSeparator11.Size = new System.Drawing.Size(143, 6);
- //
- // startToolStripMenuItem
- //
- this.startToolStripMenuItem.Name = "startToolStripMenuItem";
- this.startToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
- this.startToolStripMenuItem.Text = "&Start";
- this.startToolStripMenuItem.Click += new System.EventHandler(this.startServiceMenuItem_Click);
- //
- // pauseToolStripMenuItem
- //
- this.pauseToolStripMenuItem.Name = "pauseToolStripMenuItem";
- this.pauseToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
- this.pauseToolStripMenuItem.Text = "&Pause";
- this.pauseToolStripMenuItem.Click += new System.EventHandler(this.pauseServiceMenuItem_Click);
- //
- // continueToolStripMenuItem
- //
- this.continueToolStripMenuItem.Name = "continueToolStripMenuItem";
- this.continueToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
- this.continueToolStripMenuItem.Text = "&Continue";
- this.continueToolStripMenuItem.Click += new System.EventHandler(this.continueServiceMenuItem_Click);
- //
- // stopToolStripMenuItem
- //
- this.stopToolStripMenuItem.Name = "stopToolStripMenuItem";
- this.stopToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
- this.stopToolStripMenuItem.Text = "S&top";
- this.stopToolStripMenuItem.Click += new System.EventHandler(this.stopServiceMenuItem_Click);
- //
- // deleteToolStripMenuItem
- //
- this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
- this.deleteToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
- this.deleteToolStripMenuItem.Text = "Delete";
- this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteServiceMenuItem_Click);
- //
- // toolStripSeparator12
- //
- this.toolStripSeparator12.Name = "toolStripSeparator12";
- this.toolStripSeparator12.Size = new System.Drawing.Size(143, 6);
- //
- // copyToolStripMenuItem1
- //
- this.copyToolStripMenuItem1.Name = "copyToolStripMenuItem1";
- this.copyToolStripMenuItem1.Size = new System.Drawing.Size(146, 22);
- this.copyToolStripMenuItem1.Text = "Copy";
- //
- // selectAllServiceMenuItem
- //
- this.selectAllServiceMenuItem.Name = "selectAllServiceMenuItem";
- this.selectAllServiceMenuItem.Size = new System.Drawing.Size(146, 22);
- this.selectAllServiceMenuItem.Text = "Select All";
- this.selectAllServiceMenuItem.Click += new System.EventHandler(this.selectAllServiceMenuItem_Click);
- //
- // toolStripSeparator13
- //
- this.toolStripSeparator13.Name = "toolStripSeparator13";
- this.toolStripSeparator13.Size = new System.Drawing.Size(143, 6);
- //
- // propertiesToolStripMenuItem
- //
- this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem";
- this.propertiesToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
- this.propertiesToolStripMenuItem.Text = "&Properties";
- this.propertiesToolStripMenuItem.Click += new System.EventHandler(this.propertiesServiceMenuItem_Click);
+ this.listServices.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listServices_KeyDown);
//
// tabNetwork
//
@@ -772,101 +1000,25 @@ private void InitializeComponent()
this.tabNetwork.Location = new System.Drawing.Point(4, 22);
this.tabNetwork.Name = "tabNetwork";
this.tabNetwork.Padding = new System.Windows.Forms.Padding(3);
- this.tabNetwork.Size = new System.Drawing.Size(796, 468);
+ this.tabNetwork.Size = new System.Drawing.Size(796, 299);
this.tabNetwork.TabIndex = 2;
this.tabNetwork.Text = "Network";
this.tabNetwork.UseVisualStyleBackColor = true;
//
// listNetwork
//
- this.listNetwork.ContextMenuStrip = this.contextMenuStripNetwork;
this.listNetwork.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.listNetwork.DoubleBuffered = true;
this.listNetwork.Location = new System.Drawing.Point(3, 3);
this.listNetwork.Name = "listNetwork";
this.listNetwork.Provider = null;
- this.listNetwork.Size = new System.Drawing.Size(790, 462);
+ this.listNetwork.Size = new System.Drawing.Size(790, 293);
this.listNetwork.TabIndex = 0;
- this.listNetwork.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listNetwork_KeyDown);
this.listNetwork.DoubleClick += new System.EventHandler(this.listNetwork_DoubleClick);
- //
- // contextMenuStripNetwork
- //
- this.contextMenuStripNetwork.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.goToProcessNetworkMenuItem,
- this.toolsToolStripMenuItem1,
- this.closeNetworkMenuItem,
- this.toolStripSeparator7,
- this.copyToolStripMenuItem,
- this.selectAllNetworkMenuItem});
- this.contextMenuStripNetwork.Name = "contextMenuStripNetwork";
- this.contextMenuStripNetwork.Size = new System.Drawing.Size(147, 120);
- //
- // goToProcessNetworkMenuItem
- //
- this.goToProcessNetworkMenuItem.Name = "goToProcessNetworkMenuItem";
- this.goToProcessNetworkMenuItem.Size = new System.Drawing.Size(146, 22);
- this.goToProcessNetworkMenuItem.Text = "&Go to Process";
- this.goToProcessNetworkMenuItem.Click += new System.EventHandler(this.goToProcessNetworkMenuItem_Click);
- //
- // toolsToolStripMenuItem1
- //
- this.toolsToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.whoisNetworkMenuItem,
- this.tracertNetworkMenuItem,
- this.pingNetworkMenuItem});
- this.toolsToolStripMenuItem1.Name = "toolsToolStripMenuItem1";
- this.toolsToolStripMenuItem1.Size = new System.Drawing.Size(146, 22);
- this.toolsToolStripMenuItem1.Text = "Tools";
- //
- // whoisNetworkMenuItem
- //
- this.whoisNetworkMenuItem.Name = "whoisNetworkMenuItem";
- this.whoisNetworkMenuItem.Size = new System.Drawing.Size(111, 22);
- this.whoisNetworkMenuItem.Text = "Whois";
- this.whoisNetworkMenuItem.Click += new System.EventHandler(this.whoisNetworkMenuItem_Click);
- //
- // tracertNetworkMenuItem
- //
- this.tracertNetworkMenuItem.Name = "tracertNetworkMenuItem";
- this.tracertNetworkMenuItem.Size = new System.Drawing.Size(111, 22);
- this.tracertNetworkMenuItem.Text = "Tracert";
- this.tracertNetworkMenuItem.Click += new System.EventHandler(this.tracertNetworkMenuItem_Click);
- //
- // pingNetworkMenuItem
- //
- this.pingNetworkMenuItem.Name = "pingNetworkMenuItem";
- this.pingNetworkMenuItem.Size = new System.Drawing.Size(111, 22);
- this.pingNetworkMenuItem.Text = "Ping";
- this.pingNetworkMenuItem.Click += new System.EventHandler(this.pingNetworkMenuItem_Click);
- //
- // closeNetworkMenuItem
- //
- this.closeNetworkMenuItem.Name = "closeNetworkMenuItem";
- this.closeNetworkMenuItem.Size = new System.Drawing.Size(146, 22);
- this.closeNetworkMenuItem.Text = "Close";
- this.closeNetworkMenuItem.Click += new System.EventHandler(this.closeNetworkMenuItem_Click);
- //
- // toolStripSeparator7
- //
- this.toolStripSeparator7.Name = "toolStripSeparator7";
- this.toolStripSeparator7.Size = new System.Drawing.Size(143, 6);
- //
- // copyToolStripMenuItem
- //
- this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
- this.copyToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
- this.copyToolStripMenuItem.Text = "Copy";
- //
- // selectAllNetworkMenuItem
- //
- this.selectAllNetworkMenuItem.Name = "selectAllNetworkMenuItem";
- this.selectAllNetworkMenuItem.Size = new System.Drawing.Size(146, 22);
- this.selectAllNetworkMenuItem.Text = "Select All";
- this.selectAllNetworkMenuItem.Click += new System.EventHandler(this.selectAllNetworkMenuItem_Click);
+ this.listNetwork.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listNetwork_KeyDown);
//
// toolStrip
//
- this.toolStrip.ClickThrough = true;
this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.refreshToolStripButton,
@@ -874,30 +1026,31 @@ private void InitializeComponent()
this.shutDownToolStripMenuItem,
this.toolStripSeparator1,
this.findHandlesToolStripButton,
- this.sysInfoToolStripButton,
- this.toolStripTextBox2});
- this.toolStrip.Location = new System.Drawing.Point(0, 24);
+ this.sysInfoToolStripButton});
+ this.toolStrip.Location = new System.Drawing.Point(0, 0);
this.toolStrip.Name = "toolStrip";
- this.toolStrip.Size = new System.Drawing.Size(804, 28);
+ this.toolStrip.Size = new System.Drawing.Size(804, 25);
this.toolStrip.TabIndex = 5;
this.toolStrip.Text = "toolStrip1";
//
// refreshToolStripButton
//
+ this.refreshToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.refreshToolStripButton.Image = global::ProcessHacker.Properties.Resources.arrow_refresh;
this.refreshToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.refreshToolStripButton.Name = "refreshToolStripButton";
- this.refreshToolStripButton.Size = new System.Drawing.Size(66, 25);
+ this.refreshToolStripButton.Size = new System.Drawing.Size(23, 22);
this.refreshToolStripButton.Text = "Refresh";
this.refreshToolStripButton.ToolTipText = "Refresh (F5)";
this.refreshToolStripButton.Click += new System.EventHandler(this.refreshToolStripButton_Click);
//
// optionsToolStripButton
//
+ this.optionsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.optionsToolStripButton.Image = global::ProcessHacker.Properties.Resources.cog_edit;
this.optionsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.optionsToolStripButton.Name = "optionsToolStripButton";
- this.optionsToolStripButton.Size = new System.Drawing.Size(69, 25);
+ this.optionsToolStripButton.Size = new System.Drawing.Size(23, 22);
this.optionsToolStripButton.Text = "Options";
this.optionsToolStripButton.ToolTipText = "Options... (Ctrl+O)";
this.optionsToolStripButton.Click += new System.EventHandler(this.optionsToolStripButton_Click);
@@ -908,561 +1061,331 @@ private void InitializeComponent()
this.shutDownToolStripMenuItem.Image = global::ProcessHacker.Properties.Resources.lightbulb_off;
this.shutDownToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.shutDownToolStripMenuItem.Name = "shutDownToolStripMenuItem";
- this.shutDownToolStripMenuItem.Size = new System.Drawing.Size(29, 25);
+ this.shutDownToolStripMenuItem.Size = new System.Drawing.Size(29, 22);
this.shutDownToolStripMenuItem.Text = "Shutdown";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
- this.toolStripSeparator1.Size = new System.Drawing.Size(6, 28);
+ this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// findHandlesToolStripButton
//
+ this.findHandlesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.findHandlesToolStripButton.Image = global::ProcessHacker.Properties.Resources.find;
this.findHandlesToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.findHandlesToolStripButton.Name = "findHandlesToolStripButton";
- this.findHandlesToolStripButton.Size = new System.Drawing.Size(147, 25);
+ this.findHandlesToolStripButton.Size = new System.Drawing.Size(23, 22);
this.findHandlesToolStripButton.Text = "Find Handles or DLLs...";
this.findHandlesToolStripButton.ToolTipText = "Find Handles or DLLs... (Ctrl+F)";
this.findHandlesToolStripButton.Click += new System.EventHandler(this.findHandlesToolStripButton_Click);
//
// sysInfoToolStripButton
//
+ this.sysInfoToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.sysInfoToolStripButton.Image = global::ProcessHacker.Properties.Resources.chart_line;
this.sysInfoToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.sysInfoToolStripButton.Name = "sysInfoToolStripButton";
- this.sysInfoToolStripButton.Size = new System.Drawing.Size(140, 25);
+ this.sysInfoToolStripButton.Size = new System.Drawing.Size(23, 22);
this.sysInfoToolStripButton.Text = "System Information...";
this.sysInfoToolStripButton.ToolTipText = "System Information... (Ctrl+I)";
this.sysInfoToolStripButton.Click += new System.EventHandler(this.sysInfoToolStripButton_Click);
//
- // toolStripTextBox2
- //
- this.toolStripTextBox2.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
- this.toolStripTextBox2.BackColor = System.Drawing.SystemColors.InactiveBorder;
- this.toolStripTextBox2.ForeColor = System.Drawing.SystemColors.GrayText;
- this.toolStripTextBox2.Name = "toolStripTextBox2";
- this.toolStripTextBox2.Size = new System.Drawing.Size(180, 25);
- //
- // statusStrip1
- //
- this.statusStrip1.AllowItemReorder = true;
- this.statusStrip1.BackColor = System.Drawing.SystemColors.Control;
- this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.statusMemory,
- this.statusCPU,
- this.statusGeneral});
- this.statusStrip1.Location = new System.Drawing.Point(0, 546);
- this.statusStrip1.Name = "statusStrip1";
- this.statusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
- this.statusStrip1.Size = new System.Drawing.Size(804, 22);
- this.statusStrip1.TabIndex = 7;
- this.statusStrip1.Text = "statusStrip1";
- //
- // statusMemory
- //
- this.statusMemory.Name = "statusMemory";
- this.statusMemory.Size = new System.Drawing.Size(52, 17);
- this.statusMemory.Text = "Memory";
- //
- // statusCPU
- //
- this.statusCPU.Name = "statusCPU";
- this.statusCPU.Size = new System.Drawing.Size(30, 17);
- this.statusCPU.Text = "CPU";
- //
- // statusGeneral
- //
- this.statusGeneral.Name = "statusGeneral";
- this.statusGeneral.Size = new System.Drawing.Size(47, 17);
- this.statusGeneral.Text = "General";
- //
- // menuStripEx1
- //
- this.menuStripEx1.ClickThrough = true;
- this.menuStripEx1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.hackerToolStripMenuItem,
- this.viewToolStripMenuItem,
- this.toolsToolStripMenuItem,
- this.usersToolStripMenuItem,
- this.windowToolStripMenuItem,
- this.helpToolStripMenuItem});
- this.menuStripEx1.Location = new System.Drawing.Point(0, 0);
- this.menuStripEx1.Name = "menuStripEx1";
- this.menuStripEx1.Size = new System.Drawing.Size(804, 24);
- this.menuStripEx1.TabIndex = 8;
- this.menuStripEx1.Text = "menuStripEx1";
- //
- // hackerToolStripMenuItem
- //
- this.hackerToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.runToolStripMenuItem,
- this.runAsToolStripMenuItem,
- this.runAsAdministratorMenuItem,
- this.showDetailsForAllProcessesMenuItem,
- this.toolStripSeparator4,
- this.openToolStripMenuItem,
- this.saveToolStripMenuItem,
- this.toolStripSeparator6,
- this.findHandlesMenuItem,
- this.inspectPEFileToolStripMenuItem,
- this.optionsMenuItem,
- this.toolStripSeparator5,
- this.shutdownMenuItem,
- this.exitToolStripMenuItem});
- this.hackerToolStripMenuItem.Name = "hackerToolStripMenuItem";
- this.hackerToolStripMenuItem.Size = new System.Drawing.Size(56, 20);
- this.hackerToolStripMenuItem.Text = "Hacker";
- //
- // runToolStripMenuItem
- //
- this.runToolStripMenuItem.Name = "runToolStripMenuItem";
- this.runToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
- this.runToolStripMenuItem.Text = "Run...";
- this.runToolStripMenuItem.Click += new System.EventHandler(this.runMenuItem_Click);
- //
- // runAsToolStripMenuItem
- //
- this.runAsToolStripMenuItem.Name = "runAsToolStripMenuItem";
- this.runAsToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
- this.runAsToolStripMenuItem.Text = "Run As...";
- this.runAsToolStripMenuItem.Click += new System.EventHandler(this.runAsServiceMenuItem_Click);
- //
- // runAsAdministratorMenuItem
- //
- this.runAsAdministratorMenuItem.Name = "runAsAdministratorMenuItem";
- this.runAsAdministratorMenuItem.Size = new System.Drawing.Size(230, 22);
- this.runAsAdministratorMenuItem.Text = "Run As Administrator...";
- this.runAsAdministratorMenuItem.Click += new System.EventHandler(this.runAsAdministratorMenuItem_Click);
- //
- // showDetailsForAllProcessesMenuItem
- //
- this.showDetailsForAllProcessesMenuItem.Name = "showDetailsForAllProcessesMenuItem";
- this.showDetailsForAllProcessesMenuItem.Size = new System.Drawing.Size(230, 22);
- this.showDetailsForAllProcessesMenuItem.Text = "Show Details for All Processes";
- this.showDetailsForAllProcessesMenuItem.Click += new System.EventHandler(this.showDetailsForAllProcessesMenuItem_Click);
- //
- // toolStripSeparator4
- //
- this.toolStripSeparator4.Name = "toolStripSeparator4";
- this.toolStripSeparator4.Size = new System.Drawing.Size(227, 6);
- //
- // openToolStripMenuItem
- //
- this.openToolStripMenuItem.Name = "openToolStripMenuItem";
- this.openToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
- this.openToolStripMenuItem.Text = "Open";
- this.openToolStripMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
- //
- // saveToolStripMenuItem
- //
- this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
- this.saveToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
- this.saveToolStripMenuItem.Text = "Save";
- this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click);
+ // menuService
//
- // toolStripSeparator6
- //
- this.toolStripSeparator6.Name = "toolStripSeparator6";
- this.toolStripSeparator6.Size = new System.Drawing.Size(227, 6);
- //
- // findHandlesMenuItem
- //
- this.findHandlesMenuItem.Name = "findHandlesMenuItem";
- this.findHandlesMenuItem.Size = new System.Drawing.Size(230, 22);
- this.findHandlesMenuItem.Text = "&Find Handles or DLLs...";
- this.findHandlesMenuItem.Click += new System.EventHandler(this.findHandlesMenuItem_Click);
- //
- // inspectPEFileToolStripMenuItem
- //
- this.inspectPEFileToolStripMenuItem.Name = "inspectPEFileToolStripMenuItem";
- this.inspectPEFileToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
- this.inspectPEFileToolStripMenuItem.Text = "Inspect &PE File...";
- this.inspectPEFileToolStripMenuItem.Click += new System.EventHandler(this.inspectPEFileMenuItem_Click);
- //
- // optionsMenuItem
- //
- this.optionsMenuItem.Name = "optionsMenuItem";
- this.optionsMenuItem.Size = new System.Drawing.Size(230, 22);
- this.optionsMenuItem.Text = "&Options...";
- this.optionsMenuItem.Click += new System.EventHandler(this.optionsMenuItem_Click);
- //
- // toolStripSeparator5
- //
- this.toolStripSeparator5.Name = "toolStripSeparator5";
- this.toolStripSeparator5.Size = new System.Drawing.Size(227, 6);
- //
- // shutdownMenuItem
- //
- this.shutdownMenuItem.Name = "shutdownMenuItem";
- this.shutdownMenuItem.Size = new System.Drawing.Size(230, 22);
- this.shutdownMenuItem.Text = "Shutdown";
- //
- // exitToolStripMenuItem
- //
- this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
- this.exitToolStripMenuItem.Size = new System.Drawing.Size(230, 22);
- this.exitToolStripMenuItem.Text = "Exit";
- this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click);
- //
- // viewToolStripMenuItem
- //
- this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.toolbarMenuItem,
- this.sysInfoMenuItem,
- this.trayIconsToolStripMenuItem,
- this.toolStripSeparator3,
- this.refreshToolStripMenuItem,
- this.updateProcessesMenuItem,
- this.updateServicesMenuItem});
- this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
- this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
- this.viewToolStripMenuItem.Text = "View";
- //
- // toolbarMenuItem
- //
- this.toolbarMenuItem.Name = "toolbarMenuItem";
- this.toolbarMenuItem.Size = new System.Drawing.Size(178, 22);
- this.toolbarMenuItem.Text = "Toolbar";
- this.toolbarMenuItem.Click += new System.EventHandler(this.toolbarMenuItem_Click);
- //
- // sysInfoMenuItem
- //
- this.sysInfoMenuItem.Name = "sysInfoMenuItem";
- this.sysInfoMenuItem.Size = new System.Drawing.Size(178, 22);
- this.sysInfoMenuItem.Text = "System &Information";
- this.sysInfoMenuItem.Click += new System.EventHandler(this.sysInfoMenuItem_Click);
- //
- // trayIconsToolStripMenuItem
- //
- this.trayIconsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.cpuHistoryMenuItem,
- this.cpuUsageMenuItem,
- this.ioHistoryMenuItem,
- this.commitHistoryMenuItem,
- this.physMemHistoryMenuItem});
- this.trayIconsToolStripMenuItem.Name = "trayIconsToolStripMenuItem";
- this.trayIconsToolStripMenuItem.Size = new System.Drawing.Size(178, 22);
- this.trayIconsToolStripMenuItem.Text = "Tray Icons";
- //
- // cpuHistoryMenuItem
- //
- this.cpuHistoryMenuItem.Name = "cpuHistoryMenuItem";
- this.cpuHistoryMenuItem.Size = new System.Drawing.Size(206, 22);
- this.cpuHistoryMenuItem.Text = "CPU History";
- this.cpuHistoryMenuItem.Click += new System.EventHandler(this.cpuHistoryMenuItem_Click);
- //
- // cpuUsageMenuItem
- //
- this.cpuUsageMenuItem.Name = "cpuUsageMenuItem";
- this.cpuUsageMenuItem.Size = new System.Drawing.Size(206, 22);
- this.cpuUsageMenuItem.Text = "CPU Usage";
- this.cpuUsageMenuItem.Click += new System.EventHandler(this.cpuUsageMenuItem_Click);
+ this.menuService.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.goToProcessServiceMenuItem,
+ this.startServiceMenuItem,
+ this.continueServiceMenuItem,
+ this.pauseServiceMenuItem,
+ this.stopServiceMenuItem,
+ this.deleteServiceMenuItem,
+ this.propertiesServiceMenuItem,
+ this.menuItem8,
+ this.copyServiceMenuItem,
+ this.selectAllServiceMenuItem});
+ this.menuService.Popup += new System.EventHandler(this.menuService_Popup);
//
- // ioHistoryMenuItem
+ // goToProcessServiceMenuItem
//
- this.ioHistoryMenuItem.Name = "ioHistoryMenuItem";
- this.ioHistoryMenuItem.Size = new System.Drawing.Size(206, 22);
- this.ioHistoryMenuItem.Text = "I/O History";
- this.ioHistoryMenuItem.Click += new System.EventHandler(this.ioHistoryMenuItem_Click);
+ this.vistaMenu.SetImage(this.goToProcessServiceMenuItem, global::ProcessHacker.Properties.Resources.arrow_right);
+ this.goToProcessServiceMenuItem.Index = 0;
+ this.goToProcessServiceMenuItem.Text = "&Go to Process";
+ this.goToProcessServiceMenuItem.Click += new System.EventHandler(this.goToProcessServiceMenuItem_Click);
//
- // commitHistoryMenuItem
+ // startServiceMenuItem
//
- this.commitHistoryMenuItem.Name = "commitHistoryMenuItem";
- this.commitHistoryMenuItem.Size = new System.Drawing.Size(206, 22);
- this.commitHistoryMenuItem.Text = "Commit History";
- this.commitHistoryMenuItem.Click += new System.EventHandler(this.commitHistoryMenuItem_Click);
+ this.vistaMenu.SetImage(this.startServiceMenuItem, global::ProcessHacker.Properties.Resources.control_play_blue);
+ this.startServiceMenuItem.Index = 1;
+ this.startServiceMenuItem.Text = "&Start";
+ this.startServiceMenuItem.Click += new System.EventHandler(this.startServiceMenuItem_Click);
//
- // physMemHistoryMenuItem
+ // continueServiceMenuItem
//
- this.physMemHistoryMenuItem.Name = "physMemHistoryMenuItem";
- this.physMemHistoryMenuItem.Size = new System.Drawing.Size(206, 22);
- this.physMemHistoryMenuItem.Text = "Physical Memory History";
- this.physMemHistoryMenuItem.Click += new System.EventHandler(this.physMemHistoryMenuItem_Click);
+ this.continueServiceMenuItem.Index = 2;
+ this.continueServiceMenuItem.Text = "&Continue";
+ this.continueServiceMenuItem.Click += new System.EventHandler(this.continueServiceMenuItem_Click);
//
- // toolStripSeparator3
+ // pauseServiceMenuItem
//
- this.toolStripSeparator3.Name = "toolStripSeparator3";
- this.toolStripSeparator3.Size = new System.Drawing.Size(175, 6);
+ this.vistaMenu.SetImage(this.pauseServiceMenuItem, global::ProcessHacker.Properties.Resources.control_pause_blue);
+ this.pauseServiceMenuItem.Index = 3;
+ this.pauseServiceMenuItem.Text = "&Pause";
+ this.pauseServiceMenuItem.Click += new System.EventHandler(this.pauseServiceMenuItem_Click);
//
- // refreshToolStripMenuItem
+ // stopServiceMenuItem
//
- this.refreshToolStripMenuItem.Name = "refreshToolStripMenuItem";
- this.refreshToolStripMenuItem.Size = new System.Drawing.Size(178, 22);
- this.refreshToolStripMenuItem.Text = "Refresh";
- this.refreshToolStripMenuItem.Click += new System.EventHandler(this.refreshToolStripButton_Click);
+ this.vistaMenu.SetImage(this.stopServiceMenuItem, global::ProcessHacker.Properties.Resources.control_stop_blue);
+ this.stopServiceMenuItem.Index = 4;
+ this.stopServiceMenuItem.Text = "S&top";
+ this.stopServiceMenuItem.Click += new System.EventHandler(this.stopServiceMenuItem_Click);
//
- // updateProcessesMenuItem
+ // deleteServiceMenuItem
//
- this.updateProcessesMenuItem.Name = "updateProcessesMenuItem";
- this.updateProcessesMenuItem.Size = new System.Drawing.Size(178, 22);
- this.updateProcessesMenuItem.Text = "Update &Processes";
- this.updateProcessesMenuItem.Click += new System.EventHandler(this.updateProcessesMenuItem_Click);
+ this.vistaMenu.SetImage(this.deleteServiceMenuItem, global::ProcessHacker.Properties.Resources.cross);
+ this.deleteServiceMenuItem.Index = 5;
+ this.deleteServiceMenuItem.Shortcut = System.Windows.Forms.Shortcut.Del;
+ this.deleteServiceMenuItem.Text = "Delete";
+ this.deleteServiceMenuItem.Click += new System.EventHandler(this.deleteServiceMenuItem_Click);
//
- // updateServicesMenuItem
+ // propertiesServiceMenuItem
//
- this.updateServicesMenuItem.Name = "updateServicesMenuItem";
- this.updateServicesMenuItem.Size = new System.Drawing.Size(178, 22);
- this.updateServicesMenuItem.Text = "Update &Services";
- this.updateServicesMenuItem.Click += new System.EventHandler(this.updateServicesMenuItem_Click);
+ this.propertiesServiceMenuItem.DefaultItem = true;
+ this.vistaMenu.SetImage(this.propertiesServiceMenuItem, global::ProcessHacker.Properties.Resources.application_form_magnify);
+ this.propertiesServiceMenuItem.Index = 6;
+ this.propertiesServiceMenuItem.Text = "&Properties";
+ this.propertiesServiceMenuItem.Click += new System.EventHandler(this.propertiesServiceMenuItem_Click);
//
- // toolsToolStripMenuItem
+ // menuItem8
//
- this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.createServiceToolStripMenuItem,
- this.hiddenProcessesToolStripMenuItem,
- this.verifyFileSignatureToolStripMenuItem});
- this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
- this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
- this.toolsToolStripMenuItem.Text = "Tools";
+ this.menuItem8.Index = 7;
+ this.menuItem8.Text = "-";
//
- // createServiceToolStripMenuItem
+ // copyServiceMenuItem
//
- this.createServiceToolStripMenuItem.Name = "createServiceToolStripMenuItem";
- this.createServiceToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
- this.createServiceToolStripMenuItem.Text = "Create &Service";
- this.createServiceToolStripMenuItem.Click += new System.EventHandler(this.createServiceMenuItem_Click);
+ this.vistaMenu.SetImage(this.copyServiceMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
+ this.copyServiceMenuItem.Index = 8;
+ this.copyServiceMenuItem.Text = "Copy";
//
- // hiddenProcessesToolStripMenuItem
+ // selectAllServiceMenuItem
//
- this.hiddenProcessesToolStripMenuItem.Name = "hiddenProcessesToolStripMenuItem";
- this.hiddenProcessesToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
- this.hiddenProcessesToolStripMenuItem.Text = "&Hidden Processes";
- this.hiddenProcessesToolStripMenuItem.Click += new System.EventHandler(this.hiddenProcessesMenuItem_Click);
+ this.selectAllServiceMenuItem.Index = 9;
+ this.selectAllServiceMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
+ this.selectAllServiceMenuItem.Text = "Select &All";
+ this.selectAllServiceMenuItem.Click += new System.EventHandler(this.selectAllServiceMenuItem_Click);
//
- // verifyFileSignatureToolStripMenuItem
+ // menuIcon
//
- this.verifyFileSignatureToolStripMenuItem.Name = "verifyFileSignatureToolStripMenuItem";
- this.verifyFileSignatureToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
- this.verifyFileSignatureToolStripMenuItem.Text = "&Verify File Signature...";
- this.verifyFileSignatureToolStripMenuItem.Click += new System.EventHandler(this.verifyFileSignatureMenuItem_Click);
+ this.menuIcon.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.showHideMenuItem,
+ this.sysInformationIconMenuItem,
+ this.networkInfomationMenuItem,
+ this.notificationsMenuItem,
+ this.processesMenuItem,
+ this.shutdownTrayMenuItem,
+ this.exitTrayMenuItem});
+ this.menuIcon.Popup += new System.EventHandler(this.menuIcon_Popup);
//
- // usersToolStripMenuItem
+ // showHideMenuItem
//
- this.usersToolStripMenuItem.Name = "usersToolStripMenuItem";
- this.usersToolStripMenuItem.Size = new System.Drawing.Size(47, 20);
- this.usersToolStripMenuItem.Text = "Users";
+ this.showHideMenuItem.Index = 0;
+ this.showHideMenuItem.Text = "&Show/Hide Process Hacker";
+ this.showHideMenuItem.Click += new System.EventHandler(this.showHideMenuItem_Click);
//
- // windowToolStripMenuItem
+ // sysInformationIconMenuItem
//
- this.windowToolStripMenuItem.Name = "windowToolStripMenuItem";
- this.windowToolStripMenuItem.Size = new System.Drawing.Size(63, 20);
- this.windowToolStripMenuItem.Text = "Window";
+ this.sysInformationIconMenuItem.Index = 1;
+ this.sysInformationIconMenuItem.Text = "System &Information";
+ this.sysInformationIconMenuItem.Click += new System.EventHandler(this.sysInformationIconMenuItem_Click);
//
- // helpToolStripMenuItem
+ // networkInfomationMenuItem
//
- this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.checkForUpdatesMenuItem,
- this.toolStripSeparator2,
- this.logToolStripMenuItem,
- this.helpToolStripMenuItem1,
- this.aboutToolStripMenuItem});
- this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
- this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
- this.helpToolStripMenuItem.Text = "Help";
+ this.networkInfomationMenuItem.Index = 2;
+ this.networkInfomationMenuItem.Text = "Network Infomation";
+ this.networkInfomationMenuItem.Click += new System.EventHandler(this.networkInfomationMenuItem_Click);
//
- // checkForUpdatesMenuItem
+ // notificationsMenuItem
//
- this.checkForUpdatesMenuItem.Enabled = false;
- this.checkForUpdatesMenuItem.Name = "checkForUpdatesMenuItem";
- this.checkForUpdatesMenuItem.Size = new System.Drawing.Size(173, 22);
- this.checkForUpdatesMenuItem.Text = "Check For Updates";
+ this.notificationsMenuItem.Index = 3;
+ this.notificationsMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.enableAllNotificationsMenuItem,
+ this.disableAllNotificationsMenuItem,
+ this.menuItem4,
+ this.NPMenuItem,
+ this.TPMenuItem,
+ this.NSMenuItem,
+ this.startedSMenuItem,
+ this.stoppedSMenuItem,
+ this.DSMenuItem});
+ this.notificationsMenuItem.Text = "&Notifications";
//
- // toolStripSeparator2
+ // enableAllNotificationsMenuItem
//
- this.toolStripSeparator2.Name = "toolStripSeparator2";
- this.toolStripSeparator2.Size = new System.Drawing.Size(170, 6);
+ this.enableAllNotificationsMenuItem.Index = 0;
+ this.enableAllNotificationsMenuItem.Text = "&Enable All";
+ this.enableAllNotificationsMenuItem.Click += new System.EventHandler(this.enableAllNotificationsMenuItem_Click);
//
- // logToolStripMenuItem
+ // disableAllNotificationsMenuItem
//
- this.logToolStripMenuItem.Name = "logToolStripMenuItem";
- this.logToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
- this.logToolStripMenuItem.Text = "Log";
- this.logToolStripMenuItem.Click += new System.EventHandler(this.logMenuItem_Click);
+ this.disableAllNotificationsMenuItem.Index = 1;
+ this.disableAllNotificationsMenuItem.Text = "&Disable All";
+ this.disableAllNotificationsMenuItem.Click += new System.EventHandler(this.disableAllNotificationsMenuItem_Click);
//
- // helpToolStripMenuItem1
+ // menuItem4
//
- this.helpToolStripMenuItem1.Name = "helpToolStripMenuItem1";
- this.helpToolStripMenuItem1.Size = new System.Drawing.Size(173, 22);
- this.helpToolStripMenuItem1.Text = "Help";
- this.helpToolStripMenuItem1.Click += new System.EventHandler(this.helpMenuItem_Click);
+ this.menuItem4.Index = 2;
+ this.menuItem4.Text = "-";
//
- // aboutToolStripMenuItem
+ // NPMenuItem
//
- this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
- this.aboutToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
- this.aboutToolStripMenuItem.Text = "About";
- this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutMenuItem_Click);
+ this.NPMenuItem.Index = 3;
+ this.NPMenuItem.Text = "New Processes";
//
- // contextMenuStripTray
+ // TPMenuItem
//
- this.contextMenuStripTray.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.showHideProcessHackerToolStripMenuItem,
- this.systemInformationToolStripMenuItem,
- this.networkInfomationMenuItem,
- this.toolStripSeparator9,
- this.processesMenuItem,
- this.notificationsToolStripMenuItem,
- this.toolStripSeparator8,
- this.shutdownTrayMenuItem,
- this.exitToolStripMenuItem1});
- this.contextMenuStripTray.Name = "contextMenuStripTray";
- this.contextMenuStripTray.Size = new System.Drawing.Size(217, 170);
+ this.TPMenuItem.Index = 4;
+ this.TPMenuItem.Text = "Terminated Processes";
//
- // showHideProcessHackerToolStripMenuItem
+ // NSMenuItem
//
- this.showHideProcessHackerToolStripMenuItem.Name = "showHideProcessHackerToolStripMenuItem";
- this.showHideProcessHackerToolStripMenuItem.Size = new System.Drawing.Size(216, 22);
- this.showHideProcessHackerToolStripMenuItem.Text = "&Show/Hide Process Hacker";
- this.showHideProcessHackerToolStripMenuItem.Click += new System.EventHandler(this.showHideMenuItem_Click);
+ this.NSMenuItem.Index = 5;
+ this.NSMenuItem.Text = "New Services";
//
- // systemInformationToolStripMenuItem
+ // startedSMenuItem
//
- this.systemInformationToolStripMenuItem.Name = "systemInformationToolStripMenuItem";
- this.systemInformationToolStripMenuItem.Size = new System.Drawing.Size(216, 22);
- this.systemInformationToolStripMenuItem.Text = "System &Information";
- this.systemInformationToolStripMenuItem.Click += new System.EventHandler(this.sysInfoMenuItem_Click);
+ this.startedSMenuItem.Index = 6;
+ this.startedSMenuItem.Text = "Started Services";
//
- // networkInfomationMenuItem
+ // stoppedSMenuItem
//
- this.networkInfomationMenuItem.Name = "networkInfomationMenuItem";
- this.networkInfomationMenuItem.Size = new System.Drawing.Size(216, 22);
- this.networkInfomationMenuItem.Text = "Network Infomation";
- this.networkInfomationMenuItem.Click += new System.EventHandler(this.networkInfomationMenuItem_Click);
+ this.stoppedSMenuItem.Index = 7;
+ this.stoppedSMenuItem.Text = "Stopped Services";
//
- // toolStripSeparator9
+ // DSMenuItem
//
- this.toolStripSeparator9.Name = "toolStripSeparator9";
- this.toolStripSeparator9.Size = new System.Drawing.Size(213, 6);
+ this.DSMenuItem.Index = 8;
+ this.DSMenuItem.Text = "Deleted Services";
//
// processesMenuItem
//
- this.processesMenuItem.Name = "processesMenuItem";
- this.processesMenuItem.Size = new System.Drawing.Size(216, 22);
+ this.processesMenuItem.Index = 4;
this.processesMenuItem.Text = "&Processes";
//
- // notificationsToolStripMenuItem
+ // shutdownTrayMenuItem
//
- this.notificationsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.enableAllToolStripMenuItem,
- this.disableAllToolStripMenuItem,
- this.toolStripSeparator10,
- this.newProcessesToolStripMenuItem,
- this.terminatedProcessesToolStripMenuItem,
- this.newServicesToolStripMenuItem,
- this.startedServicesToolStripMenuItem,
- this.stoppedServicesToolStripMenuItem,
- this.deletedServicesToolStripMenuItem});
- this.notificationsToolStripMenuItem.Name = "notificationsToolStripMenuItem";
- this.notificationsToolStripMenuItem.Size = new System.Drawing.Size(216, 22);
- this.notificationsToolStripMenuItem.Text = "&Notifications";
+ this.shutdownTrayMenuItem.Index = 5;
+ this.shutdownTrayMenuItem.Text = "Shutdown";
//
- // enableAllToolStripMenuItem
+ // exitTrayMenuItem
//
- this.enableAllToolStripMenuItem.Name = "enableAllToolStripMenuItem";
- this.enableAllToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.enableAllToolStripMenuItem.Text = "&Enable All";
- this.enableAllToolStripMenuItem.Click += new System.EventHandler(this.enableAllNotificationsMenuItem_Click);
+ this.vistaMenu.SetImage(this.exitTrayMenuItem, global::ProcessHacker.Properties.Resources.door_out);
+ this.exitTrayMenuItem.Index = 6;
+ this.exitTrayMenuItem.Text = "E&xit";
+ this.exitTrayMenuItem.Click += new System.EventHandler(this.exitTrayMenuItem_Click);
//
- // disableAllToolStripMenuItem
+ // goToProcessNetworkMenuItem
//
- this.disableAllToolStripMenuItem.Name = "disableAllToolStripMenuItem";
- this.disableAllToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.disableAllToolStripMenuItem.Text = "&Disable All";
- this.disableAllToolStripMenuItem.Click += new System.EventHandler(this.disableAllNotificationsMenuItem_Click);
+ this.goToProcessNetworkMenuItem.DefaultItem = true;
+ this.vistaMenu.SetImage(this.goToProcessNetworkMenuItem, global::ProcessHacker.Properties.Resources.arrow_right);
+ this.goToProcessNetworkMenuItem.Index = 0;
+ this.goToProcessNetworkMenuItem.Text = "&Go to Process";
+ this.goToProcessNetworkMenuItem.Click += new System.EventHandler(this.goToProcessNetworkMenuItem_Click);
//
- // toolStripSeparator10
+ // copyNetworkMenuItem
//
- this.toolStripSeparator10.Name = "toolStripSeparator10";
- this.toolStripSeparator10.Size = new System.Drawing.Size(186, 6);
+ this.vistaMenu.SetImage(this.copyNetworkMenuItem, global::ProcessHacker.Properties.Resources.page_copy);
+ this.copyNetworkMenuItem.Index = 4;
+ this.copyNetworkMenuItem.Text = "&Copy";
//
- // newProcessesToolStripMenuItem
+ // closeNetworkMenuItem
//
- this.newProcessesToolStripMenuItem.Name = "newProcessesToolStripMenuItem";
- this.newProcessesToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.newProcessesToolStripMenuItem.Text = "New Processes";
- this.newProcessesToolStripMenuItem.Click += new System.EventHandler(this.CheckedMenuItem_Click);
+ this.vistaMenu.SetImage(this.closeNetworkMenuItem, global::ProcessHacker.Properties.Resources.cross);
+ this.closeNetworkMenuItem.Index = 2;
+ this.closeNetworkMenuItem.Text = "Close";
+ this.closeNetworkMenuItem.Click += new System.EventHandler(this.closeNetworkMenuItem_Click);
//
- // terminatedProcessesToolStripMenuItem
+ // menuNetwork
//
- this.terminatedProcessesToolStripMenuItem.Name = "terminatedProcessesToolStripMenuItem";
- this.terminatedProcessesToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.terminatedProcessesToolStripMenuItem.Text = "Terminated Processes";
+ this.menuNetwork.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.goToProcessNetworkMenuItem,
+ this.toolsNetworkMenuItem,
+ this.closeNetworkMenuItem,
+ this.menuItem6,
+ this.copyNetworkMenuItem,
+ this.selectAllNetworkMenuItem});
+ this.menuNetwork.Popup += new System.EventHandler(this.menuNetwork_Popup);
//
- // newServicesToolStripMenuItem
+ // toolsNetworkMenuItem
//
- this.newServicesToolStripMenuItem.Name = "newServicesToolStripMenuItem";
- this.newServicesToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.newServicesToolStripMenuItem.Text = "New Services";
+ this.toolsNetworkMenuItem.Index = 1;
+ this.toolsNetworkMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
+ this.whoisNetworkMenuItem,
+ this.tracertNetworkMenuItem,
+ this.pingNetworkMenuItem});
+ this.toolsNetworkMenuItem.Text = "Tools";
//
- // startedServicesToolStripMenuItem
+ // whoisNetworkMenuItem
//
- this.startedServicesToolStripMenuItem.Name = "startedServicesToolStripMenuItem";
- this.startedServicesToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.startedServicesToolStripMenuItem.Text = "Started Services";
+ this.whoisNetworkMenuItem.Index = 0;
+ this.whoisNetworkMenuItem.Text = "Whois";
+ this.whoisNetworkMenuItem.Click += new System.EventHandler(this.whoisNetworkMenuItem_Click);
//
- // stoppedServicesToolStripMenuItem
+ // tracertNetworkMenuItem
//
- this.stoppedServicesToolStripMenuItem.Name = "stoppedServicesToolStripMenuItem";
- this.stoppedServicesToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.stoppedServicesToolStripMenuItem.Text = "Stopped Services";
+ this.tracertNetworkMenuItem.Index = 1;
+ this.tracertNetworkMenuItem.Text = "Tracert";
+ this.tracertNetworkMenuItem.Click += new System.EventHandler(this.tracertNetworkMenuItem_Click);
//
- // deletedServicesToolStripMenuItem
+ // pingNetworkMenuItem
//
- this.deletedServicesToolStripMenuItem.Name = "deletedServicesToolStripMenuItem";
- this.deletedServicesToolStripMenuItem.Size = new System.Drawing.Size(189, 22);
- this.deletedServicesToolStripMenuItem.Text = "Deleted Services";
+ this.pingNetworkMenuItem.Index = 2;
+ this.pingNetworkMenuItem.Text = "Ping";
+ this.pingNetworkMenuItem.Click += new System.EventHandler(this.pingNetworkMenuItem_Click);
//
- // toolStripSeparator8
+ // menuItem6
//
- this.toolStripSeparator8.Name = "toolStripSeparator8";
- this.toolStripSeparator8.Size = new System.Drawing.Size(213, 6);
+ this.menuItem6.Index = 3;
+ this.menuItem6.Text = "-";
//
- // shutdownTrayMenuItem
+ // selectAllNetworkMenuItem
//
- this.shutdownTrayMenuItem.Name = "shutdownTrayMenuItem";
- this.shutdownTrayMenuItem.Size = new System.Drawing.Size(216, 22);
- this.shutdownTrayMenuItem.Text = "Shutdown";
+ this.selectAllNetworkMenuItem.Index = 5;
+ this.selectAllNetworkMenuItem.Text = "Select &All";
+ this.selectAllNetworkMenuItem.Click += new System.EventHandler(this.selectAllNetworkMenuItem_Click);
//
- // exitToolStripMenuItem1
+ // vistaMenu
//
- this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1";
- this.exitToolStripMenuItem1.Size = new System.Drawing.Size(216, 22);
- this.exitToolStripMenuItem1.Text = "Exit";
- this.exitToolStripMenuItem1.Click += new System.EventHandler(this.exitMenuItem_Click);
+ this.vistaMenu.ContainerControl = this;
+ this.vistaMenu.DelaySetImageCalls = false;
//
// HackerWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.Color.WhiteSmoke;
- this.ClientSize = new System.Drawing.Size(804, 568);
+ this.ClientSize = new System.Drawing.Size(804, 372);
this.Controls.Add(this.tabControl);
this.Controls.Add(this.toolStrip);
- this.Controls.Add(this.statusStrip1);
- this.Controls.Add(this.menuStripEx1);
+ this.Controls.Add(this.statusBar);
+ this.DoubleBuffered = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
- this.MainMenuStrip = this.menuStripEx1;
+ this.Menu = this.mainMenu;
this.Name = "HackerWindow";
this.Text = "Process Hacker";
- this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.HackerWindow_FormClosing);
this.Load += new System.EventHandler(this.HackerWindow_Load);
+ this.SizeChanged += new System.EventHandler(this.HackerWindow_SizeChanged);
this.VisibleChanged += new System.EventHandler(this.HackerWindow_VisibleChanged);
+ this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.HackerWindow_FormClosing);
+ ((System.ComponentModel.ISupportInitialize)(this.statusGeneral)).EndInit();
+ ((System.ComponentModel.ISupportInitialize)(this.statusCPU)).EndInit();
+ ((System.ComponentModel.ISupportInitialize)(this.statusMemory)).EndInit();
this.tabControl.ResumeLayout(false);
this.tabProcesses.ResumeLayout(false);
- this.contextMenuStripProcess.ResumeLayout(false);
this.tabServices.ResumeLayout(false);
- this.contextMenuStripService.ResumeLayout(false);
this.tabNetwork.ResumeLayout(false);
- this.contextMenuStripNetwork.ResumeLayout(false);
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
- this.statusStrip1.ResumeLayout(false);
- this.statusStrip1.PerformLayout();
- this.menuStripEx1.ResumeLayout(false);
- this.menuStripEx1.PerformLayout();
- this.contextMenuStripTray.ResumeLayout(false);
+ ((System.ComponentModel.ISupportInitialize)(this.vistaMenu)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
@@ -1470,6 +1393,19 @@ private void InitializeComponent()
#endregion
+ private System.Windows.Forms.ContextMenu menuProcess;
+ private System.Windows.Forms.MenuItem terminateMenuItem;
+ private System.Windows.Forms.MenuItem suspendMenuItem;
+ private System.Windows.Forms.MenuItem resumeMenuItem;
+ private System.Windows.Forms.MenuItem menuItem5;
+ private System.Windows.Forms.MenuItem priorityMenuItem;
+ private System.Windows.Forms.MenuItem menuItem7;
+ private System.Windows.Forms.MenuItem realTimeMenuItem;
+ private System.Windows.Forms.MenuItem highMenuItem;
+ private System.Windows.Forms.MenuItem aboveNormalMenuItem;
+ private System.Windows.Forms.MenuItem normalMenuItem;
+ private System.Windows.Forms.MenuItem belowNormalMenuItem;
+ private System.Windows.Forms.MenuItem idleMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem9;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem10;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem11;
@@ -1477,157 +1413,142 @@ private void InitializeComponent()
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem13;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem14;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem15;
+ private wyDay.Controls.VistaMenu vistaMenu;
+ private System.Windows.Forms.MainMenu mainMenu;
+ private System.Windows.Forms.MenuItem hackerMenuItem;
+ private System.Windows.Forms.MenuItem aboutMenuItem;
+ private System.Windows.Forms.MenuItem optionsMenuItem;
+ private System.Windows.Forms.MenuItem helpMenuItem;
+ private System.Windows.Forms.MenuItem exitMenuItem;
+ private System.Windows.Forms.MenuItem windowMenuItem;
private ProcessHacker.ProcessTree treeProcesses;
+ private System.Windows.Forms.MenuItem inspectPEFileMenuItem;
+ private System.Windows.Forms.MenuItem propertiesProcessMenuItem;
+ private System.Windows.Forms.MenuItem searchProcessMenuItem;
+ private System.Windows.Forms.StatusBar statusBar;
+ private System.Windows.Forms.MenuItem logMenuItem;
+ private System.Windows.Forms.StatusBarPanel statusGeneral;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.TabPage tabProcesses;
private System.Windows.Forms.TabPage tabServices;
private ProcessHacker.Components.ServiceList listServices;
+ private System.Windows.Forms.ContextMenu menuService;
+ private System.Windows.Forms.MenuItem propertiesServiceMenuItem;
+ private System.Windows.Forms.MenuItem startServiceMenuItem;
+ private System.Windows.Forms.MenuItem pauseServiceMenuItem;
+ private System.Windows.Forms.MenuItem stopServiceMenuItem;
+ private System.Windows.Forms.MenuItem deleteServiceMenuItem;
+ private System.Windows.Forms.MenuItem continueServiceMenuItem;
+ private System.Windows.Forms.MenuItem goToProcessServiceMenuItem;
+ private System.Windows.Forms.MenuItem menuItem8;
+ private System.Windows.Forms.MenuItem copyServiceMenuItem;
+ private System.Windows.Forms.MenuItem selectAllServiceMenuItem;
+ private System.Windows.Forms.MenuItem toolsMenuItem;
+ private System.Windows.Forms.ContextMenu menuIcon;
+ private System.Windows.Forms.MenuItem showHideMenuItem;
+ private System.Windows.Forms.MenuItem exitTrayMenuItem;
+ private System.Windows.Forms.MenuItem notificationsMenuItem;
+ private System.Windows.Forms.MenuItem NPMenuItem;
+ private System.Windows.Forms.MenuItem TPMenuItem;
+ private System.Windows.Forms.MenuItem NSMenuItem;
+ private System.Windows.Forms.MenuItem startedSMenuItem;
+ private System.Windows.Forms.MenuItem stoppedSMenuItem;
+ private System.Windows.Forms.MenuItem DSMenuItem;
+ private System.Windows.Forms.MenuItem findHandlesMenuItem;
+ private System.Windows.Forms.MenuItem affinityProcessMenuItem;
+ private System.Windows.Forms.MenuItem runAsServiceMenuItem;
+ private System.Windows.Forms.MenuItem runAsProcessMenuItem;
+ private System.Windows.Forms.MenuItem launchAsUserProcessMenuItem;
+ private System.Windows.Forms.MenuItem launchAsThisUserProcessMenuItem;
+ private System.Windows.Forms.MenuItem sysInfoMenuItem;
+ private System.Windows.Forms.MenuItem copyProcessMenuItem;
+ private System.Windows.Forms.MenuItem selectAllProcessMenuItem;
+ private System.Windows.Forms.MenuItem terminatorProcessMenuItem;
+ private System.Windows.Forms.MenuItem menuItem2;
+ private System.Windows.Forms.StatusBarPanel statusCPU;
+ private System.Windows.Forms.StatusBarPanel statusMemory;
+ private System.Windows.Forms.MenuItem reloadStructsMenuItem;
private System.Windows.Forms.TabPage tabNetwork;
private ProcessHacker.Components.NetworkList listNetwork;
- private System.ToolStripEx toolStrip;
+ private System.Windows.Forms.MenuItem sysInformationIconMenuItem;
+ private System.Windows.Forms.MenuItem hiddenProcessesMenuItem;
+ private System.Windows.Forms.MenuItem viewMenuItem;
+ private System.Windows.Forms.MenuItem updateNowMenuItem;
+ private System.Windows.Forms.MenuItem updateProcessesMenuItem;
+ private System.Windows.Forms.MenuItem updateServicesMenuItem;
+ private System.Windows.Forms.MenuItem processesMenuItem;
+ private System.Windows.Forms.MenuItem restartProcessMenuItem;
+ private System.Windows.Forms.MenuItem setTokenProcessMenuItem;
+ private System.Windows.Forms.MenuItem helpMenu;
+ private System.Windows.Forms.MenuItem menuItem3;
+ private System.Windows.Forms.MenuItem verifyFileSignatureMenuItem;
+ private System.Windows.Forms.MenuItem enableAllNotificationsMenuItem;
+ private System.Windows.Forms.MenuItem disableAllNotificationsMenuItem;
+ private System.Windows.Forms.MenuItem menuItem4;
+ private System.Windows.Forms.MenuItem shutdownTrayMenuItem;
+ private System.Windows.Forms.MenuItem shutdownMenuItem;
+ private System.Windows.Forms.MenuItem runAsAdministratorMenuItem;
+ private System.Windows.Forms.MenuItem showDetailsForAllProcessesMenuItem;
+ private System.Windows.Forms.MenuItem uacSeparatorMenuItem;
+ private System.Windows.Forms.MenuItem runMenuItem;
+ private System.Windows.Forms.MenuItem runAsMenuItem;
+ private System.Windows.Forms.MenuItem freeMemoryMenuItem;
+ private System.Windows.Forms.MenuItem menuItem1;
+ private System.Windows.Forms.MenuItem reanalyzeProcessMenuItem;
+ private System.Windows.Forms.MenuItem reduceWorkingSetProcessMenuItem;
+ private System.Windows.Forms.MenuItem virtualizationProcessMenuItem;
+ private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripButton refreshToolStripButton;
private System.Windows.Forms.ToolStripButton findHandlesToolStripButton;
private System.Windows.Forms.ToolStripButton sysInfoToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripDropDownButton shutDownToolStripMenuItem;
private System.Windows.Forms.ToolStripButton optionsToolStripButton;
- private System.Windows.Forms.StatusStrip statusStrip1;
- private System.Windows.Forms.ToolStripStatusLabel statusMemory;
- private System.Windows.Forms.ToolStripStatusLabel statusCPU;
- private System.Windows.Forms.ToolStripStatusLabel statusGeneral;
- private System.MenuStripEx menuStripEx1;
- private System.Windows.Forms.ToolStripMenuItem hackerToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem usersToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem checkForUpdatesMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
- private System.Windows.Forms.ToolStripMenuItem logToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem1;
- private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
- private ToolStripSearchBox toolStripTextBox2;
- private System.Windows.Forms.ToolStripMenuItem toolbarMenuItem;
- private System.Windows.Forms.ToolStripMenuItem sysInfoMenuItem;
- private System.Windows.Forms.ToolStripMenuItem trayIconsToolStripMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
- private System.Windows.Forms.ToolStripMenuItem refreshToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem updateProcessesMenuItem;
- private System.Windows.Forms.ToolStripMenuItem updateServicesMenuItem;
- private System.Windows.Forms.ToolStripMenuItem runToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem runAsToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem runAsAdministratorMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
- private System.Windows.Forms.ToolStripMenuItem shutdownMenuItem;
- private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem showDetailsForAllProcessesMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
- private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
- private System.Windows.Forms.ToolStripMenuItem findHandlesMenuItem;
- private System.Windows.Forms.ToolStripMenuItem inspectPEFileToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem optionsMenuItem;
- private System.Windows.Forms.ToolStripMenuItem createServiceToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem hiddenProcessesToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem verifyFileSignatureToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem cpuHistoryMenuItem;
- private System.Windows.Forms.ToolStripMenuItem cpuUsageMenuItem;
- private System.Windows.Forms.ToolStripMenuItem ioHistoryMenuItem;
- private System.Windows.Forms.ToolStripMenuItem commitHistoryMenuItem;
- private System.Windows.Forms.ToolStripMenuItem physMemHistoryMenuItem;
- private System.Windows.Forms.ContextMenuStrip contextMenuStripNetwork;
- private System.Windows.Forms.ToolStripMenuItem goToProcessNetworkMenuItem;
- private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem1;
- private System.Windows.Forms.ToolStripMenuItem closeNetworkMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
- private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem selectAllNetworkMenuItem;
- private System.Windows.Forms.ToolStripMenuItem whoisNetworkMenuItem;
- private System.Windows.Forms.ToolStripMenuItem tracertNetworkMenuItem;
- private System.Windows.Forms.ToolStripMenuItem pingNetworkMenuItem;
- private System.Windows.Forms.ContextMenuStrip contextMenuStripTray;
- private System.Windows.Forms.ToolStripMenuItem showHideProcessHackerToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem systemInformationToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem networkInfomationMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
- private System.Windows.Forms.ToolStripMenuItem shutdownTrayMenuItem;
- private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
- private System.Windows.Forms.ToolStripMenuItem processesMenuItem;
- private System.Windows.Forms.ToolStripMenuItem notificationsToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem enableAllToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem disableAllToolStripMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
- private System.Windows.Forms.ToolStripMenuItem newProcessesToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem terminatedProcessesToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem newServicesToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem startedServicesToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem stoppedServicesToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem deletedServicesToolStripMenuItem;
- private System.Windows.Forms.ContextMenuStrip contextMenuStripService;
- private System.Windows.Forms.ToolStripMenuItem goToProcessServiceMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
- private System.Windows.Forms.ToolStripMenuItem startToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem continueToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem pauseToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem stopToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator12;
- private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem1;
- private System.Windows.Forms.ToolStripMenuItem selectAllServiceMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator13;
- private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem;
- private System.Windows.Forms.ContextMenuStrip contextMenuStripProcess;
- private System.Windows.Forms.ToolStripMenuItem terminateToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem terminateProcessTreeToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem suspendToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem resumeToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem restartToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem reduceWorkingSetToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem virtualizationToolStripMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator14;
- private System.Windows.Forms.ToolStripMenuItem affinityToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem createDumpFileToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem terminatorToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem miscellaneousToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem priorityToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem runAsToolStripMenuItem1;
- private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem1;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator15;
- private System.Windows.Forms.ToolStripMenuItem searchOnlineToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem reanalyzeToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem copyProcessMenuItem;
- private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator16;
- private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem1;
- private System.Windows.Forms.ToolStripMenuItem launchAsUserToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem launchAsThisUserToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem bringToFrontToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem restoreToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem minimizeToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem maximizeToolStripMenuItem;
- private System.Windows.Forms.ToolStripSeparator toolStripSeparator17;
- private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem realTimeToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem highToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem aboveNormalToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem normalToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem belowNormalToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem idleToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem analyzeWaitChainToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem detachFromDebuggerToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem heapsToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem injectDLLToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem iOPriorityToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem protectionToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem setTokenToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem uploadToVirusTotalToolStripMenuItem;
- private System.Windows.Forms.ToolStripMenuItem ioPriority0ThreadMenuItem;
- private System.Windows.Forms.ToolStripMenuItem ioPriority1ThreadMenuItem;
- private System.Windows.Forms.ToolStripMenuItem ioPriority3ThreadMenuItem;
- private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
+ private System.Windows.Forms.MenuItem toolbarMenuItem;
+ private System.Windows.Forms.MenuItem saveMenuItem;
+ private System.Windows.Forms.ContextMenu menuNetwork;
+ private System.Windows.Forms.MenuItem goToProcessNetworkMenuItem;
+ private System.Windows.Forms.MenuItem copyNetworkMenuItem;
+ private System.Windows.Forms.MenuItem menuItem6;
+ private System.Windows.Forms.MenuItem selectAllNetworkMenuItem;
+ private System.Windows.Forms.MenuItem injectDllProcessMenuItem;
+ private System.Windows.Forms.MenuItem terminateProcessTreeMenuItem;
+ private System.Windows.Forms.MenuItem trayIconsMenuItem;
+ private System.Windows.Forms.MenuItem cpuHistoryMenuItem;
+ private System.Windows.Forms.MenuItem cpuUsageMenuItem;
+ private System.Windows.Forms.MenuItem ioHistoryMenuItem;
+ private System.Windows.Forms.MenuItem commitHistoryMenuItem;
+ private System.Windows.Forms.MenuItem physMemHistoryMenuItem;
+ private System.Windows.Forms.MenuItem closeNetworkMenuItem;
+ private System.Windows.Forms.MenuItem protectionProcessMenuItem;
+ private System.Windows.Forms.MenuItem createDumpFileProcessMenuItem;
+ private System.Windows.Forms.MenuItem miscellaneousProcessMenuItem;
+ private System.Windows.Forms.MenuItem detachFromDebuggerProcessMenuItem;
+ private System.Windows.Forms.MenuItem usersMenuItem;
+ private System.Windows.Forms.MenuItem createServiceMenuItem;
+ private System.Windows.Forms.MenuItem heapsProcessMenuItem;
+ private System.Windows.Forms.MenuItem windowProcessMenuItem;
+ private System.Windows.Forms.MenuItem bringToFrontProcessMenuItem;
+ private System.Windows.Forms.MenuItem restoreProcessMenuItem;
+ private System.Windows.Forms.MenuItem minimizeProcessMenuItem;
+ private System.Windows.Forms.MenuItem maximizeProcessMenuItem;
+ private System.Windows.Forms.MenuItem menuItem15;
+ private System.Windows.Forms.MenuItem closeProcessMenuItem;
+ private System.Windows.Forms.MenuItem checkForUpdatesMenuItem;
+ private System.Windows.Forms.MenuItem toolsNetworkMenuItem;
+ private System.Windows.Forms.MenuItem whoisNetworkMenuItem;
+ private System.Windows.Forms.MenuItem tracertNetworkMenuItem;
+ private System.Windows.Forms.MenuItem pingNetworkMenuItem;
+ private System.Windows.Forms.MenuItem VirusTotalMenuItem;
+ private System.Windows.Forms.MenuItem networkInfomationMenuItem;
+ private System.Windows.Forms.MenuItem analyzeWaitChainProcessMenuItem;
+ private System.Windows.Forms.MenuItem donateMenuItem;
+ private System.Windows.Forms.MenuItem ioPriorityThreadMenuItem;
+ private System.Windows.Forms.MenuItem ioPriority0ThreadMenuItem;
+ private System.Windows.Forms.MenuItem ioPriority1ThreadMenuItem;
+ private System.Windows.Forms.MenuItem ioPriority2ThreadMenuItem;
+ private System.Windows.Forms.MenuItem ioPriority3ThreadMenuItem;
+ private System.Windows.Forms.MenuItem openMenuItem;
}
}
diff --git a/1.x/trunk/ProcessHacker/Forms/HackerWindow.cs b/1.x/trunk/ProcessHacker/Forms/HackerWindow.cs
index 83593796e..28c3c81b1 100644
--- a/1.x/trunk/ProcessHacker/Forms/HackerWindow.cs
+++ b/1.x/trunk/ProcessHacker/Forms/HackerWindow.cs
@@ -35,7 +35,6 @@
using ProcessHacker.Native.Debugging;
using ProcessHacker.Native.Objects;
using ProcessHacker.Native.Security;
-using ProcessHacker.Native.Threading;
using ProcessHacker.UI;
using ProcessHacker.UI.Actions;
using TaskbarLib;
@@ -46,10 +45,10 @@ public partial class HackerWindow : Form
{
public delegate void LogUpdatedEventHandler(KeyValuePair? value);
- private readonly ThumbButtonManager thumbButtonManager;
+ private ThumbButtonManager thumbButtonManager;
//private JumpListManager jumpListManager; //Reserved for future use
- public delegate void AddMenuItemDelegate(string text, EventHandler onClick);
+ private delegate void AddMenuItemDelegate(string text, EventHandler onClick);
// This entire file is a big monolithic mess.
@@ -73,6 +72,11 @@ public partial class HackerWindow : Form
///
public SysInfoWindow SysInfoWindow;
+ ///
+ /// The UAC shield bitmap. Used for the various menu items which
+ /// require UAC elevation.
+ ///
+ Bitmap uacShieldIcon;
///
/// A black icon which all notification icons are set to initially
/// before their first paint.
@@ -86,7 +90,7 @@ public partial class HackerWindow : Form
///
/// The list of notification icons.
///
- readonly List notifyIcons = new List();
+ List notifyIcons = new List();
///
/// The CPU history icon, with a history of CPU usage.
///
@@ -114,7 +118,7 @@ public partial class HackerWindow : Form
/// A dictionary relating services to processes. Each key is a PID and
/// each value is a list of service names hosted in that particular process.
///
- readonly Dictionary> processServices = new Dictionary>();
+ Dictionary> processServices = new Dictionary>();
///
/// The number of selected processes. Not used.
@@ -129,7 +133,7 @@ public partial class HackerWindow : Form
/// The PH log, with events such as process creation/termination and various
/// service events.
///
- readonly List> _log = new List>();
+ List> _log = new List>();
///
/// windowhandle owned by the currently selected process.
@@ -157,9 +161,14 @@ public partial class HackerWindow : Form
// The following two properties were used by the Window menu system.
// Not very useful, but still needed for now.
- public ToolStripMenuItem WindowMenuItem
+ public MenuItem WindowMenuItem
{
- get { return windowToolStripMenuItem; }
+ get { return windowMenuItem; }
+ }
+
+ public wyDay.Controls.VistaMenu VistaMenu
+ {
+ get { return vistaMenu; }
}
// Mostly used by Save.cs.
@@ -259,18 +268,15 @@ private void runAsMenuItem_Click(object sender, EventArgs e)
private void runAsAdministratorMenuItem_Click(object sender, EventArgs e)
{
- using (PromptBox box = new PromptBox
- {
- Text = "Enter the command to start"
- })
- {
- box.TextBox.AutoCompleteSource = AutoCompleteSource.AllSystemSources;
- box.TextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
+ PromptBox box = new PromptBox();
- if (box.ShowDialog() == DialogResult.OK)
- {
- Program.StartProgramAdmin(box.Value, "", null, ShowWindowType.Show, this.Handle);
- }
+ box.Text = "Enter the command to start";
+ box.TextBox.AutoCompleteSource = AutoCompleteSource.AllSystemSources;
+ box.TextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
+
+ if (box.ShowDialog() == DialogResult.OK)
+ {
+ Program.StartProgramAdmin(box.Value, "", null, ShowWindowType.Show, this.Handle);
}
}
@@ -282,7 +288,10 @@ private void runAsServiceMenuItem_Click(object sender, EventArgs e)
private void showDetailsForAllProcessesMenuItem_Click(object sender, EventArgs e)
{
- Program.StartProcessHackerAdmin("-v", this.Exit, this.Handle);
+ Program.StartProcessHackerAdmin("-v", () =>
+ {
+ this.Exit();
+ }, this.Handle);
}
private void findHandlesMenuItem_Click(object sender, EventArgs e)
@@ -343,7 +352,7 @@ private void sysInfoMenuItem_Click(object sender, EventArgs e)
}
else
{
- SysInfoWindow.BeginInvoke(new MethodInvoker(() =>
+ SysInfoWindow.BeginInvoke(new MethodInvoker(delegate
{
SysInfoWindow.Show();
SysInfoWindow.Activate();
@@ -368,21 +377,20 @@ private void logMenuItem_Click(object sender, EventArgs e)
private void aboutMenuItem_Click(object sender, EventArgs e)
{
- using (AboutWindow about = new AboutWindow())
- {
- about.ShowDialog();
- }
+ AboutWindow about = new AboutWindow();
+ about.ShowDialog();
}
private void optionsMenuItem_Click(object sender, EventArgs e)
{
- using (OptionsWindow options = new OptionsWindow())
- {
- if (options.ShowDialog() == DialogResult.OK)
- {
- this.LoadOtherSettings();
- }
- }
+ OptionsWindow options = new OptionsWindow();
+
+ DialogResult result = options.ShowDialog();
+
+ if (result == DialogResult.OK)
+ {
+ this.LoadOtherSettings();
+ }
}
private void freeMemoryMenuItem_Click(object sender, EventArgs e)
@@ -410,6 +418,15 @@ private void toolbarMenuItem_Click(object sender, EventArgs e)
Settings.Instance.ToolbarVisible = toolStrip.Visible = toolbarMenuItem.Checked;
}
+ private void updateNowMenuItem_Click(object sender, EventArgs e)
+ {
+ if (Program.ProcessProvider.RunCount > 1)
+ Program.ProcessProvider.Boost();
+
+ if (Program.ServiceProvider.RunCount > 1)
+ Program.ServiceProvider.Boost();
+ }
+
private void updateProcessesMenuItem_Click(object sender, EventArgs e)
{
updateProcessesMenuItem.Checked = !updateProcessesMenuItem.Checked;
@@ -437,85 +454,81 @@ private void hiddenProcessesMenuItem_Click(object sender, EventArgs e)
private void verifyFileSignatureMenuItem_Click(object sender, EventArgs e)
{
- using (OpenFileDialog ofd = new OpenFileDialog
- {
- CheckFileExists = true,
- CheckPathExists = true,
- Filter = "Executable files (*.exe;*.dll;*.sys;*.scr;*.cpl)|*.exe;*.dll;*.sys;*.scr;*.cpl|All files (*.*)|*.*"
- })
+ OpenFileDialog ofd = new OpenFileDialog();
+
+ ofd.CheckFileExists = true;
+ ofd.CheckPathExists = true;
+ ofd.Filter = "Executable files (*.exe;*.dll;*.sys;*.scr;*.cpl)|*.exe;*.dll;*.sys;*.scr;*.cpl|All files (*.*)|*.*";
+
+ if (ofd.ShowDialog() == DialogResult.OK)
{
- if (ofd.ShowDialog() == DialogResult.OK)
+ try
{
- try
- {
- var result = Cryptography.VerifyFile(ofd.FileName);
- string message = string.Empty;
+ var result = Cryptography.VerifyFile(ofd.FileName);
+ string message = "";
- switch (result)
- {
- case VerifyResult.Distrust:
- message = "is not trusted";
- break;
- case VerifyResult.Expired:
- message = "has an expired certificate";
- break;
- case VerifyResult.NoSignature:
- message = "does not have a digital signature";
- break;
- case VerifyResult.Revoked:
- message = "has a revoked certificate";
- break;
- case VerifyResult.SecuritySettings:
- message = "could not be verified due to security settings";
- break;
- case VerifyResult.Trusted:
- message = "is trusted";
- break;
- case VerifyResult.Unknown:
- message = "could not be verified";
- break;
- default:
- message = "could not be verified";
- break;
- }
-
- PhUtils.ShowInformation("The file \"" + ofd.FileName + "\" " + message + ".");
- }
- catch (Exception ex)
+ switch (result)
{
- PhUtils.ShowException("Unable to verify the file", ex);
+ case VerifyResult.Distrust:
+ message = "is not trusted";
+ break;
+ case VerifyResult.Expired:
+ message = "has an expired certificate";
+ break;
+ case VerifyResult.NoSignature:
+ message = "does not have a digital signature";
+ break;
+ case VerifyResult.Revoked:
+ message = "has a revoked certificate";
+ break;
+ case VerifyResult.SecuritySettings:
+ message = "could not be verified due to security settings";
+ break;
+ case VerifyResult.Trusted:
+ message = "is trusted";
+ break;
+ case VerifyResult.Unknown:
+ message = "could not be verified";
+ break;
+ default:
+ message = "could not be verified";
+ break;
}
+
+ PhUtils.ShowInformation("The file \"" + ofd.FileName + "\" " + message + ".");
+ }
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to verify the file", ex);
}
}
}
private void openMenuItem_Click(object sender, EventArgs e)
{
- using (OpenFileDialog ofd = new OpenFileDialog
- {
- Filter = "Process Hacker Dump Files (*.phi)|*.phi|All Files (*.*)|*.*"
- })
- {
- if (ofd.ShowDialog() == DialogResult.OK)
- {
- DumpHackerWindow dhw = null;
+ OpenFileDialog ofd = new OpenFileDialog();
- try
- {
- dhw = new DumpHackerWindow(ofd.FileName);
- }
- catch (ProcessHacker.Native.Mfs.MfsInvalidFileSystemException)
- {
- PhUtils.ShowError("Unable to open the dump file: the dump file is invalid.");
- }
- catch (Exception ex)
- {
- PhUtils.ShowException("Unable to open the dump file", ex);
- }
+ ofd.Filter = "Process Hacker Dump Files (*.phi)|*.phi|All Files (*.*)|*.*";
+
+ if (ofd.ShowDialog() == DialogResult.OK)
+ {
+ DumpHackerWindow dhw = null;
- if (dhw != null)
- dhw.Show();
+ try
+ {
+ dhw = new DumpHackerWindow(ofd.FileName);
}
+ catch (ProcessHacker.Native.Mfs.MfsInvalidFileSystemException)
+ {
+ PhUtils.ShowError("Unable to open the dump file: the dump file is invalid.");
+ }
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to open the dump file", ex);
+ }
+
+ if (dhw != null)
+ dhw.Show();
}
}
@@ -590,30 +603,21 @@ private void physMemHistoryMenuItem_Click(object sender, EventArgs e)
#endregion
- public class ToolStripSearchBox : ToolStripControlHost
- {
- public ToolStripSearchBox()
- : base(new VistaSearchBox())
- {
-
- }
- }
-
#region Network Context Menu
private void menuNetwork_Popup(object sender, EventArgs e)
{
if (listNetwork.SelectedItems.Count == 0)
{
- //contextMenuStripNetwork.DisableAll();
+ menuNetwork.DisableAll();
}
else if (listNetwork.SelectedItems.Count == 1)
{
- //contextMenuStripNetwork.EnableAll();
+ menuNetwork.EnableAll();
}
else
{
- //contextMenuStripNetwork.EnableAll();
+ menuNetwork.EnableAll();
goToProcessNetworkMenuItem.Enabled = false;
}
@@ -799,7 +803,7 @@ private void closeNetworkMenuItem_Click(object sender, EventArgs e)
private void selectAllNetworkMenuItem_Click(object sender, EventArgs e)
{
- this.listNetwork.List.Items.SelectAll();
+ Utils.SelectAll(listNetwork.List.Items);
}
#endregion
@@ -816,10 +820,10 @@ private void menuIcon_Popup(object sender, EventArgs e)
List processes = new List();
// Clear the images so we don't get GDI+ handle leaks
- //foreach (MenuItem item in processesMenuItem.MenuItems)
- //vistaMenu.SetImage(item, null);
+ foreach (MenuItem item in processesMenuItem.MenuItems)
+ vistaMenu.SetImage(item, null);
- processesMenuItem.DropDownItems.Clear();
+ processesMenuItem.MenuItems.DisposeAndClear();
// HACK: To be fixed later - we need some sort of locking for the process provider
try
@@ -872,61 +876,62 @@ private void menuIcon_Popup(object sender, EventArgs e)
processItem.Text = process.Name + " (" + process.Pid.ToString() + ")";
processItem.Tag = process;
- terminateItem.Click += (sender_, e_) =>
+ terminateItem.Click += new EventHandler((sender_, e_) =>
{
- ProcessItem item = ((MenuItem)sender_).Parent.Tag as ProcessItem;
+ ProcessItem item = (ProcessItem)((MenuItem)sender_).Parent.Tag;
ProcessActions.Terminate(this, new int[] { item.Pid }, new string[] { item.Name }, true);
- };
+ });
terminateItem.Text = "Terminate";
- suspendItem.Click += (sender_, e_) =>
+ suspendItem.Click += new EventHandler((sender_, e_) =>
{
- ProcessItem item = ((MenuItem)sender_).Parent.Tag as ProcessItem;
+ ProcessItem item = (ProcessItem)((MenuItem)sender_).Parent.Tag;
ProcessActions.Suspend(this, new int[] { item.Pid }, new string[] { item.Name }, true);
- };
+ });
suspendItem.Text = "Suspend";
- resumeItem.Click += (sender_, e_) =>
+ resumeItem.Click += new EventHandler((sender_, e_) =>
{
- ProcessItem item = ((MenuItem)sender_).Parent.Tag as ProcessItem;
+ ProcessItem item = (ProcessItem)((MenuItem)sender_).Parent.Tag;
ProcessActions.Resume(this, new int[] { item.Pid }, new string[] { item.Name }, true);
- };
+ });
resumeItem.Text = "Resume";
- //propertiesItem.Click += (sender_, e_) =>
- //{
- // try
- // {
- // ProcessItem item = (ProcessItem)((MenuItem)sender_).Parent.Tag;
-
- // Program.GetProcessWindow(Program.ProcessProvider.Dictionary[item.Pid], f =>
- // {
- // f.Show();
- // f.Activate();
- // });
- // }
- // catch (Exception ex)
- // {
- // PhUtils.ShowException("Unable to inspect the process", ex);
- // }
- //};
- //propertiesItem.Text = "Properties";
-
- //processItem.MenuItems.AddRange(new MenuItem[] { terminateItem, suspendItem, resumeItem, propertiesItem });
- //processesMenuItem.DropDownItems.Add(processItem);
-
- // vistaMenu.SetImage(processItem, (treeProcesses.Tree.Model as ProcessTreeModel).Nodes[process.Pid].Icon);
+ propertiesItem.Click += new EventHandler((sender_, e_) =>
+ {
+ try
+ {
+ ProcessItem item = (ProcessItem)((MenuItem)sender_).Parent.Tag;
+
+ ProcessWindow pForm = Program.GetProcessWindow(Program.ProcessProvider.Dictionary[item.Pid],
+ new Program.PWindowInvokeAction(delegate(ProcessWindow f)
+ {
+ f.Show();
+ f.Activate();
+ }));
+ }
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to inspect the process", ex);
+ }
+ });
+ propertiesItem.Text = "Properties";
+
+ processItem.MenuItems.AddRange(new MenuItem[] { terminateItem, suspendItem, resumeItem, propertiesItem });
+ processesMenuItem.MenuItems.Add(processItem);
+
+ vistaMenu.SetImage(processItem, (treeProcesses.Tree.Model as ProcessTreeModel).Nodes[process.Pid].Icon);
}
}
catch
{
- //foreach (MenuItem item in processesMenuItem.MenuItems)
- //vistaMenu.SetImage(item, null);
+ foreach (MenuItem item in processesMenuItem.MenuItems)
+ vistaMenu.SetImage(item, null);
- processesMenuItem.DropDownItems.Clear();
+ processesMenuItem.MenuItems.DisposeAndClear();
}
}
@@ -962,22 +967,22 @@ private void networkInfomationMenuItem_Click(object sender, EventArgs e)
private void enableAllNotificationsMenuItem_Click(object sender, EventArgs e)
{
- newProcessesToolStripMenuItem.Checked = true;
- terminatedProcessesToolStripMenuItem.Checked = true;
- newServicesToolStripMenuItem.Checked = true;
- startedServicesToolStripMenuItem.Checked = true;
- stoppedServicesToolStripMenuItem.Checked = true;
- deletedServicesToolStripMenuItem.Checked = true;
+ NPMenuItem.Checked = true;
+ TPMenuItem.Checked = true;
+ NSMenuItem.Checked = true;
+ startedSMenuItem.Checked = true;
+ stoppedSMenuItem.Checked = true;
+ DSMenuItem.Checked = true;
}
private void disableAllNotificationsMenuItem_Click(object sender, EventArgs e)
{
- newProcessesToolStripMenuItem.Checked = false;
- terminatedProcessesToolStripMenuItem.Checked = false;
- newServicesToolStripMenuItem.Checked = false;
- startedServicesToolStripMenuItem.Checked = false;
- stoppedServicesToolStripMenuItem.Checked = false;
- deletedServicesToolStripMenuItem.Checked = false;
+ NPMenuItem.Checked = false;
+ TPMenuItem.Checked = false;
+ NSMenuItem.Checked = false;
+ startedSMenuItem.Checked = false;
+ stoppedSMenuItem.Checked = false;
+ DSMenuItem.Checked = false;
}
private void exitTrayMenuItem_Click(object sender, EventArgs e)
@@ -991,7 +996,7 @@ private void exitTrayMenuItem_Click(object sender, EventArgs e)
private void menuProcess_Popup(object sender, EventArgs e)
{
- virtualizationToolStripMenuItem.Checked = false;
+ virtualizationProcessMenuItem.Checked = false;
// Menu item fixup...
if (treeProcesses.SelectedTreeNodes.Count == 0)
@@ -999,72 +1004,72 @@ private void menuProcess_Popup(object sender, EventArgs e)
// If nothing is selected, disable everything.
// The Select All menu item will be enabled later if
// we have at least one process in the tree.
- //contextMenuStripProcess.DisableAll();
+ menuProcess.DisableAll();
}
else if (treeProcesses.SelectedTreeNodes.Count == 1)
{
// All actions should work with one process selected.
- //contextMenuStripProcess.EnableAll();
+ menuProcess.EnableAll();
// Singular nouns.
- //priorityMenuItem.Text = "&Priority";
- //terminateToolStripMenuItem.Text = "&Terminate Process";
- //suspendToolStripMenuItem.Text = "&Suspend Process";
- //resumeToolStripMenuItem.Text = "&Resume Process";
+ priorityMenuItem.Text = "&Priority";
+ terminateMenuItem.Text = "&Terminate Process";
+ suspendMenuItem.Text = "&Suspend Process";
+ resumeMenuItem.Text = "&Resume Process";
// Clear the priority menu items.
- realTimeToolStripMenuItem.Checked = false;
- highToolStripMenuItem.Checked = false;
- aboveNormalToolStripMenuItem.Checked = false;
- normalToolStripMenuItem.Checked = false;
- belowNormalToolStripMenuItem.Checked = false;
- idleToolStripMenuItem.Checked = false;
+ realTimeMenuItem.Checked = false;
+ highMenuItem.Checked = false;
+ aboveNormalMenuItem.Checked = false;
+ normalMenuItem.Checked = false;
+ belowNormalMenuItem.Checked = false;
+ idleMenuItem.Checked = false;
// Clear the I/O priority menu items.
- iOPriorityToolStripMenuItem.Enabled = true;
+ ioPriorityThreadMenuItem.Enabled = true;
ioPriority0ThreadMenuItem.Checked = false;
ioPriority1ThreadMenuItem.Checked = false;
- ioPriority3ThreadMenuItem.Checked = false;
+ ioPriority2ThreadMenuItem.Checked = false;
ioPriority3ThreadMenuItem.Checked = false;
try
{
- using (ProcessHandle phandle = new ProcessHandle(processSelectedPid, Program.MinProcessQueryRights))
+ using (var phandle = new ProcessHandle(processSelectedPid, Program.MinProcessQueryRights))
{
try
{
- switch (phandle.PriorityClass)
+ switch (phandle.GetPriorityClass())
{
case ProcessPriorityClass.RealTime:
- realTimeToolStripMenuItem.Checked = true;
+ realTimeMenuItem.Checked = true;
break;
case ProcessPriorityClass.High:
- highToolStripMenuItem.Checked = true;
+ highMenuItem.Checked = true;
break;
case ProcessPriorityClass.AboveNormal:
- aboveNormalToolStripMenuItem.Checked = true;
+ aboveNormalMenuItem.Checked = true;
break;
case ProcessPriorityClass.Normal:
- normalToolStripMenuItem.Checked = true;
+ normalMenuItem.Checked = true;
break;
case ProcessPriorityClass.BelowNormal:
- belowNormalToolStripMenuItem.Checked = true;
+ belowNormalMenuItem.Checked = true;
break;
case ProcessPriorityClass.Idle:
- idleToolStripMenuItem.Checked = true;
+ idleMenuItem.Checked = true;
break;
}
}
catch
{
- realTimeToolStripMenuItem.Enabled = false;
+ priorityMenuItem.Enabled = false;
}
try
{
if (OSVersion.HasIoPriority)
{
- switch (phandle.IoPriority)
+ switch (phandle.GetIoPriority())
{
case 0:
ioPriority0ThreadMenuItem.Checked = true;
@@ -1073,7 +1078,7 @@ private void menuProcess_Popup(object sender, EventArgs e)
ioPriority1ThreadMenuItem.Checked = true;
break;
case 2:
- ioPriority3ThreadMenuItem.Checked = true;
+ ioPriority2ThreadMenuItem.Checked = true;
break;
case 3:
ioPriority3ThreadMenuItem.Checked = true;
@@ -1083,37 +1088,44 @@ private void menuProcess_Popup(object sender, EventArgs e)
}
catch
{
- iOPriorityToolStripMenuItem.Enabled = false;
+ ioPriorityThreadMenuItem.Enabled = false;
}
}
}
catch
{
- priorityToolStripMenuItem.Enabled = false;
- iOPriorityToolStripMenuItem.Enabled = false;
+ priorityMenuItem.Enabled = false;
+ ioPriorityThreadMenuItem.Enabled = false;
}
// Check if we think the process exists. If we don't, disable all menu items
// to avoid random exceptions occurring when the user clicks on certain things.
if (!Program.ProcessProvider.Dictionary.ContainsKey(processSelectedPid))
{
- //menuProcess.DisableAll();
+ menuProcess.DisableAll();
}
else
{
// Check the virtualization menu item.
try
{
- using (ProcessHandle phandle = new ProcessHandle(processSelectedPid, Program.MinProcessQueryRights))
- using (TokenHandle thandle = phandle.GetToken(TokenAccess.Query))
+ using (var phandle = new ProcessHandle(processSelectedPid, Program.MinProcessQueryRights))
{
- if (virtualizationToolStripMenuItem.Enabled = thandle.IsVirtualizationAllowed)
- virtualizationToolStripMenuItem.Checked = thandle.IsVirtualizationEnabled;
+ try
+ {
+ using (var thandle = phandle.GetToken(TokenAccess.Query))
+ {
+ if (virtualizationProcessMenuItem.Enabled = thandle.IsVirtualizationAllowed())
+ virtualizationProcessMenuItem.Checked = thandle.IsVirtualizationEnabled();
+ }
+ }
+ catch
+ { }
}
}
catch
{
- virtualizationToolStripMenuItem.Enabled = false;
+ virtualizationProcessMenuItem.Enabled = false;
}
// Enable/disable DLL injection based on the process' session ID. This only applies
@@ -1124,9 +1136,9 @@ private void menuProcess_Popup(object sender, EventArgs e)
OSVersion.IsBelowOrEqual(WindowsVersion.XP) &&
Program.ProcessProvider.Dictionary[processSelectedPid].SessionId != Program.CurrentSessionId
)
- injectDLLToolStripMenuItem.Enabled = false;
+ injectDllProcessMenuItem.Enabled = false;
else
- injectDLLToolStripMenuItem.Enabled = true;
+ injectDllProcessMenuItem.Enabled = true;
}
catch (Exception ex)
{
@@ -1138,10 +1150,11 @@ private void menuProcess_Popup(object sender, EventArgs e)
// is sorting the list (!).
try
{
- if (treeProcesses.SelectedTreeNodes[0].IsLeaf && string.IsNullOrEmpty((treeProcesses.Tree.Model as ProcessTreeModel).GetSortColumn()))
- terminateProcessTreeToolStripMenuItem.Visible = false;
+ if (treeProcesses.SelectedTreeNodes[0].IsLeaf &&
+ (treeProcesses.Tree.Model as ProcessTreeModel).GetSortColumn() == "")
+ terminateProcessTreeMenuItem.Visible = false;
else
- terminateProcessTreeToolStripMenuItem.Visible = true;
+ terminateProcessTreeMenuItem.Visible = true;
}
catch (Exception ex)
{
@@ -1150,47 +1163,48 @@ private void menuProcess_Popup(object sender, EventArgs e)
// Find the process' window (if any).
windowHandle = WindowHandle.Zero;
- WindowHandle.Enumerate(handle =>
- {
- // GetWindowLong
- // Shell_TrayWnd
- if (handle.IsWindow && handle.IsVisible && handle.IsParent)
+ WindowHandle.Enumerate(
+ (handle) =>
{
- int pid;
- Win32.GetWindowThreadProcessId(handle, out pid);
-
- if (pid == processSelectedPid)
+ // GetWindowLong
+ // Shell_TrayWnd
+ if (handle.IsWindow() && handle.IsVisible() && handle.IsParent())
{
- windowHandle = handle;
- return false;
+ int pid;
+ Win32.GetWindowThreadProcessId(handle, out pid);
+
+ if (pid == processSelectedPid)
+ {
+ windowHandle = handle;
+ return false;
+ }
}
- }
- return true;
- });
+ return true;
+ });
// Enable the Window submenu if we found window owned
// by the process. Otherwise, disable the submenu.
if (windowHandle.IsInvalid)
{
- windowToolStripMenuItem1.Enabled = false;
+ windowProcessMenuItem.Enabled = false;
}
else
{
- windowToolStripMenuItem1.Enabled = true;
- //windowToolStripMenuItem1.EnableAll();
+ windowProcessMenuItem.Enabled = true;
+ windowProcessMenuItem.EnableAll();
- switch (windowHandle.Placement.ShowState)
+ switch (windowHandle.GetPlacement().ShowState)
{
case ShowWindowType.ShowMinimized:
- minimizeToolStripMenuItem.Enabled = false;
+ minimizeProcessMenuItem.Enabled = false;
break;
case ShowWindowType.ShowMaximized:
- maximizeToolStripMenuItem.Enabled = false;
+ maximizeProcessMenuItem.Enabled = false;
break;
case ShowWindowType.ShowNormal:
- restoreToolStripMenuItem.Enabled = false;
+ restoreProcessMenuItem.Enabled = false;
break;
}
}
@@ -1199,37 +1213,37 @@ private void menuProcess_Popup(object sender, EventArgs e)
else
{
// Assume most process actions will not work with more than one process.
- //menuProcess.DisableAll();
+ menuProcess.DisableAll();
// Use plural nouns.
- terminateProcessTreeToolStripMenuItem.Text = "&Terminate Processes";
- suspendToolStripMenuItem.Text = "&Suspend Processes";
- resumeToolStripMenuItem.Text = "&Resume Processes";
+ terminateMenuItem.Text = "&Terminate Processes";
+ suspendMenuItem.Text = "&Suspend Processes";
+ resumeMenuItem.Text = "&Resume Processes";
// Enable a specific set of actions.
- terminateToolStripMenuItem.Enabled = true;
- suspendToolStripMenuItem.Enabled = true;
- resumeToolStripMenuItem.Enabled = true;
- reduceWorkingSetToolStripMenuItem.Enabled = true;
+ terminateMenuItem.Enabled = true;
+ suspendMenuItem.Enabled = true;
+ resumeMenuItem.Enabled = true;
+ reduceWorkingSetProcessMenuItem.Enabled = true;
copyProcessMenuItem.Enabled = true;
}
// Special case for invalid PIDs.
if (processSelectedPid <= 0 && treeProcesses.SelectedNodes.Count == 1)
{
- //priorityMenuItem.Text = "&Priority";
- //menuProcess.DisableAll();
- propertiesToolStripMenuItem1.Enabled = true;
+ priorityMenuItem.Text = "&Priority";
+ menuProcess.DisableAll();
+ propertiesProcessMenuItem.Enabled = true;
}
// Enable/disable the Select All menu item.
if (treeProcesses.Model.Nodes.Count == 0)
{
- selectAllToolStripMenuItem.Enabled = false;
+ selectAllProcessMenuItem.Enabled = false;
}
else
{
- selectAllToolStripMenuItem.Enabled = true;
+ selectAllProcessMenuItem.Enabled = true;
}
}
@@ -1418,10 +1432,12 @@ private void virtualizationProcessMenuItem_Click(object sender, EventArgs e)
try
{
- using (ProcessHandle phandle = new ProcessHandle(processSelectedPid, Program.MinProcessQueryRights))
- using (TokenHandle thandle = phandle.GetToken(TokenAccess.GenericWrite))
+ using (var phandle = new ProcessHandle(processSelectedPid, Program.MinProcessQueryRights))
{
- thandle.IsVirtualizationEnabled = !virtualizationToolStripMenuItem.Checked;
+ using (var thandle = phandle.GetToken(TokenAccess.GenericWrite))
+ {
+ thandle.SetVirtualizationEnabled(!virtualizationProcessMenuItem.Checked);
+ }
}
}
catch (Exception ex)
@@ -1441,16 +1457,15 @@ private void propertiesProcessMenuItem_Click(object sender, EventArgs e)
private void affinityProcessMenuItem_Click(object sender, EventArgs e)
{
- using (ProcessAffinity affForm = new ProcessAffinity(processSelectedPid))
+ ProcessAffinity affForm = new ProcessAffinity(processSelectedPid);
+
+ try
{
- try
- {
- affForm.ShowDialog();
- }
- catch (Exception ex)
- {
- Logging.Log(ex);
- }
+ affForm.ShowDialog();
+ }
+ catch (Exception ex)
+ {
+ Logging.Log(ex);
}
}
@@ -1500,7 +1515,6 @@ private void createDumpFileProcessMenuItem_Click(object sender, EventArgs e)
td.MainInstruction = "Creating the dump file...";
td.ShowMarqueeProgressBar = true;
td.EnableHyperlinks = true;
- td.PositionRelativeToWindow = true;
td.CallbackTimer = true;
td.Callback = (taskDialog, args, userData) =>
{
@@ -1571,14 +1585,11 @@ private void createDumpFileProcessMenuItem_Click(object sender, EventArgs e)
private void terminatorProcessMenuItem_Click(object sender, EventArgs e)
{
- using (TerminatorWindow w = new TerminatorWindow(processSelectedPid)
- {
- Text = "Terminator - " + Program.ProcessProvider.Dictionary[this.processSelectedPid].Name +
- " (PID " + this.processSelectedPid.ToString() + ")"
- })
- {
- w.ShowDialog();
- }
+ TerminatorWindow w = new TerminatorWindow(processSelectedPid);
+
+ w.Text = "Terminator - " + Program.ProcessProvider.Dictionary[processSelectedPid].Name +
+ " (PID " + processSelectedPid.ToString() + ")";
+ w.ShowDialog();
}
#region Run As
@@ -1589,10 +1600,8 @@ private void launchAsUserProcessMenuItem_Click(object sender, EventArgs e)
{
Settings.Instance.RunAsCommand = Program.ProcessProvider.Dictionary[processSelectedPid].FileName;
- using (RunWindow run = new RunWindow())
- {
- run.ShowDialog();
- }
+ RunWindow run = new RunWindow();
+ run.ShowDialog();
}
catch (Exception ex)
{
@@ -1604,11 +1613,9 @@ private void launchAsThisUserProcessMenuItem_Click(object sender, EventArgs e)
{
try
{
- using (RunWindow run = new RunWindow())
- {
- run.UsePID(processSelectedPid);
- run.ShowDialog();
- }
+ RunWindow run = new RunWindow();
+ run.UsePID(processSelectedPid);
+ run.ShowDialog();
}
catch (Exception ex)
{
@@ -1674,25 +1681,24 @@ private void heapsProcessMenuItem_Click(object sender, EventArgs e)
private void injectDllProcessMenuItem_Click(object sender, EventArgs e)
{
- using (OpenFileDialog ofd = new OpenFileDialog
- {
- Filter = "DLL Files (*.dll)|*.dll|All Files (*.*)|*.*"
- })
+ OpenFileDialog ofd = new OpenFileDialog();
+
+ ofd.Filter = "DLL Files (*.dll)|*.dll|All Files (*.*)|*.*";
+
+ if (ofd.ShowDialog() == DialogResult.OK)
{
- if (ofd.ShowDialog() == DialogResult.OK)
+ try
{
- try
- {
- using (ProcessHandle phandle = new ProcessHandle(processSelectedPid, ProcessAccess.CreateThread | ProcessAccess.VmOperation | ProcessAccess.VmWrite))
- {
- phandle.InjectDll(ofd.FileName, 5000);
- }
- }
- catch (Exception ex)
+ using (var phandle = new ProcessHandle(processSelectedPid,
+ ProcessAccess.CreateThread | ProcessAccess.VmOperation | ProcessAccess.VmWrite))
{
- PhUtils.ShowException("Unable to inject the DLL", ex);
+ phandle.InjectDll(ofd.FileName, 5000);
}
}
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to inject the DLL", ex);
+ }
}
}
@@ -1728,21 +1734,19 @@ private void protectionProcessMenuItem_Click(object sender, EventArgs e)
private void setTokenProcessMenuItem_Click(object sender, EventArgs e)
{
- using (ProcessPickerWindow picker = new ProcessPickerWindow
- {
- Label = "Select the source of the token:"
- })
+ ProcessPickerWindow picker = new ProcessPickerWindow();
+
+ picker.Label = "Select the source of the token:";
+
+ if (picker.ShowDialog() == DialogResult.OK)
{
- if (picker.ShowDialog() == DialogResult.OK)
+ try
{
- try
- {
- //KProcessHacker2.Instance.KphOpenProcessToken(picker, processSelectedPid);
- }
- catch (Exception ex)
- {
- PhUtils.ShowException("Unable to set the process token", ex);
- }
+ KProcessHacker.Instance.SetProcessToken(picker.SelectedPid, processSelectedPid);
+ }
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to set the process token", ex);
}
}
}
@@ -1787,9 +1791,9 @@ private void idleMenuItem_Click(object sender, EventArgs e)
private void bringToFrontProcessMenuItem_Click(object sender, EventArgs e)
{
- if (!windowHandle.IsInvalid && windowHandle.IsWindow)
+ if (!windowHandle.IsInvalid && windowHandle.IsWindow())
{
- WindowPlacement placement = windowHandle.Placement;
+ WindowPlacement placement = windowHandle.GetPlacement();
if (placement.ShowState == ShowWindowType.ShowMinimized)
windowHandle.Show(ShowWindowType.Restore);
@@ -1800,7 +1804,7 @@ private void bringToFrontProcessMenuItem_Click(object sender, EventArgs e)
private void restoreProcessMenuItem_Click(object sender, EventArgs e)
{
- if (!windowHandle.IsInvalid && windowHandle.IsWindow)
+ if (!windowHandle.IsInvalid && windowHandle.IsWindow())
{
windowHandle.Show(ShowWindowType.Restore);
}
@@ -1808,7 +1812,7 @@ private void restoreProcessMenuItem_Click(object sender, EventArgs e)
private void minimizeProcessMenuItem_Click(object sender, EventArgs e)
{
- if (!windowHandle.IsInvalid && windowHandle.IsWindow)
+ if (!windowHandle.IsInvalid && windowHandle.IsWindow())
{
windowHandle.Show(ShowWindowType.ShowMinimized);
}
@@ -1816,7 +1820,7 @@ private void minimizeProcessMenuItem_Click(object sender, EventArgs e)
private void maximizeProcessMenuItem_Click(object sender, EventArgs e)
{
- if (!windowHandle.IsInvalid && windowHandle.IsWindow)
+ if (!windowHandle.IsInvalid && windowHandle.IsWindow())
{
windowHandle.Show(ShowWindowType.ShowMaximized);
}
@@ -1824,7 +1828,7 @@ private void maximizeProcessMenuItem_Click(object sender, EventArgs e)
private void closeProcessMenuItem_Click(object sender, EventArgs e)
{
- if (!windowHandle.IsInvalid && windowHandle.IsWindow)
+ if (!windowHandle.IsInvalid && windowHandle.IsWindow())
{
windowHandle.PostMessage(WindowMessage.Close, 0, 0);
//windowHandle.Close();
@@ -1838,7 +1842,8 @@ private void searchProcessMenuItem_Click(object sender, EventArgs e)
if (treeProcesses.SelectedNodes.Count != 1)
return;
- Program.TryStart(Settings.Instance.SearchEngine.Replace("%s", treeProcesses.SelectedNodes[0].Name));
+ Program.TryStart(Settings.Instance.SearchEngine.Replace("%s",
+ treeProcesses.SelectedNodes[0].Name));
}
private void reanalyzeProcessMenuItem_Click(object sender, EventArgs e)
@@ -1884,9 +1889,7 @@ private void virusTotalMenuItem_Click(object sender, EventArgs e)
vt.Show();
}
else
- {
PhUtils.ShowError("An Internet session could not be established. Please verify connectivity.");
- }
}
private void analyzeWaitChainProcessMenuItem_Click(object sender, EventArgs e)
@@ -1912,41 +1915,41 @@ private void processP_Updated()
Program.ProcessProvider.DictionaryRemoved += processP_DictionaryRemoved;
Program.ProcessProvider.Updated -= processP_Updated;
- ProcessHandle.Current.PriorityClass = ProcessPriorityClass.High;
+ try { ProcessHandle.Current.SetPriorityClass(ProcessPriorityClass.High); }
+ catch { }
_enableNetworkProviderSync.Increment();
_refreshHighlightingSync.Increment();
if (Program.ProcessProvider.RunCount >= 1)
- this.BeginInvoke(new MethodInvoker(() =>
+ this.BeginInvoke(new MethodInvoker(delegate
{
- this.treeProcesses.Tree.EndCompleteUpdate();
- this.treeProcesses.Tree.EndUpdate();
+ treeProcesses.Tree.EndCompleteUpdate();
+ treeProcesses.Tree.EndUpdate();
if (Settings.Instance.ScrollDownProcessTree)
{
// HACK
try
{
- foreach (var process in this.treeProcesses.Model.Roots)
+ foreach (var process in treeProcesses.Model.Roots)
{
if (
string.Equals(process.Name, "explorer.exe",
- StringComparison.OrdinalIgnoreCase) &&
+ StringComparison.OrdinalIgnoreCase) &&
process.ProcessItem.Username == Program.CurrentUsername)
{
- this.treeProcesses.FindTreeNode(process).EnsureVisible2();
+ treeProcesses.FindTreeNode(process).EnsureVisible2();
break;
}
}
}
catch
- {
- }
+ { }
}
- this.treeProcesses.Invalidate();
+ treeProcesses.Invalidate();
Program.ProcessProvider.Boost();
this.Cursor = Cursors.Default;
}));
@@ -1954,7 +1957,10 @@ private void processP_Updated()
private void processP_InfoUpdater()
{
- this.BeginInvoke(new MethodInvoker(this.UpdateStatusInfo));
+ this.BeginInvoke(new MethodInvoker(delegate
+ {
+ UpdateStatusInfo();
+ }));
}
private void processP_FileProcessingReceived(int stage, int pid)
@@ -1970,7 +1976,7 @@ private void processP_FileProcessingReceived(int stage, int pid)
public void processP_DictionaryAdded(ProcessItem item)
{
ProcessItem parent = null;
- string parentText = string.Empty;
+ string parentText = "";
if (item.HasParent && Program.ProcessProvider.Dictionary.ContainsKey(item.ParentPid))
{
@@ -1988,11 +1994,11 @@ public void processP_DictionaryAdded(ProcessItem item)
this.QueueMessage("New Process: " + item.Name + " (PID " + item.Pid.ToString() + ")" + parentText);
- if (newProcessesToolStripMenuItem.Checked)
+ if (NPMenuItem.Checked)
this.GetFirstIcon().ShowBalloonTip(2000, "New Process",
"The process " + item.Name + " (" + item.Pid.ToString() +
- ") was started" + ((parentText != string.Empty) ? " by " +
- parent.Name + " (" + parent.Pid.ToString() + ")" : string.Empty) + ".", ToolTipIcon.Info);
+ ") was started" + ((parentText != "") ? " by " +
+ parent.Name + " (" + parent.Pid.ToString() + ")" : "") + ".", ToolTipIcon.Info);
}
public void processP_DictionaryRemoved(ProcessItem item)
@@ -2002,14 +2008,17 @@ public void processP_DictionaryRemoved(ProcessItem item)
if (processServices.ContainsKey(item.Pid))
processServices.Remove(item.Pid);
- if (terminatedProcessesToolStripMenuItem.Checked)
+ if (TPMenuItem.Checked)
this.GetFirstIcon().ShowBalloonTip(2000, "Terminated Process",
"The process " + item.Name + " (" + item.Pid.ToString() + ") was terminated.", ToolTipIcon.Info);
}
private void serviceP_Updated()
{
- listServices.BeginInvoke(new MethodInvoker(() => this.listServices.List.EndUpdate()));
+ listServices.BeginInvoke(new MethodInvoker(delegate
+ {
+ listServices.List.EndUpdate();
+ }));
HighlightingContext.StateHighlighting = true;
@@ -2025,11 +2034,11 @@ public void serviceP_DictionaryAdded(ServiceItem item)
{
this.QueueMessage("New Service: " + item.Status.ServiceName +
" (" + item.Status.ServiceStatusProcess.ServiceType.ToString() + ")" +
- (!string.IsNullOrEmpty(item.Status.DisplayName) ?
+ ((item.Status.DisplayName != "") ?
" (" + item.Status.DisplayName + ")" :
- string.Empty));
+ ""));
- if (newServicesToolStripMenuItem.Checked)
+ if (NSMenuItem.Checked)
this.GetFirstIcon().ShowBalloonTip(2000, "New Service",
"The service " + item.Status.ServiceName + " (" + item.Status.DisplayName + ") has been created.",
ToolTipIcon.Info);
@@ -2057,11 +2066,11 @@ public void serviceP_DictionaryModified(ServiceItem oldItem, ServiceItem newItem
{
this.QueueMessage("Service Started: " + newItem.Status.ServiceName +
" (" + newItem.Status.ServiceStatusProcess.ServiceType.ToString() + ")" +
- ((newItem.Status.DisplayName != string.Empty) ?
+ ((newItem.Status.DisplayName != "") ?
" (" + newItem.Status.DisplayName + ")" :
- string.Empty));
+ ""));
- if (startedServicesToolStripMenuItem.Checked)
+ if (startedSMenuItem.Checked)
this.GetFirstIcon().ShowBalloonTip(2000, "Service Started",
"The service " + newItem.Status.ServiceName + " (" + newItem.Status.DisplayName + ") has been started.",
ToolTipIcon.Info);
@@ -2071,20 +2080,20 @@ public void serviceP_DictionaryModified(ServiceItem oldItem, ServiceItem newItem
newState == ServiceState.Paused)
this.QueueMessage("Service Paused: " + newItem.Status.ServiceName +
" (" + newItem.Status.ServiceStatusProcess.ServiceType.ToString() + ")" +
- ((newItem.Status.DisplayName != string.Empty) ?
+ ((newItem.Status.DisplayName != "") ?
" (" + newItem.Status.DisplayName + ")" :
- string.Empty));
+ ""));
if (oldState == ServiceState.Running &&
newState == ServiceState.Stopped)
{
this.QueueMessage("Service Stopped: " + newItem.Status.ServiceName +
" (" + newItem.Status.ServiceStatusProcess.ServiceType.ToString() + ")" +
- ((newItem.Status.DisplayName != string.Empty) ?
+ ((newItem.Status.DisplayName != "") ?
" (" + newItem.Status.DisplayName + ")" :
- string.Empty));
+ ""));
- if (stoppedServicesToolStripMenuItem.Checked)
+ if (stoppedSMenuItem.Checked)
this.GetFirstIcon().ShowBalloonTip(2000, "Service Stopped",
"The service " + newItem.Status.ServiceName + " (" + newItem.Status.DisplayName + ") has been stopped.",
ToolTipIcon.Info);
@@ -2123,11 +2132,11 @@ public void serviceP_DictionaryRemoved(ServiceItem item)
{
this.QueueMessage("Deleted Service: " + item.Status.ServiceName +
" (" + item.Status.ServiceStatusProcess.ServiceType.ToString() + ")" +
- ((item.Status.DisplayName != string.Empty) ?
+ ((item.Status.DisplayName != "") ?
" (" + item.Status.DisplayName + ")" :
- string.Empty));
+ ""));
- if (deletedServicesToolStripMenuItem.Checked)
+ if (DSMenuItem.Checked)
this.GetFirstIcon().ShowBalloonTip(2000, "Service Deleted",
"The service " + item.Status.ServiceName + " (" + item.Status.DisplayName + ") has been deleted.",
ToolTipIcon.Info);
@@ -2150,6 +2159,102 @@ public void serviceP_DictionaryRemoved_Process(ServiceItem item)
#region Service Context Menu
+ private void menuService_Popup(object sender, EventArgs e)
+ {
+ if (listServices.SelectedItems.Count == 0)
+ {
+ menuService.DisableAll();
+ goToProcessServiceMenuItem.Visible = true;
+ startServiceMenuItem.Visible = true;
+ continueServiceMenuItem.Visible = true;
+ pauseServiceMenuItem.Visible = true;
+ stopServiceMenuItem.Visible = true;
+
+ selectAllServiceMenuItem.Enabled = true;
+ }
+ else if (listServices.SelectedItems.Count == 1)
+ {
+ menuService.EnableAll();
+
+ goToProcessServiceMenuItem.Visible = true;
+ startServiceMenuItem.Visible = true;
+ continueServiceMenuItem.Visible = true;
+ pauseServiceMenuItem.Visible = true;
+ stopServiceMenuItem.Visible = true;
+
+ try
+ {
+ ServiceItem item = Program.ServiceProvider.Dictionary[listServices.SelectedItems[0].Name];
+
+ if (item.Status.ServiceStatusProcess.ProcessID != 0)
+ {
+ goToProcessServiceMenuItem.Enabled = true;
+ }
+ else
+ {
+ goToProcessServiceMenuItem.Enabled = false;
+ }
+
+ if ((item.Status.ServiceStatusProcess.ControlsAccepted & ServiceAccept.PauseContinue)
+ == 0)
+ {
+ continueServiceMenuItem.Visible = false;
+ pauseServiceMenuItem.Visible = false;
+ }
+ else
+ {
+ continueServiceMenuItem.Visible = true;
+ pauseServiceMenuItem.Visible = true;
+ }
+
+ if (item.Status.ServiceStatusProcess.CurrentState == ServiceState.Paused)
+ {
+ startServiceMenuItem.Enabled = false;
+ pauseServiceMenuItem.Enabled = false;
+ }
+ else if (item.Status.ServiceStatusProcess.CurrentState == ServiceState.Running)
+ {
+ startServiceMenuItem.Enabled = false;
+ continueServiceMenuItem.Enabled = false;
+ }
+ else if (item.Status.ServiceStatusProcess.CurrentState == ServiceState.Stopped)
+ {
+ pauseServiceMenuItem.Enabled = false;
+ stopServiceMenuItem.Enabled = false;
+ }
+
+ if ((item.Status.ServiceStatusProcess.ControlsAccepted & ServiceAccept.Stop) == 0 &&
+ item.Status.ServiceStatusProcess.CurrentState == ServiceState.Running)
+ {
+ stopServiceMenuItem.Enabled = false;
+ }
+ }
+ catch
+ {
+ menuService.DisableAll();
+ copyServiceMenuItem.Enabled = true;
+ propertiesServiceMenuItem.Enabled = true;
+ }
+ }
+ else
+ {
+ menuService.DisableAll();
+
+ goToProcessServiceMenuItem.Visible = false;
+ startServiceMenuItem.Visible = false;
+ continueServiceMenuItem.Visible = false;
+ pauseServiceMenuItem.Visible = false;
+ stopServiceMenuItem.Visible = false;
+
+ copyServiceMenuItem.Enabled = true;
+ propertiesServiceMenuItem.Enabled = true;
+ selectAllServiceMenuItem.Enabled = true;
+ }
+
+ if (listServices.List.Items.Count == 0)
+ selectAllServiceMenuItem.Enabled = false;
+ }
+
private void goToProcessServiceMenuItem_Click(object sender, EventArgs e)
{
this.SelectProcess(
@@ -2209,7 +2314,7 @@ private void propertiesServiceMenuItem_Click(object sender, EventArgs e)
private void selectAllServiceMenuItem_Click(object sender, EventArgs e)
{
- this.listServices.Items.SelectAll();
+ Utils.SelectAll(listServices.Items);
}
#endregion
@@ -2328,26 +2433,22 @@ private void thumbButtonManager_TaskbarButtonCreated(object sender, EventArgs e)
private void findHandlesToolStripButton_Click(object sender, EventArgs e)
{
- findHandlesMenuItem.PerformClick();
+ findHandlesMenuItem_Click(sender, e);
}
private void refreshToolStripButton_Click(object sender, EventArgs e)
{
- if (Program.ProcessProvider.RunCount > 1)
- Program.ProcessProvider.Boost();
-
- if (Program.ServiceProvider.RunCount > 1)
- Program.ServiceProvider.Boost();
+ updateNowMenuItem_Click(sender, e);
}
private void sysInfoToolStripButton_Click(object sender, EventArgs e)
{
- sysInfoMenuItem.PerformClick();
+ sysInfoMenuItem_Click(sender, e);
}
private void optionsToolStripButton_Click(object sender, EventArgs e)
{
- optionsMenuItem.PerformClick();
+ optionsMenuItem_Click(sender, e);
}
#endregion
@@ -2422,18 +2523,18 @@ public void ClearLog()
private void CreateShutdownMenuItems()
{
- AddMenuItemDelegate addMenuItem = (text, onClick) =>
+ AddMenuItemDelegate addMenuItem = (string text, EventHandler onClick) =>
{
- shutdownMenuItem.DropDownItems.Add(text, null, onClick);
- shutdownTrayMenuItem.DropDownItems.Add(text, null, onClick);
+ shutdownMenuItem.MenuItems.Add(new MenuItem(text, onClick));
+ shutdownTrayMenuItem.MenuItems.Add(new MenuItem(text, onClick));
shutDownToolStripMenuItem.DropDownItems.Add(text, null, onClick);
};
- addMenuItem("Lock", (sender, e) => Win32.LockWorkStation());
- addMenuItem("Logoff", (sender, e) => Win32.ExitWindowsEx(ExitWindowsFlags.Logoff, 0));
+ addMenuItem("Lock", (sender, e) => { Win32.LockWorkStation(); });
+ addMenuItem("Logoff", (sender, e) => { Win32.ExitWindowsEx(ExitWindowsFlags.Logoff, 0); });
addMenuItem("-", null);
- addMenuItem("Sleep", (sender, e) => Win32.SetSuspendState(false, false, false));
- addMenuItem("Hibernate", (sender, e) => Win32.SetSuspendState(true, false, false));
+ addMenuItem("Sleep", (sender, e) => { Win32.SetSuspendState(false, false, false); });
+ addMenuItem("Hibernate", (sender, e) => { Win32.SetSuspendState(true, false, false); });
addMenuItem("-", null);
addMenuItem("Restart", (sender, e) =>
{
@@ -2471,7 +2572,7 @@ private Bitmap GetUacShieldIcon()
const int height = 50;
const int margin = 4;
Bitmap shieldImage;
- Button button = new Button
+ Button button = new Button()
{
Text = " ",
Size = new Size(width, height),
@@ -2614,10 +2715,25 @@ private void LoadOtherSettings()
if (Loader.LoadDll(Settings.Instance.DbgHelpPath) == IntPtr.Zero)
Loader.LoadDll("dbghelp.dll");
- // Load symsrv.dll from the same directory as dbghelp.dll.
- // TODO: improve logic.
- if (Loader.LoadDll(System.IO.Path.GetDirectoryName(Settings.Instance.DbgHelpPath) + "\\symsrv.dll") == IntPtr.Zero)
- Loader.LoadDll("symsrv.dll");
+ // Find the location of the dbghelp.dll we loaded and load symsrv.dll.
+ try
+ {
+ ProcessHandle.Current.EnumModules((module) =>
+ {
+ if (module.FileName.ToLowerInvariant().EndsWith("dbghelp.dll"))
+ {
+ // Load symsrv.dll from the same directory as dbghelp.dll.
+
+ Loader.LoadDll(System.IO.Path.GetDirectoryName(module.FileName) + "\\symsrv.dll");
+
+ return false;
+ }
+
+ return true;
+ });
+ }
+ catch
+ { }
// Set the first run setting here.
Settings.Instance.FirstRun = false;
@@ -2657,12 +2773,12 @@ private void SaveSettings()
Settings.Instance.ServiceListViewColumns = ColumnSettings.SaveSettings(listServices.List);
Settings.Instance.NetworkListViewColumns = ColumnSettings.SaveSettings(listNetwork.List);
- Settings.Instance.NewProcesses = newProcessesToolStripMenuItem.Checked;
- Settings.Instance.TerminatedProcesses = terminatedProcessesToolStripMenuItem.Checked;
- Settings.Instance.NewServices = newServicesToolStripMenuItem.Checked;
- Settings.Instance.StartedServices = startedServicesToolStripMenuItem.Checked;
- Settings.Instance.StoppedServices = stoppedServicesToolStripMenuItem.Checked;
- Settings.Instance.DeletedServices = deletedServicesToolStripMenuItem.Checked;
+ Settings.Instance.NewProcesses = NPMenuItem.Checked;
+ Settings.Instance.TerminatedProcesses = TPMenuItem.Checked;
+ Settings.Instance.NewServices = NSMenuItem.Checked;
+ Settings.Instance.StartedServices = startedSMenuItem.Checked;
+ Settings.Instance.StoppedServices = stoppedSMenuItem.Checked;
+ Settings.Instance.DeletedServices = DSMenuItem.Checked;
try
{
@@ -2705,18 +2821,20 @@ private void UpdateProgram(bool interactive)
{
checkForUpdatesMenuItem.Enabled = false;
- NativeThreadPool.QueueWorkItem(o =>
- {
- Updater.Update(this, interactive);
- this.BeginInvoke(new MethodInvoker(() => this.checkForUpdatesMenuItem.Enabled = true));
- }, null);
+ Thread t = new Thread(new ThreadStart(() =>
+ {
+ Updater.Update(this, interactive);
+ this.Invoke(new MethodInvoker(() => checkForUpdatesMenuItem.Enabled = true));
+ }), Utils.SixteenthStackSize);
+ t.IsBackground = true;
+ t.Start();
}
private void UpdateSessions()
{
- TerminalServerHandle currentServer = TerminalServerHandle.GetCurrent();
+ var currentServer = TerminalServerHandle.GetCurrent();
- usersToolStripMenuItem.DropDownItems.Clear();
+ usersMenuItem.MenuItems.Clear();
foreach (var session in currentServer.GetSessions())
{
@@ -2729,82 +2847,88 @@ private void UpdateSessions()
continue;
}
- AddMenuItemDelegate addMenuItem = (text, onClick) =>
- {
- usersToolStripMenuItem.DropDownItems.Add(text, null, onClick);
- shutdownTrayMenuItem.DropDownItems.Add(text, null, onClick);
- shutDownToolStripMenuItem.DropDownItems.Add(text, null, onClick);
- };
+ MenuItem userMenuItem = new MenuItem();
- addMenuItem("Disconnect", (sender, e) =>
- {
- int sessionId = (int)((MenuItem)sender).Tag;
+ userMenuItem.Text = session.SessionId + ": " + displayName;
+
+ MenuItem currentMenuItem;
- SessionActions.Disconnect(this, session.SessionId, false);
- });
+ currentMenuItem = new MenuItem() { Text = "Disconnect", Tag = session.SessionId };
+ currentMenuItem.Click += (sender, e) =>
+ {
+ int sessionId = (int)((MenuItem)sender).Tag;
- //MenuItem userMenuItem = new MenuItem();
- //userMenuItem.Text = session.SessionId + ": " + displayName;
- addMenuItem("Logoff", (sender, e) =>
+ SessionActions.Disconnect(this, sessionId, false);
+ };
+ userMenuItem.MenuItems.Add(currentMenuItem);
+ currentMenuItem = new MenuItem() { Text = "Logoff", Tag = session.SessionId };
+ currentMenuItem.Click += (sender, e) =>
{
int sessionId = (int)((MenuItem)sender).Tag;
- SessionActions.Logoff(this, session.SessionId, true);
- });
-
- addMenuItem("Send Message...", (sender, e) =>
+ SessionActions.Logoff(this, sessionId, true);
+ };
+ userMenuItem.MenuItems.Add(currentMenuItem);
+ currentMenuItem = new MenuItem() { Text = "Send Message...", Tag = session.SessionId };
+ currentMenuItem.Click += (sender, e) =>
{
+ int sessionId = (int)((MenuItem)sender).Tag;
+
try
{
- MessageBoxWindow mbw = new MessageBoxWindow
- {
- MessageBoxTitle = "Message from " + Program.CurrentUsername
- };
+ var mbw = new MessageBoxWindow();
+ mbw.MessageBoxTitle = "Message from " + Program.CurrentUsername;
mbw.OkButtonClicked += () =>
- {
- try
- {
- TerminalServerHandle.GetCurrent().GetSession(session.SessionId).SendMessage(
- mbw.MessageBoxTitle,
- mbw.MessageBoxText,
- MessageBoxButtons.OK,
- mbw.MessageBoxIcon,
- 0,
- 0,
- mbw.MessageBoxTimeout,
- false
- );
-
- return true;
- }
- catch (Exception ex)
{
- PhUtils.ShowException("Unable to send the message", ex);
- return false;
- }
- };
+ try
+ {
+ TerminalServerHandle.GetCurrent().GetSession(sessionId).SendMessage(
+ mbw.MessageBoxTitle,
+ mbw.MessageBoxText,
+ MessageBoxButtons.OK,
+ mbw.MessageBoxIcon,
+ 0,
+ 0,
+ mbw.MessageBoxTimeout,
+ false
+ );
+ return true;
+ }
+ catch (Exception ex)
+ {
+ PhUtils.ShowException("Unable to send the message", ex);
+ return false;
+ }
+ };
mbw.ShowDialog();
}
catch (Exception ex)
{
PhUtils.ShowException("Unable to show the message window", ex);
}
- });
-
- addMenuItem("Properties...", (sender, e) =>
+ };
+ userMenuItem.MenuItems.Add(currentMenuItem);
+ currentMenuItem = new MenuItem() { Text = "Properties...", Tag = session.SessionId };
+ currentMenuItem.Click += (sender, e) =>
{
+ int sessionId = (int)((MenuItem)sender).Tag;
+
try
{
- using (var sessionWindow = new SessionInformationWindow(TerminalServerHandle.GetCurrent().GetSession(session.SessionId)))
- sessionWindow.ShowDialog();
+ var sessionInformationWindow =
+ new SessionInformationWindow(TerminalServerHandle.GetCurrent().GetSession(sessionId));
+
+ sessionInformationWindow.ShowDialog();
}
catch (Exception ex)
{
PhUtils.ShowException("Unable to show session properties", ex);
}
- });
+ };
+ userMenuItem.MenuItems.Add(currentMenuItem);
+ usersMenuItem.MenuItems.Add(userMenuItem);
session.Dispose();
}
}
@@ -2830,8 +2954,8 @@ private void SetProcessPriority(ProcessPriorityClass priority)
{
try
{
- using (ProcessHandle phandle = new ProcessHandle(processSelectedPid, ProcessAccess.SetInformation))
- phandle.PriorityClass = priority;
+ using (var phandle = new ProcessHandle(processSelectedPid, ProcessAccess.SetInformation))
+ phandle.SetPriorityClass(priority);
}
catch (Exception ex)
{
@@ -2843,8 +2967,8 @@ private void SetProcessIoPriority(int ioPriority)
{
try
{
- using (ProcessHandle phandle = new ProcessHandle(processSelectedPid, ProcessAccess.SetInformation))
- phandle.IoPriority = ioPriority;
+ using (var phandle = new ProcessHandle(processSelectedPid, ProcessAccess.SetInformation))
+ phandle.SetIoPriority(ioPriority);
}
catch (Exception ex)
{
@@ -2942,6 +3066,11 @@ protected override void WndProc(ref Message m)
}
}
break;
+
+ case (int)WindowMessage.Paint:
+ this.Painting();
+ break;
+
case (int)WindowMessage.Activate:
case (int)WindowMessage.KillFocus:
{
@@ -2974,7 +3103,7 @@ protected override void WndProc(ref Message m)
case (int)WindowMessage.SettingChange:
{
// Refresh icon sizes.
- this.ExecuteOnIcons(icon => icon.Size = UsageIcon.GetSmallIconSize());
+ this.ExecuteOnIcons((icon) => icon.Size = UsageIcon.GetSmallIconSize());
// Refresh the tree view visual style.
treeProcesses.Tree.RefreshVisualStyles();
}
@@ -2991,27 +3120,29 @@ public void Exit()
public void Exit(bool saveSettings)
{
- Program.ProcessProvider.Enabled = false;
- Program.ProcessProvider.Dispose();
+ //processP.Dispose();
+ //serviceP.Dispose();
+ //networkP.Dispose();
- Program.ServiceProvider.Enabled = false;
- Program.ServiceProvider.Dispose();
-
- Program.NetworkProvider.Enabled = false;
- Program.NetworkProvider.Dispose();
-
- this.ExecuteOnIcons(icon => icon.Visible = false);
- this.ExecuteOnIcons(icon => icon.Dispose());
+ this.ExecuteOnIcons((icon) => icon.Visible = false);
+ this.ExecuteOnIcons((icon) => icon.Dispose());
// Only save settings if requested and no other instance of
// PH is running.
if (saveSettings && !Program.CheckPreviousInstance())
SaveSettings();
- if (KProcessHacker2.Instance != null)
- KProcessHacker2.Instance.Dispose();
+ this.Visible = false;
+
+ if (KProcessHacker.Instance != null)
+ KProcessHacker.Instance.Close();
- Win32.NtTerminateProcess(ProcessHandle.Current, NtStatus.Success);
+ try
+ {
+ Win32.ExitProcess(0);
+ }
+ catch
+ { }
}
private void HackerWindow_FormClosing(object sender, FormClosingEventArgs e)
@@ -3023,7 +3154,7 @@ private void HackerWindow_FormClosing(object sender, FormClosingEventArgs e)
)
{
e.Cancel = true;
- this.showHideProcessHackerToolStripMenuItem.PerformClick();
+ showHideMenuItem_Click(sender, null);
return;
}
@@ -3037,26 +3168,26 @@ private void CheckedMenuItem_Click(object sender, EventArgs e)
public void LoadFixOSSpecific()
{
- //if (KProcessHacker.Instance == null)
- //hiddenProcessesMenuItem.Visible = false;
+ if (KProcessHacker.Instance == null)
+ hiddenProcessesMenuItem.Visible = false;
- //if (KProcessHacker.Instance == null || !OSVersion.HasSetAccessToken)
- setTokenToolStripMenuItem.Visible = false;
+ if (KProcessHacker.Instance == null || !OSVersion.HasSetAccessToken)
+ setTokenProcessMenuItem.Visible = false;
- //if (KProcessHacker.Instance == null || !Settings.Instance.EnableExperimentalFeatures)
- protectionToolStripMenuItem.Visible = false;
+ if (KProcessHacker.Instance == null || !Settings.Instance.EnableExperimentalFeatures)
+ protectionProcessMenuItem.Visible = false;
if (!OSVersion.HasUac)
- virtualizationToolStripMenuItem.Visible = false;
+ virtualizationProcessMenuItem.Visible = false;
if (OSVersion.IsBelow(WindowsVersion.Vista))
- analyzeWaitChainToolStripMenuItem.Visible = false;
+ analyzeWaitChainProcessMenuItem.Visible = false;
if (OSVersion.IsBelow(WindowsVersion.XP))
tabControl.TabPages.Remove(tabNetwork);
if (!OSVersion.HasIoPriority)
- iOPriorityToolStripMenuItem.Visible = false;
+ ioPriorityThreadMenuItem.Visible = false;
}
private void LoadFixNProcessHacker()
@@ -3105,8 +3236,9 @@ private void LoadUac()
{
if (Program.ElevationType == TokenElevationType.Limited)
{
- this.showDetailsForAllProcessesMenuItem.Image = this.GetUacShieldIcon();
- //vistaMenu.SetImage(showDetailsForAllProcessesMenuItem, uacShieldIcon);
+ uacShieldIcon = this.GetUacShieldIcon();
+
+ vistaMenu.SetImage(showDetailsForAllProcessesMenuItem, uacShieldIcon);
//vistaMenu.SetImage(startServiceMenuItem, uacShieldIcon);
//vistaMenu.SetImage(continueServiceMenuItem, uacShieldIcon);
//vistaMenu.SetImage(pauseServiceMenuItem, uacShieldIcon);
@@ -3143,39 +3275,42 @@ private void LoadNotificationIcons()
foreach (var icon in notifyIcons)
icon.Icon = (Icon)blackIcon.Clone();
- this.ExecuteOnIcons(icon => icon.ContextMenu = contextMenuStripTray);
- this.ExecuteOnIcons(icon => icon.MouseDoubleClick += notifyIcon_MouseDoubleClick);
-
- this.cpuHistoryMenuItem.Checked = Settings.Instance.CpuHistoryIconVisible;
- this.cpuUsageMenuItem.Checked = Settings.Instance.CpuUsageIconVisible;
- this.ioHistoryMenuItem.Checked = Settings.Instance.IoHistoryIconVisible;
- this.commitHistoryMenuItem.Checked = Settings.Instance.CommitHistoryIconVisible;
- this.physMemHistoryMenuItem.Checked = Settings.Instance.PhysMemHistoryIconVisible;
+ this.ExecuteOnIcons((icon) => icon.ContextMenu = menuIcon);
+ this.ExecuteOnIcons((icon) => icon.MouseDoubleClick += notifyIcon_MouseDoubleClick);
+ cpuHistoryMenuItem.Checked = Settings.Instance.CpuHistoryIconVisible;
+ cpuUsageMenuItem.Checked = Settings.Instance.CpuUsageIconVisible;
+ ioHistoryMenuItem.Checked = Settings.Instance.IoHistoryIconVisible;
+ commitHistoryMenuItem.Checked = Settings.Instance.CommitHistoryIconVisible;
+ physMemHistoryMenuItem.Checked = Settings.Instance.PhysMemHistoryIconVisible;
this.ApplyIconVisibilities();
- this.newProcessesToolStripMenuItem.Checked = Settings.Instance.NewProcesses;
- this.terminatedProcessesToolStripMenuItem.Checked = Settings.Instance.TerminatedProcesses;
- this.newServicesToolStripMenuItem.Checked = Settings.Instance.NewServices;
- this.startedServicesToolStripMenuItem.Checked = Settings.Instance.StartedServices;
- this.stoppedServicesToolStripMenuItem.Checked = Settings.Instance.StoppedServices;
- this.deletedServicesToolStripMenuItem.Checked = Settings.Instance.DeletedServices;
+ NPMenuItem.Checked = Settings.Instance.NewProcesses;
+ TPMenuItem.Checked = Settings.Instance.TerminatedProcesses;
+ NSMenuItem.Checked = Settings.Instance.NewServices;
+ startedSMenuItem.Checked = Settings.Instance.StartedServices;
+ stoppedSMenuItem.Checked = Settings.Instance.StoppedServices;
+ DSMenuItem.Checked = Settings.Instance.DeletedServices;
- this.newProcessesToolStripMenuItem.Click += this.CheckedMenuItem_Click;
- this.terminatedProcessesToolStripMenuItem.Click += this.CheckedMenuItem_Click;
- this.newServicesToolStripMenuItem.Click += this.CheckedMenuItem_Click;
- this.startedServicesToolStripMenuItem.Click += this.CheckedMenuItem_Click;
- this.stoppedServicesToolStripMenuItem.Click += this.CheckedMenuItem_Click;
- this.deletedServicesToolStripMenuItem.Click += this.CheckedMenuItem_Click;
+ NPMenuItem.Click += new EventHandler(CheckedMenuItem_Click);
+ TPMenuItem.Click += new EventHandler(CheckedMenuItem_Click);
+ NSMenuItem.Click += new EventHandler(CheckedMenuItem_Click);
+ startedSMenuItem.Click += new EventHandler(CheckedMenuItem_Click);
+ stoppedSMenuItem.Click += new EventHandler(CheckedMenuItem_Click);
+ DSMenuItem.Click += new EventHandler(CheckedMenuItem_Click);
}
private void LoadControls()
{
networkInfomationMenuItem.Visible = false; // not ready
- analyzeWaitChainToolStripMenuItem.Visible = false; // not ready
+ analyzeWaitChainProcessMenuItem.Visible = false; // not ready
+
+ GenericViewMenu.AddMenuItems(copyProcessMenuItem.MenuItems, treeProcesses.Tree);
+ GenericViewMenu.AddMenuItems(copyServiceMenuItem.MenuItems, listServices.List, null);
+ GenericViewMenu.AddMenuItems(copyNetworkMenuItem.MenuItems, listNetwork.List, null);
- //GenericViewMenu.AddMenuItems(copyProcessMenuItem.MenuItems, treeProcesses.Tree);
- //GenericViewMenu.AddMenuItems(copyToolStripMenuItem1.MenuItems, listServices.List, null);
- //GenericViewMenu.AddMenuItems(copyNetworkMenuItem.MenuItems, listNetwork.List, null);
+ treeProcesses.ContextMenu = menuProcess;
+ listServices.ContextMenu = menuService;
+ listNetwork.ContextMenu = menuNetwork;
treeProcesses.Provider = Program.ProcessProvider;
treeProcesses.Tree.BeginUpdate();
@@ -3205,33 +3340,30 @@ private void LoadControls()
}
treeProcesses.Tree.MouseDown += (sender, e) =>
- {
- if (e.Button == MouseButtons.Right && e.Location.Y < treeProcesses.Tree.ColumnHeaderHeight)
{
- ContextMenu menu = new ContextMenu();
-
- menu.MenuItems.Add(new MenuItem("Choose Columns...", (sender_, e_) =>
+ if (e.Button == MouseButtons.Right && e.Location.Y < treeProcesses.Tree.ColumnHeaderHeight)
{
- using (var c = new ChooseColumnsWindow(treeProcesses.Tree))
- {
- c.ShowDialog();
- }
+ ContextMenu menu = new ContextMenu();
- copyProcessMenuItem.DropDownItems.Clear();
- //GenericViewMenu.AddMenuItems(copyProcessMenuItem.MenuItems, treeProcesses.Tree);
- treeProcesses.Tree.InvalidateNodeControlCache();
- treeProcesses.Tree.Invalidate();
- }));
+ menu.MenuItems.Add(new MenuItem("Choose Columns...", (sender_, e_) =>
+ {
+ (new ChooseColumnsWindow(treeProcesses.Tree)
+ { }).ShowDialog();
- menu.Show(treeProcesses.Tree, e.Location);
- }
- };
+ copyProcessMenuItem.MenuItems.DisposeAndClear();
+ GenericViewMenu.AddMenuItems(copyProcessMenuItem.MenuItems, treeProcesses.Tree);
+ treeProcesses.Tree.InvalidateNodeControlCache();
+ treeProcesses.Tree.Invalidate();
+ }));
- treeProcesses.Tree.ColumnClicked += (sender, e) => this.DeselectAll(this.treeProcesses.Tree);
+ menu.Show(treeProcesses.Tree, e.Location);
+ }
+ };
+ treeProcesses.Tree.ColumnClicked += (sender, e) => { DeselectAll(treeProcesses.Tree); };
treeProcesses.Tree.ColumnReordered += (sender, e) =>
{
- copyProcessMenuItem.DropDownItems.Clear();
- // GenericViewMenu.AddMenuItems(copyProcessMenuItem.MenuItems, treeProcesses.Tree);
+ copyProcessMenuItem.MenuItems.DisposeAndClear();
+ GenericViewMenu.AddMenuItems(copyProcessMenuItem.MenuItems, treeProcesses.Tree);
};
tabControlBig_SelectedIndexChanged(null, null);
@@ -3239,17 +3371,17 @@ private void LoadControls()
private void LoadAddShortcuts()
{
- treeProcesses.Tree.KeyDown += (sender, e) =>
- {
- if (e.Control && e.KeyCode == Keys.A)
+ treeProcesses.Tree.KeyDown +=
+ (sender, e) =>
{
- treeProcesses.TreeNodes.SelectAll();
- treeProcesses.Tree.Invalidate();
- }
-
- if (e.Control && e.KeyCode == Keys.C) GenericViewMenu.TreeViewAdvCopy(treeProcesses.Tree, -1);
- };
+ if (e.Control && e.KeyCode == Keys.A)
+ {
+ treeProcesses.TreeNodes.SelectAll();
+ treeProcesses.Tree.Invalidate();
+ }
+ if (e.Control && e.KeyCode == Keys.C) GenericViewMenu.TreeViewAdvCopy(treeProcesses.Tree, -1);
+ };
listServices.List.AddShortcuts();
listNetwork.List.AddShortcuts();
}
@@ -3261,31 +3393,31 @@ private void LoadApplyCommandLineArgs()
private void LoadStructs()
{
- WorkQueue.GlobalQueueWorkItemTag(new MethodInvoker(() =>
- {
- try
+ WorkQueue.GlobalQueueWorkItemTag(new Action(() =>
{
- if (System.IO.File.Exists(Application.StartupPath + "\\structs.txt"))
+ try
{
- Structs.StructParser parser = new ProcessHacker.Structs.StructParser(Program.Structs);
+ if (System.IO.File.Exists(Application.StartupPath + "\\structs.txt"))
+ {
+ Structs.StructParser parser = new ProcessHacker.Structs.StructParser(Program.Structs);
- parser.Parse(Application.StartupPath + "\\structs.txt");
+ parser.Parse(Application.StartupPath + "\\structs.txt");
+ }
}
- }
- catch (Exception ex)
- {
- QueueMessage("Error loading structure definitions: " + ex.Message);
- }
- }), "load-structs");
+ catch (Exception ex)
+ {
+ QueueMessage("Error loading structure definitions: " + ex.Message);
+ }
+ }), "load-structs");
}
private void LoadOther()
{
try
{
- using (TokenHandle thandle = ProcessHandle.Current.GetToken(TokenAccess.Query))
- using (Sid sid = thandle.User)
- this.Text += " [" + sid.GetFullName(true) + "]" + (KProcessHacker2.Instance != null ? "+" : string.Empty);
+ using (var thandle = ProcessHandle.Current.GetToken(TokenAccess.Query))
+ using (var sid = thandle.GetUser())
+ this.Text += " [" + sid.GetFullName(true) + (KProcessHacker.Instance != null ? "+" : "") + "]";
}
catch
{ }
@@ -3303,6 +3435,10 @@ public HackerWindow()
{
InitializeComponent();
+ // Force the handle to be created
+ { var handle = this.Handle; }
+ Program.HackerWindowHandle = this.Handle;
+
if (OSVersion.HasExtendedTaskbar)
{
// We need to call this here or we don't receive the TaskbarButtonCreated message
@@ -3311,7 +3447,7 @@ public HackerWindow()
Windows7Taskbar.ProcessAppId = "ProcessHacker";
thumbButtonManager = new ThumbButtonManager(this);
- thumbButtonManager.TaskbarButtonCreated += this.thumbButtonManager_TaskbarButtonCreated;
+ thumbButtonManager.TaskbarButtonCreated += new EventHandler(thumbButtonManager_TaskbarButtonCreated);
}
this.AddEscapeToClose();
@@ -3323,8 +3459,11 @@ public HackerWindow()
Program.NetworkProvider.Enabled = true;
Program.NetworkProvider.Boost();
}, 2);
-
- _refreshHighlightingSync = new ActionSync(() => this.BeginInvoke(new MethodInvoker(this.treeProcesses.RefreshItems), null), 2);
+ _refreshHighlightingSync = new ActionSync(
+ () =>
+ {
+ this.BeginInvoke(new Action(treeProcesses.RefreshItems), null);
+ }, 2);
Logging.Logged += this.QueueMessage;
this.LoadWindowSettings();
@@ -3332,7 +3471,8 @@ public HackerWindow()
this.LoadControls();
this.LoadNotificationIcons();
- if ((!Settings.Instance.StartHidden && !Program.StartHidden) || Program.StartVisible)
+ if ((!Settings.Instance.StartHidden && !Program.StartHidden) ||
+ Program.StartVisible)
{
this.Visible = true;
}
@@ -3343,145 +3483,110 @@ public HackerWindow()
this.LoadOther();
this.LoadStructs();
+ vistaMenu.DelaySetImageCalls = false;
+ vistaMenu.PerformPendingSetImageCalls();
+
Program.ServiceProvider.Enabled = true;
Program.ServiceProvider.Boost();
- ProcessHackerRestartRecovery.ApplicationRestartRecoveryManager.RegisterForRestart();
- //ProcessHackerRestartRecovery.ApplicationRestartRecoveryManager.RegisterForRecovery();
-
- this.CreateShutdownMenuItems();
- this.LoadFixOSSpecific();
- this.LoadUac();
- this.LoadAddShortcuts();
- this.LoadFixNProcessHacker();
-
- toolStrip.Items.Add(new ToolStripSeparator());
- var targetButton = new TargetWindowButton();
- targetButton.TargetWindowFound += (pid, tid) => this.SelectProcess(pid);
- toolStrip.Items.Add(targetButton);
-
- var targetThreadButton = new TargetWindowButton();
- targetThreadButton.TargetWindowFound += (pid, tid) => Program.GetProcessWindow(Program.ProcessProvider.Dictionary[pid], f =>
- {
- Program.FocusWindow(f);
- f.SelectThread(tid);
- });
- targetThreadButton.Image = Properties.Resources.application_go;
- targetThreadButton.Text = "Find window and select thread";
- targetThreadButton.ToolTipText = "Find window and select thread";
- toolStrip.Items.Add(targetThreadButton);
-
- try { TerminalServerHandle.RegisterNotificationsCurrent(this, true); }
- catch (Exception ex) { Logging.Log(ex); }
- try { this.UpdateSessions(); }
- catch (Exception ex) { Logging.Log(ex); }
-
- try { Win32.SetProcessShutdownParameters(0x100, 0); }
- catch { }
-
- if (Settings.Instance.AppUpdateAutomatic)
- this.UpdateProgram(false);
-
- ToolStripManager.Renderer = new AeroRenderer(ToolbarTheme.Blue);
+ _dontCalculate = false;
}
private void HackerWindow_Load(object sender, EventArgs e)
{
- Program.UpdateWindowMenu(windowToolStripMenuItem, this);
+ Program.UpdateWindowMenu(windowMenuItem, this);
this.ApplyFont(Settings.Instance.Font);
this.BeginInvoke(new MethodInvoker(this.LoadApplyCommandLineArgs));
}
+ private void HackerWindow_SizeChanged(object sender, EventArgs e)
+ {
+ tabControl.Invalidate(false);
+ }
+
private void HackerWindow_VisibleChanged(object sender, EventArgs e)
{
treeProcesses.Draw = this.Visible;
}
- private void contextMenuStripService_Opening(object sender, System.ComponentModel.CancelEventArgs e)
+ // ==== Performance hacks section ====
+ private bool _dontCalculate = true;
+ private int _layoutCount = 0;
+
+ protected override void OnLayout(LayoutEventArgs levent)
{
- switch (this.listServices.SelectedItems.Count)
+ _layoutCount++;
+
+ if (_layoutCount < 3)
+ return;
+
+ base.OnLayout(levent);
+ }
+
+ protected override void OnResize(EventArgs e)
+ {
+ if (_dontCalculate)
+ return;
+
+ //
+ // Size grip bug fix as per
+ // http://jelle.druyts.net/2003/10/20/StatusBarResizeBug.aspx
+ //
+ if (statusBar != null)
{
- case 0:
- this.goToProcessServiceMenuItem.Visible = true;
- this.startToolStripMenuItem.Visible = true;
- this.continueToolStripMenuItem.Visible = true;
- this.pauseToolStripMenuItem.Visible = true;
- this.stopToolStripMenuItem.Visible = true;
- this.selectAllServiceMenuItem.Enabled = true;
- break;
- case 1:
- this.goToProcessServiceMenuItem.Visible = true;
- this.startToolStripMenuItem.Visible = true;
- this.continueToolStripMenuItem.Visible = true;
- this.pauseToolStripMenuItem.Visible = true;
- this.stopToolStripMenuItem.Visible = true;
- try
- {
- ServiceItem item = Program.ServiceProvider.Dictionary[this.listServices.SelectedItems[0].Name];
+ statusBar.SizingGrip = (WindowState == FormWindowState.Normal);
+ }
- if (item.Status.ServiceStatusProcess.ProcessID != 0)
- {
- this.goToProcessServiceMenuItem.Enabled = true;
- }
- else
- {
- this.goToProcessServiceMenuItem.Enabled = false;
- }
+ base.OnResize(e);
+ }
- if ((item.Status.ServiceStatusProcess.ControlsAccepted & ServiceAccept.PauseContinue) == 0)
- {
- this.continueToolStripMenuItem.Visible = false;
- this.pauseToolStripMenuItem.Visible = false;
- }
- else
- {
- this.continueToolStripMenuItem.Visible = true;
- this.pauseToolStripMenuItem.Visible = true;
- }
+ private bool isFirstPaint = true;
- switch (item.Status.ServiceStatusProcess.CurrentState)
- {
- case ServiceState.Paused:
- this.startToolStripMenuItem.Enabled = false;
- this.pauseToolStripMenuItem.Enabled = false;
- break;
- case ServiceState.Running:
- this.startToolStripMenuItem.Enabled = false;
- this.continueToolStripMenuItem.Enabled = false;
- break;
- case ServiceState.Stopped:
- this.pauseToolStripMenuItem.Enabled = false;
- this.stopToolStripMenuItem.Enabled = false;
- break;
- }
+ private void Painting()
+ {
+ if (isFirstPaint)
+ {
+ isFirstPaint = false;
+
+ ProcessHackerRestartRecovery.ApplicationRestartRecoveryManager.RegisterForRestart();
+ //ProcessHackerRestartRecovery.ApplicationRestartRecoveryManager.RegisterForRecovery();
- if ((item.Status.ServiceStatusProcess.ControlsAccepted & ServiceAccept.Stop) == 0 &&
- item.Status.ServiceStatusProcess.CurrentState == ServiceState.Running)
- {
- this.stopToolStripMenuItem.Enabled = false;
- }
- }
- catch
+ this.CreateShutdownMenuItems();
+ this.LoadFixOSSpecific();
+ this.LoadUac();
+ this.LoadAddShortcuts();
+ this.LoadFixNProcessHacker();
+
+ toolStrip.Items.Add(new ToolStripSeparator());
+ var targetButton = new TargetWindowButton();
+ targetButton.TargetWindowFound += (pid, tid) => this.SelectProcess(pid);
+ toolStrip.Items.Add(targetButton);
+
+ var targetThreadButton = new TargetWindowButton();
+ targetThreadButton.TargetWindowFound += (pid, tid) =>
{
- //contextMenuStripService.DisableAll();
- this.copyToolStripMenuItem1.Enabled = true;
- this.propertiesToolStripMenuItem.Enabled = true;
- }
- break;
- default:
- this.goToProcessServiceMenuItem.Visible = false;
- this.startToolStripMenuItem.Visible = false;
- this.continueToolStripMenuItem.Visible = false;
- this.pauseToolStripMenuItem.Visible = false;
- this.stopToolStripMenuItem.Visible = false;
- this.copyToolStripMenuItem1.Enabled = true;
- this.propertiesToolStripMenuItem.Enabled = true;
- this.selectAllServiceMenuItem.Enabled = true;
- break;
- }
+ Program.GetProcessWindow(Program.ProcessProvider.Dictionary[pid], (f) =>
+ {
+ Program.FocusWindow(f);
+ f.SelectThread(tid);
+ });
+ };
+ targetThreadButton.Image = Properties.Resources.application_go;
+ targetThreadButton.Text = "Find window and select thread";
+ targetThreadButton.ToolTipText = "Find window and select thread";
+ toolStrip.Items.Add(targetThreadButton);
- if (listServices.List.Items.Count == 0)
- selectAllServiceMenuItem.Enabled = false;
+ try { TerminalServerHandle.RegisterNotificationsCurrent(this, true); }
+ catch (Exception ex) { Logging.Log(ex); }
+ try { this.UpdateSessions(); }
+ catch (Exception ex) { Logging.Log(ex); }
+
+ try { Win32.SetProcessShutdownParameters(0x100, 0); }
+ catch { }
+
+ if (Settings.Instance.AppUpdateAutomatic)
+ this.UpdateProgram(false);
+ }
}
}
}
diff --git a/1.x/trunk/ProcessHacker/Forms/HackerWindow.resx b/1.x/trunk/ProcessHacker/Forms/HackerWindow.resx
index 127dec02d..9f272f97e 100644
--- a/1.x/trunk/ProcessHacker/Forms/HackerWindow.resx
+++ b/1.x/trunk/ProcessHacker/Forms/HackerWindow.resx
@@ -112,36 +112,24 @@
2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
- 357, 17
-
-
- 742, 17
-
-
- 547, 17
-
-
- 143, 17
-
-
- 241, 17
-
-
+
17, 17
-
- 929, 17
+
+ 141, 17
-
- 69
+
+