June 12, 2009

How To: Disable General Protection Fault Dialog for Your Program

Abstraction
Are you using any 3rd-party componet or ActiveX, which is not stable enough, in your program? You will get a GPF dialog if the componet in your program goes abnormal. That is not your problem totally, but actually your program crashed. There's a Windows API to prevent showing GPF dialog, you may adapt this solution if the crash can be ignored.

Code Snippet

UINT uPrevErrMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);

Do you not know what GPF is?

Windows Calendar Crash

Reference on MSDN

June 06, 2009

Read/Write Windows Registry on Windows 64-Bits Platforms (C# Version)

Abstraction
How does a 32-bits(x64) program running on Windows 64-bits(x64) access the 64-bits registry? In C#, you can use P/Invoke to call RegOpenKeyEx function with KEY_WOW64_KEY to access the 64-bits registry.

Code Snippet

//
// This is a C# example to get the version of Windows Media Center on Windows 7 64-bits.
//

class RegQueryValueDemo
{
  [DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "RegOpenKeyExW", SetLastError = true)]
  public static extern int RegOpenKeyEx(UIntPtr hKey, string subKey, uint options, int sam, out UIntPtr phkResult);
  public static UIntPtr HKEY_CURRENT_USER = (UIntPtr)0x80000001;
  public static UIntPtr HKEY_LOCAL_MACHINE = (UIntPtr)0x80000002;
  public static int KEY_QUERY_VALUE = 0x0001;
  public static int KEY_SET_VALUE = 0x0002;
  public static int KEY_CREATE_SUB_KEY = 0x0004;
  public static int KEY_ENUMERATE_SUB_KEYS = 0x0008;
  public static int KEY_WOW64_64KEY = 0x0100;
  public static int KEY_WOW64_32KEY = 0x0200;

  [DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError = true)]
  public static extern int RegQueryValueEx(UIntPtr hKey, string lpValueName, int lpReserved, out uint lpType,
    StringBuilder lpData, ref int lpcbData);

  public string GetMCEIdent()
  {
    UIntPtr regKeyHandle;
    if (RegOpenKeyEx(
    HKEY_LOCAL_MACHINE,
    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Media Center",
    0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, out regKeyHandle) == 0)
    {
      uint type;

      StringBuilder stringBuilder = new StringBuilder(2048);
      int cbData = stringBuilder.Capacity;
      if (RegQueryValueEx(regKeyHandle, "Ident", 0, out type, stringBuilder, ref cbData) == 0)
      {
        return stringBuilder.ToString();
      }
    }

    return string.Empty;
  }
}


Find a C++ version?
Read/Write Windows Registry on Windows 64-Bits Platforms

Reference on MSDN:
RegOpenKeyEx Function
32-bit and 64-bit Application Data in the Registry