Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for gettitle.cs

(view source code of gettitle.cs as plain text)

  1. using Microsoft.Win32;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. using System.Security.Principal;
  6. using System.Text;
  7.  
  8. namespace RobvanderWoude
  9. {
  10. 	class GetTitle
  11. 	{
  12. 		// DLL imports required to read window title
  13. 		[DllImport( "kernel32.dll", CharSet = CharSet.Auto, SetLastError = true )]
  14. 		internal static extern int GetConsoleTitle( StringBuilder sb, int capacity );
  15.  
  16. 		static int Main( string[] args )
  17. 		{
  18. 			try
  19. 			{
  20. 				// By default, do not strip anything
  21. 				bool trimPrefix = false;
  22. 				bool trimCmdline = false;
  23. 				string cmdline = Environment.CommandLine;
  24.  
  25. 				// Read the full window title
  26. 				string windowTitle = GetWindowTitle( );
  27.  
  28. 				#region Command Line Parsing
  29.  
  30. 				// Check command line arguments
  31. 				foreach ( string arg in args )
  32. 				{
  33. 					switch ( arg.ToLower( ) )
  34. 					{
  35. 						case "/nc":
  36. 						case "-nc":
  37. 							if ( trimCmdline )
  38. 							{
  39. 								return WriteError( "Duplicate command line switch " + arg.ToUpper( ) );
  40. 							}
  41. 							trimCmdline = true;
  42. 							break;
  43. 						case "/np":
  44. 						case "-np":
  45. 							if ( trimPrefix )
  46. 							{
  47. 								return WriteError( "Duplicate command line switch " + arg.ToUpper( ) );
  48. 							}
  49. 							// Ignore the /NP switch if we're not running with elevated privileges
  50. 							trimPrefix = UacHelper.IsProcessElevated;
  51. 							break;
  52. 						case "/?":
  53. 						case "-?":
  54. 						case "/h":
  55. 						case "-h":
  56. 						case "/help":
  57. 						case "-help":
  58. 						case "--help":
  59. 							// Display help text without error message
  60. 							return WriteError( string.Empty );
  61. 						default:
  62. 							return WriteError( "Invalid command line argument(s)" );
  63. 					}
  64. 				}
  65. 				if ( args.Length > 2 )
  66. 				{
  67. 					return WriteError( "Invalid command line argument(s)" );
  68. 				}
  69. 				#endregion Command Line Parsing
  70.  
  71. 				// If /NP is used in elevated process,
  72. 				// check if the first space in the title comes after the first colon, which must be
  73. 				// after the second position (otherwise it may be the colon for the drive letter);
  74. 				// if so, remove everything from the start through the firts colon,
  75. 				// then trim leading spaces
  76. 				if ( trimPrefix )
  77. 				{
  78. 					int posC = windowTitle.IndexOf( ':', 2 );
  79. 					int posS = windowTitle.IndexOf( ' ' );
  80. 					if ( posC > 2 && posS > posC )
  81. 					{
  82. 						windowTitle = windowTitle.Substring( posC + 1 ).Trim( );
  83. 					}
  84. 				}
  85.  
  86. 				// Strip the command line from the window title if /NC is used
  87. 				if ( trimCmdline )
  88. 				{
  89. 					int posL = windowTitle.IndexOf( " - " + cmdline );
  90. 					if ( posL > 0 )
  91. 					{
  92. 						windowTitle = windowTitle.Substring( 0, posL + 1 );
  93. 					}
  94. 				}
  95.  
  96. 				// Display the window title
  97. 				Console.WriteLine( windowTitle );
  98.  
  99. 				return 0;
  100. 			}
  101. 			catch ( Exception e )
  102. 			{
  103. 				// Display help text with error message
  104. 				return WriteError( e );
  105. 			}
  106. 		}
  107.  
  108. 		// Code to read window title, by Justin Goldspring
  109. 		public static string GetWindowTitle( )
  110. 		{
  111. 			const int nChars = 256;
  112. 			IntPtr handle = IntPtr.Zero;
  113. 			StringBuilder Buff = new StringBuilder( nChars );
  114.  
  115. 			if ( GetConsoleTitle( Buff, nChars ) > 0 )
  116. 			{
  117. 				return Buff.ToString( );
  118. 			}
  119. 			return string.Empty;
  120. 		}
  121.  
  122. 		// Code to check if running with elevated privileges, by StackOverflow.com:
  123. 		// http://www.stackoverflow.com/questions/1220213/c-detect-if-running-with-elevated-privileges
  124. 		public static class UacHelper
  125. 		{
  126. 			private const string uacRegistryKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
  127. 			private const string uacRegistryValue = "EnableLUA";
  128.  
  129. 			private static uint STANDARD_RIGHTS_READ = 0x00020000;
  130. 			private static uint TOKEN_QUERY = 0x0008;
  131. 			private static uint TOKEN_READ = ( STANDARD_RIGHTS_READ | TOKEN_QUERY );
  132.  
  133. 			[DllImport( "advapi32.dll", SetLastError = true )]
  134. 			[return: MarshalAs( UnmanagedType.Bool )]
  135. 			static extern bool OpenProcessToken( IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle );
  136.  
  137. 			[DllImport( "advapi32.dll", SetLastError = true )]
  138. 			public static extern bool GetTokenInformation( IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength );
  139.  
  140. 			public enum TOKEN_INFORMATION_CLASS
  141. 			{
  142. 				TokenUser = 1,
  143. 				TokenGroups,
  144. 				TokenPrivileges,
  145. 				TokenOwner,
  146. 				TokenPrimaryGroup,
  147. 				TokenDefaultDacl,
  148. 				TokenSource,
  149. 				TokenType,
  150. 				TokenImpersonationLevel,
  151. 				TokenStatistics,
  152. 				TokenRestrictedSids,
  153. 				TokenSessionId,
  154. 				TokenGroupsAndPrivileges,
  155. 				TokenSessionReference,
  156. 				TokenSandBoxInert,
  157. 				TokenAuditPolicy,
  158. 				TokenOrigin,
  159. 				TokenElevationType,
  160. 				TokenLinkedToken,
  161. 				TokenElevation,
  162. 				TokenHasRestrictions,
  163. 				TokenAccessInformation,
  164. 				TokenVirtualizationAllowed,
  165. 				TokenVirtualizationEnabled,
  166. 				TokenIntegrityLevel,
  167. 				TokenUIAccess,
  168. 				TokenMandatoryPolicy,
  169. 				TokenLogonSid,
  170. 				MaxTokenInfoClass
  171. 			}
  172.  
  173. 			public enum TOKEN_ELEVATION_TYPE
  174. 			{
  175. 				TokenElevationTypeDefault = 1,
  176. 				TokenElevationTypeFull,
  177. 				TokenElevationTypeLimited
  178. 			}
  179.  
  180. 			public static bool IsUacEnabled
  181. 			{
  182. 				get
  183. 				{
  184. 					RegistryKey uacKey = Registry.LocalMachine.OpenSubKey( uacRegistryKey, false );
  185. 					bool result = uacKey.GetValue( uacRegistryValue ).Equals( 1 );
  186. 					return result;
  187. 				}
  188. 			}
  189.  
  190. 			public static bool IsProcessElevated
  191. 			{
  192. 				get
  193. 				{
  194. 					// Skip this test and return false if the OS is XP or even older
  195. 					OperatingSystem osInfo = Environment.OSVersion;
  196. 					if ( osInfo.Version.Major > 5 )
  197. 					{
  198. 						if ( IsUacEnabled )
  199. 						{
  200. 							IntPtr tokenHandle;
  201. 							if ( !OpenProcessToken( Process.GetCurrentProcess( ).Handle, TOKEN_READ, out tokenHandle ) )
  202. 							{
  203. 								throw new ApplicationException( "Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error( ) );
  204. 							}
  205.  
  206. 							TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;
  207.  
  208. 							int elevationResultSize = Marshal.SizeOf( (int) elevationResult );
  209. 							uint returnedSize = 0;
  210. 							IntPtr elevationTypePtr = Marshal.AllocHGlobal( elevationResultSize );
  211.  
  212. 							bool success = GetTokenInformation( tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint) elevationResultSize, out returnedSize );
  213. 							if ( success )
  214. 							{
  215. 								elevationResult = (TOKEN_ELEVATION_TYPE) Marshal.ReadInt32( elevationTypePtr );
  216. 								bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
  217. 								return isProcessAdmin;
  218. 							}
  219. 							else
  220. 							{
  221. 								throw new ApplicationException( "Unable to determine the current elevation." );
  222. 							}
  223. 						}
  224. 						else
  225. 						{
  226. 							WindowsIdentity identity = WindowsIdentity.GetCurrent( );
  227. 							WindowsPrincipal principal = new WindowsPrincipal( identity );
  228. 							bool result = principal.IsInRole( WindowsBuiltInRole.Administrator );
  229. 							return result;
  230. 						}
  231. 					}
  232. 					else
  233. 					{
  234. 						return false;
  235. 					}
  236. 				}
  237. 			}
  238. 		}
  239.  
  240. 		// Code to display help and optional error message, by Bas van der Woude
  241. 		public static int WriteError( Exception e )
  242. 		{
  243. 			return WriteError( e == null ? null : e.Message );
  244. 		}
  245.  
  246. 		public static int WriteError( string errorMessage )
  247. 		{
  248. 			string exeName = Process.GetCurrentProcess( ).ProcessName;
  249.  
  250. 			/*
  251. 			GetTitle,  Version 4.00
  252. 			Return the current window's title, optionally stripping the 'Administrator:'
  253. 			prefix on UAC enabled systems, and/or the command line
  254.  
  255. 			Usage:    GETTITLE  [ /NC ]  [ /NP ]
  256.  
  257. 			Where:    /NC   strips the command line if appended to the title
  258. 			          /NP   strips the 'Administrator:' prefix on UAC enabled systems
  259. 			                (ignored if the process does not run with elevated privileges)
  260.  
  261. 			Credits:  Check for elevated privileges based on a thread on StackOverflow.com
  262. 			          /questions/1220213/c-detect-if-running-with-elevated-privileges
  263. 			          Code to read console window title by Justin Goldspring.
  264.  
  265. 			Written by Rob van der Woude
  266. 			http://www.robvanderwoude.com
  267. 			*/
  268.  
  269. 			if ( string.IsNullOrEmpty( errorMessage ) == false )
  270. 			{
  271. 				Console.Error.WriteLine( );
  272. 				Console.ForegroundColor = ConsoleColor.Red;
  273. 				Console.Error.Write( "ERROR: " );
  274. 				Console.ForegroundColor = ConsoleColor.White;
  275. 				Console.Error.WriteLine( errorMessage );
  276. 				Console.ResetColor( );
  277. 			}
  278.  
  279. 			Console.Error.WriteLine( );
  280. 			Console.Error.WriteLine( "GetTitle,  Version 4.00" );
  281. 			Console.Error.WriteLine( "Return the current window's title, optionally stripping the 'Administrator:'" );
  282. 			Console.Error.WriteLine( "prefix on UAC enabled systems, and/or the command line" );
  283. 			Console.Error.WriteLine( );
  284. 			Console.Error.Write( "Usage:    " );
  285. 			Console.ForegroundColor = ConsoleColor.White;
  286. 			Console.Error.WriteLine( "{0}  [ /NC ]  [ /NP ]", exeName.ToUpper( ) );
  287. 			Console.ResetColor( );
  288. 			Console.Error.WriteLine( );
  289. 			Console.Error.Write( "Where:    " );
  290. 			Console.ForegroundColor = ConsoleColor.White;
  291. 			Console.Error.Write( "/NC" );
  292. 			Console.ResetColor( );
  293. 			Console.Error.WriteLine( "   strips the command line if appended to the title" );
  294. 			Console.ForegroundColor = ConsoleColor.White;
  295. 			Console.Error.Write( "          /NP" );
  296. 			Console.ResetColor( );
  297. 			Console.Error.WriteLine( "   strips the 'Administrator:' prefix on UAC enabled systems" );
  298. 			Console.Error.WriteLine( "                (ignored if the process does not run with elevated privileges)" );
  299. 			Console.Error.WriteLine( );
  300. 			Console.Error.Write( "Credits:  Check for elevated privileges based on a thread on " );
  301. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  302. 			Console.Error.WriteLine( "StackOverflow.com" );
  303. 			Console.Error.WriteLine( "          /questions/1220213/c-detect-if-running-with-elevated-privileges" );
  304. 			Console.ResetColor( );
  305. 			Console.Error.WriteLine( "          Code to read console window title by Justin Goldspring." );
  306. 			Console.Error.WriteLine( );
  307. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  308. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  309. 			return 1;
  310. 		}
  311. 	}
  312. }

page last modified: 2024-04-16; loaded in 0.0103 seconds