Monday, February 7, 2011

Positioning Window forms

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);


const int AW_HIDE = 0X10000;
const int AW_ACTIVATE = 0X20000;
const int AW_HOR_POSITIVE = 0X1;
const int AW_HOR_NEGATIVE = 0X2;
const int AW_VER_POSITIVE = 0X4;
const int AW_VER_NEGATIVE = 0X8;
const int AW_SLIDE = 0X40000;
const int AW_BLEND = 0X80000;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int AnimateWindow
(IntPtr hwand, int dwTime, int dwFlags);


public static void ApplyPOS(string strWindowName)
{
try
{
Global.FormInSession = strWindowName;
if (Global.MaintenanceMode == false)
{
IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, strWindowName);

if (Global.TestingMode == true)
{
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 300, 150, SWP_SHOWWINDOW);
}
else
{
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 15000, 150500, SWP_SHOWWINDOW);
}

Log.Flow_writeToLogFile("Positioning Form : " + strWindowName);
}
}
catch (Exception ex)
{

}
}

public static void RemovePOS(string strWindowName)
{
try
{
IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, strWindowName);
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_HIDEWINDOW);
}
catch (Exception ex)
{

}
}

Class for Keyboard Hook that Registers HotKey

public sealed class KeyboardHook : IDisposable
{
// Registers a hot key with Windows.
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
// Unregisters the hot key with Windows.
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

///
/// Represents the window that is used internally to get the messages.
///

private class Window : NativeWindow, IDisposable
{
private static int WM_HOTKEY = 0x0312;

public Window()
{
// create the handle for the window.
try
{
this.CreateHandle(new CreateParams());
}
catch (Exception ex)
{
ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Target : " + ex.TargetSite.ToString() + System.Environment.NewLine + "Message : " + ex.Message.ToString() + System.Environment.NewLine + "Stack : " + ex.StackTrace.ToString());
}
}

///
/// Overridden to get the notifications.
///

///
protected override void WndProc(ref Message m)
{
try
{
base.WndProc(ref m);

// check if we got a hot key pressed.
if (m.Msg == WM_HOTKEY)
{
// get the keys.
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);

// invoke the event to notify the parent.
if (KeyPressed != null)
KeyPressed(this, new KeyPressedEventArgs(modifier, key));
}
}
catch (Exception ex)
{
ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Target : " + ex.TargetSite.ToString() + System.Environment.NewLine + "Message : " + ex.Message.ToString() + System.Environment.NewLine + "Stack : " + ex.StackTrace.ToString());
}
}

public event EventHandler KeyPressed;

#region IDisposable Members

public void Dispose()
{
this.DestroyHandle();
}

#endregion
}

private Window _window = new Window();
private int _currentId;

public KeyboardHook()
{
try
{
// register the event of the inner native window.
_window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
{
if (KeyPressed != null)
KeyPressed(this, args);
};
}
catch (Exception ex)
{
ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Target : " + ex.TargetSite.ToString() + System.Environment.NewLine + "Message : " + ex.Message.ToString() + System.Environment.NewLine + "Stack : " + ex.StackTrace.ToString());
}
}

///
/// Registers a hot key in the system.
///

/// The modifiers that are associated with the hot key.
/// The key itself that is associated with the hot key.
public void RegisterHotKey(ModifierKeys modifier, Keys key)
{
try
{
// increment the counter.
_currentId = _currentId + 1;

// register the hot key.
if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
throw new InvalidOperationException("Couldn’t register the hot key.");
}
catch (Exception ex)
{
ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Target : " + ex.TargetSite.ToString() + System.Environment.NewLine + "Message : " + ex.Message.ToString() + System.Environment.NewLine + "Stack : " + ex.StackTrace.ToString());
}
}

///
/// A hot key has been pressed.
///

public event EventHandler KeyPressed;

#region IDisposable Members

public void Dispose()
{
// unregister all the registered hot keys.
for (int i = _currentId; i > 0; i--)
{
UnregisterHotKey(_window.Handle, i);
}

// dispose the inner native window.
_window.Dispose();
}

#endregion
}

///
/// Event Args for the event that is fired after the hot key has been pressed.
///

public class KeyPressedEventArgs : EventArgs
{
private ModifierKeys _modifier;
private Keys _key;

internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
{
_modifier = modifier;
_key = key;
}

public ModifierKeys Modifier
{
get { return _modifier; }
}

public Keys Key
{
get { return _key; }
}
}

///
/// The enumeration of possible modifiers.
///

[Flags]
public enum ModifierKeys : uint
{
Alt = 1,
Control = 2,
Shift = 4,
Win = 8
}

Block Windows Task Bar

BlockWindowsTaskbar.Show();
BlockWindowsTaskbar.Hide();

class BlockWindowsTaskbar
{
[DllImport("user32.dll")]
public static extern int FindWindow(string className, string windowText);
[DllImport("user32.dll")]
public static extern int ShowWindow(int hwnd, int command);

public const int SW_HIDE = 0;
public const int SW_SHOW = 1;

public int _taskbarHandle;
protected static int Handle
{
get
{
return FindWindow("Shell_TrayWnd", "");
}
}

public BlockWindowsTaskbar()
{
_taskbarHandle = FindWindow("Shell_TrayWnd", "");
}

public static void Show()
{
ShowWindow(Handle, SW_SHOW);
}

public static void Hide()
{
ShowWindow(Handle, SW_HIDE);
}
}

User Impersonation using c# in Windows application

ImpersonateUser iU = new ImpersonateUser();
Login = iU.Impersonate(Global.Impersonate_DOMAIN, Global.Impersonate_UID, Global.Impersonate_PWD);





class ImpersonateUser
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);

private static IntPtr tokenHandle = new IntPtr(0);
private static WindowsImpersonationContext impersonatedUser;

[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public bool Impersonate(string domainName, string userName, string password)
{
bool returnValue;
const int LOGON32_PROVIDER_DEFAULT = 0;
// Passing this parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;

// ---- Step - 1
// Call LogonUser to obtain a handle to an access token.
returnValue = LogonUser(
userName,
domainName,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref tokenHandle); // tokenHandle - new security token

//commented for avoiding exception. Instead show message box with "wrong password"
//if (false == returnValue)
//{
// int ret = Marshal.GetLastWin32Error();
// Console.WriteLine("LogonUser call failed with error code : " + ret);
// throw new System.ComponentModel.Win32Exception(ret);
//}
if (returnValue == true)
{
// ---- Step - 2
WindowsIdentity newId = new WindowsIdentity(tokenHandle);

// ---- Step - 3
impersonatedUser = newId.Impersonate();
}
return returnValue;
}

// Stops impersonation
public void Undo()
{
impersonatedUser.Undo();
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
}