RSS

Monthly Archives: August 2011

Disable Special Keys in Win App C#

Today, when I was planning to write an article on Grid View. I got a message from a very good friend of mine who is asking to disable the special keys(Windows Keys) in his application. When I start researching on it, I was thinking that it can be done using e.KeyChar but unfortunately, it is not showing any information about windows keys.

So in this post I will explain you, how can we disable the special keys (in our case windows keys) in C# Application.

1. Crete a c# windows application project
2. On the code behind of your default form add the following references

   1: using System.Diagnostics;
   2: using System.Runtime.InteropServices;

3. Now before the constructor of your form place the following code.

   1: // Structure contain information about low-level keyboard input event
   2: [StructLayout(LayoutKind.Sequential)]
   3: private struct KBDLLHOOKSTRUCT
   4: {
   5:     public Keys key;
   6:     public int scanCode;
   7:     public int flags;
   8:     public int time;
   9:     public IntPtr extra;
  10: }
  11:  
  12: //System level functions to be used for hook and unhook keyboard input
  13: private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
  14: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  15: private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
  16: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  17: private static extern bool UnhookWindowsHookEx(IntPtr hook);
  18: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  19: private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
  20: [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  21: private static extern IntPtr GetModuleHandle(string name);
  22: [DllImport("user32.dll", CharSet = CharSet.Auto)]
  23: private static extern short GetAsyncKeyState(Keys key);
  24:  
  25:  
  26: //Declaring Global objects
  27: private IntPtr ptrHook;
  28: private LowLevelKeyboardProc objKeyboardProcess;

4. Now add the following code on your constructor.

   1: public Form1()
   2: {
   3:     ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule; //Get Current Module
   4:     objKeyboardProcess = new LowLevelKeyboardProc(captureKey); //Assign callback function each time keyboard process
   5:     ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0); //Setting Hook of Keyboard Process for current module
   6:  
   7:  
   8:     InitializeComponent();
   9: }

5. Now Implement the callback function

   1: private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
   2: {
   3:     if (nCode >= 0)
   4:     {
   5:         KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));
   6:  
   7:         if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin) // Disabling Windows keys
   8:         {
   9:             return (IntPtr)1;
  10:         }
  11:     }
  12:     return CallNextHookEx(ptrHook, nCode, wp, lp);
  13: }

6. Now go to your designer class and replace your dispose method.

   1: /// <summary>
   2: /// Clean up any resources being used.
   3: /// </summary>
   4: /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
   5: protected override void Dispose(bool disposing)
   6: {
   7:     if (disposing && (components != null))
   8:     {
   9:  
  10:         components.Dispose();
  11:     }
  12:     if (ptrHook != IntPtr.Zero)
  13:     {
  14:         UnhookWindowsHookEx(ptrHook);
  15:         ptrHook = IntPtr.Zero;
  16:     }
  17:     base.Dispose(disposing);
  18: }

So, in this way we can stop the windows key operation till your application is running.You can find the VS 2008 Source code here.

Referenced by: http://geekswithblogs.net/aghausman/archive/2009/04/26/disable-special-keys-in-win-app-c.aspx
// ------------ Code ----------------------- 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace WindowsKeyPressed 
{
    public partial class Form1 : Form
    {
        // Structure contain information about low-level keyboard input event
        [StructLayout(LayoutKind.Sequential)]
        private struct KBDLLHOOKSTRUCT
        {
            public Keys key;
            public int scanCode;
            public int flags;
            public int time;
            public IntPtr extra;
        }

        //System level functions to be used for hook and unhook keyboard input
        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hook);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string name);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern short GetAsyncKeyState(Keys key);


        //Declaring Global objects
        private IntPtr ptrHook;
        private LowLevelKeyboardProc objKeyboardProcess; 

        public Form1()
        {
            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
            objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
            ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);


            InitializeComponent();
        }

        private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
        {
            if (nCode >= 0)
            {
                KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));

                if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin) // Disabling Windows keys
                {
                    return (IntPtr)1;
                }
            }
            return CallNextHookEx(ptrHook, nCode, wp, lp);
        }


        
        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            MessageBox.Show(e.KeyChar.ToString());
        }


    }

For Disable Art + Tab

// Structure contain information about low-level keyboard input event 
    [StructLayout(LayoutKind.Sequential)]
    private struct KBDLLHOOKSTRUCT
    {
        public Keys key;
        public int scanCode;
        public int flags;
        public int time;
        public IntPtr extra;
    }
    //System level functions to be used for hook and unhook keyboard input  
    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool UnhookWindowsHookEx(IntPtr hook);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string name);
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern short GetAsyncKeyState(Keys key);
    //Declaring Global objects     
    private IntPtr ptrHook;
    private LowLevelKeyboardProc objKeyboardProcess;

    private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
    {
        if (nCode >= 0)
        {
            KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));

            // Disabling Windows keys 

            if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin || objKeyInfo.key == Keys.Tab && HasAltModifier(objKeyInfo.flags) || objKeyInfo.key == Keys.Escape && (ModifierKeys & Keys.Control) == Keys.Control)     
            {
                return (IntPtr)1; // if 0 is returned then All the above keys will be enabled
            }
        }
        return CallNextHookEx(ptrHook, nCode, wp, lp);
    }

    bool HasAltModifier(int flags)
    {
        return (flags & 0x20) == 0x20;
    }

    /* Code to Disable WinKey, Alt+Tab, Ctrl+Esc Ends Here */

http://stackoverflow.com/questions/3213606/how-to-suppress-task-switch-keys-winkey-alt-tab-alt-esc-ctrl-esc-using-low
 
8 Comments

Posted by on August 30, 2011 in C#, Window Application

 

Date Range in C#

Get Date in Week:

public static DateTime EndOfWeek(DateTime dateTime)
    {
        DateTime start = StartOfWeek(dateTime);

        return start.AddDays(6);
    }

    public static DateTime StartOfWeek(DateTime dateTime)
    {
        int days = dateTime.DayOfWeek - DayOfWeek.Monday; 

        if (days < 0) 
            days += 7;

        return dateTime.AddDays(-1 * days).Date;
    }

Get Date in Month:

public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
   return new DateTime(dateTime.Year, dateTime.Month, 1);
}
public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
   DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
   return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

Referenced by: http://stackoverflow.com/questions/5080152/find-week-ending-date-of-last-completed-week
http://www.devprise.com/2006/10/03/getting-the-first-and-last-day-of-the-month-with-net-c/

 
Leave a comment

Posted by on August 30, 2011 in C#

 

HOWTO: Bare-Metal Restores from Windows Server 2008 Backup

Using the Windows Recovery Environment on Windows Server 2008 you can perform a bare-metal restore to recover your server operating system or the entire server itself. An operating system restore will only recover critical drive volumes that contain system components. If you would like to restore all volumes, you will need to conduct a full server recovery.

Before attempting to complete an operating system or full server restoration from a drive image backup created with BackupAssist, make sure of the following:

  • You have a Windows Server 2008 setup/installation disc.
  • If you are recovering to a new hard disk, make sure the disk is at least as big as the disk that contained the volumes that were backed up, regardless of the size of those volumes. For example, if there was only one volume that was 100 GB on a 1 TB disk during backup, you should use a disk that is at least 1 TB when restoring.
  • If you are recovering just the operating system, make sure that you have a backup available that contains at least the critical volumes of the server. If you are recovering the full server, make sure that you have a backup available that contains all volumes of the server.
Performing a bare metal recovery – step by step
  1. Windows Imaging RestoreBoot the Windows Server 2008 from the installation media and select the appropriate settings for:
    1. Language to install
    2. Time and currency format
    3. Keyboard or input format.

    When you’ve selected your settings, click on the Next button.

  2. Windows Imaging RestoreIn the next window, select the Repair your Computer option from the lower left corner of the console.
  3. Windows Imaging RestoreFrom the System Recovery Options window, you can choose to load any drivers required by your hard disk at this stage.  After loading any necessary drivers, such as RAID drivers, click on the Next button.

    Note that if you are performing a bare-metal restore to a brand new hard-disk, you will not see any Operating Systems listed as shown on the right. 

    If you are restoring a backup to a machine that already has Windows 2008, then it will be listed under Operating Systems. 

  4. Windows Imaging RestoreUnder the System Recovery Options window, select theWindows Complete PC Restoreoption. This will invoke theWindows Recovery Environment.
  5. Windows will then scan your machine for available backups. Please ensure that the media with your backup is connected to the machine. If Windows Complete PC Restore is unable to find the backup, please try un-connecting and re-connecting the backup device.
  6. Restore from a backupOnce your backup disk has been detected, you may choose to restore the latest backup or another backup. Windows 2008 will automatically choose your latest backup by default.

    Select the backup you want to restore from and click on the Nextbutton.

  7. In the Choose how to restore your backupwindow, you have the following options:
    1. Install any drivers for the disk you are restoring to by clicking on the Install Drivers button.
    2. Exclude disks that you don’t want formatted by clicking on the Exclude disks button.
    3. Choose to restart the computer after the restore process and to automatically check and update error information by clicking on the Advanced button.

    Once you have added the extra options, click on the Next button.

  8. Backup LocationSelect the location of your backup and click on the Next button.
  9. Confirm restore settingsConfirm your settings and click on the Finish button.
  10. Windows Recovery Environment will ask you whether you want to let Windows Complete PC Restore format the disks and restore the backups you have chosen. Click on the OK button.
  11. Your bare-metal restore of Windows Server 2008 should begin. Once done, your system should reboot and Windows will load. Congratulations – the procedure is complete!
 
Leave a comment

Posted by on August 22, 2011 in General