Applies to: desktop apps only
Sets the title for the current console window.
Syntax
BOOL WINAPI SetConsoleTitle( __in LPCTSTR lpConsoleTitle );
Parameters
- lpConsoleTitle [in]
-
The string to be displayed in the title bar of the console window. The total size must be less than 64K.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
When the process terminates, the system restores the original console title.
This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.
Examples
The following example shows how to retrieve and modify the console title.
#include <windows.h> #include <tchar.h> #include <conio.h> #include <strsafe.h> int main( void ) { TCHAR szOldTitle[MAX_PATH]; TCHAR szNewTitle[MAX_PATH]; // Save current console title. if( GetConsoleTitle(szOldTitle, MAX_PATH) ) { // Build new console title string. StringCchPrintf(szNewTitle, MAX_PATH, TEXT("TEST: %s"), szOldTitle); // Set console title to new title if( !SetConsoleTitle(szNewTitle) ) { _tprintf(TEXT("SetConsoleTitle failed (%d)\n"), GetLastError()); return 1; } else { _tprintf(TEXT("SetConsoleTitle succeeded.\n")); } } return 0; }
Requirements
|
Minimum supported client | Windows 2000 Professional |
|---|---|
|
Minimum supported server | Windows 2000 Server |
|
Header |
|
|
Library |
|
|
DLL |
|
|
Unicode and ANSI names | SetConsoleTitleW (Unicode) and SetConsoleTitleA (ANSI) |
See also
Send comments about this topic to Microsoft
Build date: 2/3/2012
If for some reason the BCL's property on the Console class doesn't work for you, then here's the P/Invoke prototype you should use. (This is what I used when implementing Console.SetTitle)
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=true)]
[ResourceExposure(ResourceScope.Process)]
internal static extern bool SetConsoleTitle(String title);
Here is a working example of how to call it, abridged from the BCL source for .NET FX 4.0:
// MSDN says console titles can be up to 64 KB in length (bytes, not Unicode characters)
// But I get an exception if I use buffer lengths longer than ~24500 Unicode characters.
private const int MaxConsoleTitleLength = 24500;
public static String Title {
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
set {
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > MaxConsoleTitleLength)
throw new ArgumentOutOfRangeException("value", "Console title is too long for some OS's");
Contract.EndContractBlock();
new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();
if (!NativeMethods.SetConsoleTitle(value))
__Error.WinIOError(); // Call Marshal.GetLastWin32Error() then switch on that error code to create a proper exception.
}
}
Brian Grunkemeyer
.NET CoreFX team
(And yes, I wrote the Console class)
{
[DllImportAttribute("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetConsoleTitle(IntPtr lpConsoleTitle);
/// <summary>
/// Функция устанавливает заголовок окна консоли
/// путём вызова Win32API-функции SetConsoleTitle, реализованной в kernel32.dll.
/// </summary>
/// <param name="sTitle">Заголовок для окна консоли</param>
/// <returns>true - в случае удачи, false - в случае неудачи.</returns>
unsafe public static bool SetConsoleTitle(string sTitle)
{
// Преобразуем строку в массив типа char:
char[] charArray = sTitle.ToCharArray();
// Получаем указатель на первый элемент массива,
// который передаём в Win32API-функцию SetConsoleTitle:
fixed(char *lpConsoleTitle = &charArray[0])
{
try
{
return SetConsoleTitle((IntPtr)lpConsoleTitle);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}
}
//////////
class Program
{
static void Main(string[] args)
{
// Изменяем заголовок консоли при помощи Win32API-функции из kernel32.dll:
Console.WriteLine("\n\n\tУстановка заголовка консоли при помощи Win32API-функции,\n\t\t\tопределённой в kernel32.dll.\n\n");
if (Win32Api.SetConsoleTitle("Hello kernel32.dll !"))
{
Console.WriteLine("Заголовок консоли удачно изменён by Evgen N.\n\n\n");
}
}
}
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
internal static extern bool SetConsoleTitle(string title);
could any one help me with anexample?
thanks
_________________________
public class Win32Api
{
[DllImportAttribute("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetConsoleTitle(IntPtr lpConsoleTitle);
/// <summary>
/// Функция устанавливает заголовок окна
/// путём вызова Win32API-функции SetConsoleTitle, реализованной в kernel32.dll.
/// </summary>
/// <param name="sTitle">Заголовок окна</param>
/// <returns>true - в случае удачи, false - в случае неудачи.</returns>
unsafe public static bool SetConsoleTitle(string sTitle)
{
// Преобразуем строку в массив типа char:
char[] charArray = sTitle.ToCharArray();
// Получаем указатель на первый элемент массива,
// который передаём в Win32API-функцию SetConsoleTitle:
fixed(char *lpConsoleTitle = &charArray[0])
{
try
{
return SetConsoleTitle((IntPtr)lpConsoleTitle);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}
}