Monday 10 January 2011

C# useful Shell functions

Get current user's StartUp folder path:

Environment.GetFolderPath(Environment.SpecialFolder.Startup) - returns string with startup path

Get list of StartUp processes started from the Register and StartUp folder:

ManagementClass mangnmt = new ManagementClass("Win32_StartupCommand");
ManagementObjectCollection mcol = mangnmt.GetInstances();
foreach (ManagementObject strt in mcol)
{
string[] lv = new String[4];
lv[0] = strt["Caption"].ToString();
lv[1] = strt["Location"].ToString();
lv[2] = strt["Command"].ToString();
lv[3] = strt["Description"].ToString();
listView1.Items.Add(new ListViewItem(lv, 0));
}



Start new proccess, external program EXE, batch file from C#

System.Diagnostics.Process.Start(@filename, arguments);

Get list of images in folder

List images = new List();
DirectoryInfo di = new DirectoryInfo(@"c:\myimages"); // give path
FileInfo[] finfos = di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
foreach (FileInfo fi in finfos)
images.Add(Image.FromFile(fi.FullName));
Get current Windows Desktop Shell
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon", false);
MessageBox.Show((string)(key.GetValue("Shell")));
Change Windows Desktop Shell
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon", true);
key.SetValue("Shell", "NewShell.exe", RegistryValueKind.String);

Get running application full path
string AppPath = System.Windows.Forms.Application.StartupPath;
String currentProgram = System.Environment.CommandLine;
Lock, Hibernate, Restart, Stand-by, Shutdown Windows from C#
for Restart
{ System.Diagnostics.Process.Start("shutdown","/r");
}
For logoff
{ System.Diagnostics.Process.Start("shutdown", "/l");
}
For hibernate
{
System.Diagnostics.Process.Start("shutdown", "/h");
}
For shutdown
{
System.Diagnostics.Process.Start("shutdown", "/s");
}
For locking system
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern void LockWorkStation();
{
LockWorkStation();
}

Get process id and path from window handle

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out uint processId);

public static string GetProcessPath(IntPtr hwnd)
{
uint pid = 0;
GetWindowThreadProcessId(hwnd, out pid);
Process proc = Process.GetProcessById((int)pid);
return proc.MainModule.FileName.ToString();
}