How to make a form stay always on top
Sometimes we require to make our application stay always on top of other applications. You simply achive this by setting the TopMost propetry of the Form to True. This post describes the other way using Win32 API functions.
Here is the declarations
private IntPtr HWND_TOPMOST = new IntPtr(-1);
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOMOVE = 0x0002;
private const uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd,
IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
And in the Form Load event, you need to call the SetWindowPos() function like this.
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
You require System.Runtime.InteropServices namespace for using WIN32 API functions in C#.
Run the application at Windows startup
Sometimes its required to start your application while on Windows startup. This small code snippet allows you to register your application on windows startup. This code require Microsoft.Win32 namespace. To register application you need to set the key under
“HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run”
registry key.
private void RegisterInStartup(bool isChecked)
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (isChecked)
{
registryKey.SetValue("ApplicationName", Application.ExecutablePath);
}
else
{
registryKey.DeleteValue("ApplicationName");
}
}
Happy Programming