How to lock workstation programmatically? (C#)

by Vitaly Zayko 13. January 2009 15:48
There is no such .NET function (or at least I didn’t find). Fortunately we can use PInvoke instead.
Use this function to lock workstation’s display to protect from unauthorized use. Result of this function is the same as pressing Ctrl+Alt+Del.
  1. Add namespace at the top of your code:
    	using System.Runtime.InteropServices;
    	
  2. Declare PInvoke:
    	[DllImport("user32.dll", SetLastError = true)]
    	
    	static extern bool LockWorkStation();
    	
  3. Call this function like this:
    	if (!LockWorkStation())
    	
    	   throw new Win32Exception(Marshal.GetLastWin32Error());
    	
    	
    	
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to get some User environment information? (C#)

by Vitaly Zayko 24. December 2008 15:50

Use System.Environment namespace to get lot of information about your user. Just few examples:

 

string userName = System.Environment.UserName;
string machineName = System.Environment.MachineName;
OperatingSystem osVersion = System.Environment.OSVersion;
string userDomainName = System.Environment.UserDomainName;

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to get list of removable drives installed on a computer? (C#)

by Vitaly Zayko 16. December 2008 12:32

First of all add reference to System.Management sysm assembly.
Then run something like this:

1:/// <summary>
2:/// Retuns list of all Removable drives aailable
3:/// </summary>
4:/// <param name="UsbDrives">Structure to store drive names (e.g. "D:", "E:" etc.</param>
5:/// <returns>true if at least one removable is available</returns>
6:public bool GetRemovableDisks(out IList<string> UsbDrives)
7:{
8:   // Add System.Management reference. Then
9:    bool result = false;
10:   UsbDrives = new List<string>();
11:   using (System.Management.ManagementClass managementClass = new System.Management.ManagementClass("Win32_Diskdrive"))
12:   {
13:       using (System.Management.ManagementObjectCollection driveCollection = managementClass.GetInstances())
14:       {
15:           foreach(System.Management.ManagementObject driveObject in driveCollection)
16:               foreach (System.Management.ManagementObject drivePartition in driveObject.GetRelated("Win32_DiskPartition"))
17:                   foreach (System.Management.ManagementBaseObject logicalDisk in drivePartition.GetRelated("Win32_LogicalDisk"))
18:                   {
19:                       string drive = (logicalDisk["Name"]).ToString();
20:                       string driveDescription = logicalDisk.Properties["Description"].Value.ToString();
21:                       if (driveDescription.Equals("Removable Disk", StringComparison.InvariantCultureIgnoreCase))
22:                       {
23:                           UsbDrives.Add(drive);
24:                           result = true;
25:                       }
26:                   } 
27:       }
28:   }
29:   return result;
30:}
31:
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to get path to running Assembly? (C#)

by Vitaly Zayko 14. December 2008 23:00

In this post I explained how to find this directory in .NET Compact Framework. Here is how to do this in desktop Applications.

If you are working on a Windows Forms App you, can make this call:

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

In non-WinForms Apps use this:

System.IO.Path.GetDirectoryName(
System.Reflection.
Assembly.GetEntryAssembly().Location);

Note that last back slash is not included.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

What is equivalent of Delphi's Application.ProcessMessages in C# and VB.NET?

by Vitaly Zayko 12. December 2008 10:50
Simply use
Application.DoEvents();
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to create Windows shortcut (C#)

by Vitaly Zayko 27. November 2008 11:21

1. First of all, add reference to Windows Script Host Object model:

Add Reference to Windows Script Host Object Model

2. Add Namespace:

// Add namespace reference:
using IWshRuntimeLibrary;

3. Add the code below to your App. Note: I didn't assign all IWshShortcut properties just mostly used so please check all properties by yourself.

/// <summary>
/// Create Windows Shorcut
/// </summary>
/// <param name="SourceFile">A file you want to make shortcut to</param>
/// <param name="ShortcutFile">Path and shorcut file name including file extension (.lnk)</param>
public void CreateShortcut(string SourceFile, string ShortcutFile)
{
   CreateShortcut(SourceFile, ShortcutFile, null, null, null, null);
}

/// <summary>
/// Create Windows Shorcut
/// </summary>
/// <param name="SourceFile">A file you want to make shortcut to</param>
/// <param name="ShortcutFile">Path and shorcut file name including file extension (.lnk)</param>
/// <param name="Description">Shortcut description</param>
/// <param name="Arguments">Command line arguments</param>
/// <param name="HotKey">Shortcut hot key as a string, for example "Ctrl+F"</param>
/// <param name="WorkingDirectory">"Start in" shorcut parameter</param>
public void CreateShortcut(string SourceFile, string ShortcutFile, string Description,
   string Arguments, string HotKey, string WorkingDirectory)
{
   // Check necessary parameters first:
    if (String.IsNullOrEmpty(SourceFile))
       throw new ArgumentNullException("SourceFile");
   if (String.IsNullOrEmpty(ShortcutFile))
       throw new ArgumentNullException("ShortcutFile");

   // Create WshShellClass instance:
    WshShellClass wshShell = new WshShellClass();

   // Create shortcut object:
    IWshRuntimeLibrary.IWshShortcut shorcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(ShortcutFile);

   // Assign shortcut properties:
    shorcut.TargetPath = SourceFile;
   shorcut.Description = Description;
   if(!String.IsNullOrEmpty(Arguments))
       shorcut.Arguments = Arguments;
   if (!String.IsNullOrEmpty(HotKey))
       shorcut.Hotkey = HotKey;
   if (!String.IsNullOrEmpty(WorkingDirectory))
       shorcut.WorkingDirectory = WorkingDirectory;

   // Save the shortcut:
    shorcut.Save();
}

4. And here is how to call function you just added:

// Make sure you use try/catch block because your App may has no permissions on the target path!
try
{
   CreateShortcut(@"C:\MySourceFile.exe", @"C:\MyShortcutFile.lnk", 
       "Custom Shortcut", "/param", "Ctrl+F", @"c:\");
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message);
}

Code formatted by SaveAsHtml - a free Visual Studio 2008 plugin
Technorati Tags: ,
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to open file by associated program? (C#)

by Vitaly Zayko 19. November 2008 17:40

If you are familiar with Win32 API then you should know function ShellExecute which performs some operations on files including opening in programs associated with this particular file type.

In .NET Framework world you can use this function through PInvoke but there is a managed mechanism to do the same:

using (System.Diagnostics.Process prc = new System.Diagnostics.Process())
{
   prc.StartInfo.FileName = "c:\\test.txt";
   prc.Start();
}

Enjoy!
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to convert System.Drawing.Color to a Html representation (C#)?

by Vitaly Zayko 6. November 2008 17:17

If you are working on some Web-related App then you sooner or later will need to convert a System.Drawing.Color structure to its Html format. Below are three overloaded functions.

        /// <summary>
/// Convert System.Drawing.Color struct to a Html color representation
/// </summary>
/// <param name="color">System.Drawing.Color struct to convert from</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(Color color)
{
   return "#" + color.ToArgb().ToString("x").Substring(2);
}

/// <summary>
/// Convert Red, Green and Blue components to a Html color representation
/// </summary>
/// <param name="r">The Red component value</param>
/// <param name="g">The Green component value</param>
/// <param name="b">The Blue component value</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(int r, int g, int b)
{
   Color color = System.Drawing.Color.FromArgb(r, g, b);
   return "#" + color.ToArgb().ToString("x").Substring(2);
}

/// <summary>
/// Convert ARGB color to a Html color representation
/// </summary>
/// <param name="argb">ARGB color value</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(int argb)
{
   Color color = System.Drawing.Color.FromArgb(argb);
   return "#" + color.ToArgb().ToString("x").Substring(2);
}
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Dispose pattern (C#)

by Vitaly Zayko 5. November 2008 21:21

Pretty common pattern: if you are working on a class that utilize either unmanaged resources or managed disposable classes, you need to make your class disposable as well.

    class DisposePatternClass : IDisposable
    {
       /// <summary>
        /// Doesn't allow to dispose same instance twice
        /// </summary>
        private bool disposed = false;

       /// <summary>
        /// Privately cleaning up both managed and unmanaged resources
        /// </summary>
        /// <param name="disposing">True is DisposePatternClass.Dispose() was called; false if disposing by GC</param>
        private void CleanUp(bool disposing)
       {
           if (!this.disposed)
           {
               if (disposing)
               {
                   // Disponse Managed resources here
                }

               // Clean up Unmanaged resources here
            }

           disposed = true;
       }

       /// <summary>
        /// Manual Dispose
        /// </summary>
        public void Dispose()
       {
           CleanUp(true);
           GC.SuppressFinalize(this);
       }

       /// <summary>
        /// Destructor
        /// </summary>
        ~DisposePatternClass()
       {
           CleanUp(false);
       }
   }

Have fun!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to create a string of repeated characters (C#)?

by Vitaly Zayko 2. November 2008 13:15

Pretty common question. Here you go:

string str = new string('x', 5);
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

About the author

Vitaly Zayko

Senior Software Developer / Team Lead / Product Manager

Moscow, Russia