Free Information Technology Magazines and eBooks

Saturday, June 06, 2009

C#: Eject or Undock a Laptop PC

Here is a worth sharing tip from Noah Coad of MSDN blogs. This code is worth to try if you have a mobile computer such as laptop and notebook with a docking station and you want the PC to eject from the station using C# or command line. So instead manually hitting the undock button and removing the PC and put it to sleep, you can compile the C# code to form as EXE and double-click it to eject the laptop from dock station for you.


The code uses DLL import from "cfgmgr32.dll" and the System.Runtime.InteropServices namespace.


using System;
using System.Runtime.InteropServices;

namespace EjectPC
{
class Program
{
[DllImport("cfgmgr32.dll", SetLastError = true)]
static extern int CM_Request_Eject_PC();

static void Main(string[] args)
{ CM_Request_Eject_PC(); }
}
}


You can also do the same task from the command line

rundll32 cfgmgr32.dll,CM_Request_Eject_PC


This code was originally posted from Noah Coad's blog.

To stay up-to-date on Technology news, subscribe now.

1 comments:

Russ said...

Thank you, this is exactly what I was looking for. When I run this code I see an "Undock complete" message and I notice that the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\IDConfigDB\CurrentDockInfo\DockingState value gets set to 1, though the laptop remains active and is still physically attached to the docking station. I'm now looking for a way to automatically "redock" the laptop. Is this possible? I searched the functions in cfgmgr32.dll but didn't find one that will redock.