Share via


Eject or Undock a Laptop PC from Command Line or C#

dell-dock Took me awhile to find this, so it is worth sharing.  If you have a computer (usually laptop, notebook, etc) with a docking station and want to tell the PC to undock itself from the station from the command line, this is it.  For me the scenario is that I frequently undock my system to take it home or to the office, which means I manually hit the undock button, remove the PC, open up the lid, wait for it to respond, then close the lid to put it to sleep.  Now I have a little batch file that I click that undocks the PC and goes to sleep a few moments later.  I’ve tested that this works for Windows XP (WinXP), Windows Vista, and Windows 7 (Win7).

Here is the command line…

rundll32 cfgmgr32.dll,CM_Request_Eject_PC

And here is some C# code from the entry I added to pinvoke.net,
the Visual Studio solution with code is here ejectpc.zip

class Program
{
  [DllImport("cfgmgr32.dll", SetLastError = true)]
  static extern int CM_Request_Eject_PC();
 
  static void Main(string[] args)
  { CM_Request_Eject_PC(); }
}

Worth noting is that the command begins the undock process, notifies the user via the normal hardware mechanisms that the PC is ready for undock, and then waits for the user to either undock the machine or a timeout.  This is handy for knowing when the machine was actually undocked.

And yet another option is to use a little bit of .vbs windows script code, ejectpc.vbs

CreateObject("Shell.Application").EjectPC

References

Comments

  • Anonymous
    July 10, 2009
    What's the api to monitor when this happens? I want to do something (mute my audio) when this occurs.

  • Anonymous
    October 23, 2009
    Thanks, this is exactly what I was looking for.  When I run this code, I see an "Undock Complete" message though my laptop continues to function normally.  Is there a way to automatically re-dock my laptop?  These are test cases that I'm writing for software our organization is developing.

  • Anonymous
    October 29, 2009
    Thanks alot! I was looking for a solution for Undocking our notebooks via scripting

  • Anonymous
    November 28, 2011
    The comment has been removed

  • Anonymous
    March 26, 2013
    thanks this helped a co-worker a lot!