- •Материал к курсам «Объектно-ориентированное программирование», «Инструментальные средства визуального программирования» и «Современные технологии и инструментарий программирования»
- •8. Интерфейс графического устройства, цвет и шрифт 71
- •10. Консольные приложения Windows 91
- •21. Алгоритмы 220
- •22. Профилирование программы в Microsoft Visual Studio 6.0 238
- •23. Некоторые функции api Win32 240
- •24. Разное-всякое 247
- •Часть2.Технология сом 299
- •Предисловие автора
- •1.3.Работа со строками
- •1.3.1.Кодировки и кодовые страницы
- •1.3.2.О кодировке Unicode
- •1.3.3.Использование класса cString
- •1251 (Cyrillic (Windows) ) в кодировку 866 (Cyrillic dos).
- •1.3.4.Некоторые полезные функции класса cString
- •1.4.Явное преобразование типов
- •1.4.1.Преобразование полиморфных типов dynamic_cast
- •1.4.2.Преобразование неполиморфных типов static_cast
- •1.4.3.Преобразование reinterpret_cast
- •2.Соглашения об именах
- •3.Пространства имен
- •4.Макросы и отладка
- •4.1.Макрос trace
- •4.2.Объект afxDump
- •4.3.Классы cDumpContext и cObject
- •4.5.Макрос assert_valid
- •4.6.Макрос verify
- •4.7.Автоматическая диагностика неуничтоженных объектов
- •5.Каркас приложений mfc
- •5.1.Понятие каркаса приложений
- •Каркас приложений и библиотека классов
- •Пример на базе каркаса приложений
- •5.2.Сопоставление сообщений в библиотеке mfc
- •5.3.Документы и их представление
- •5.4.Функции взаимодействия «документ-вид»
- •5.5.Простейшее приложение на базе архитектуры «документ-вид»
- •5.6.Усложненное взаимодействие «документ-вид»
- •6.Класс «вид» библиотеки mfc (версия mvs 6.0)
- •6.1.Что такое «вид»
- •6.2.Интерфейсы sdi и mdi
- •6.3. Сценарий создания приложения drw в ис mvs 6.0
- •6.4.Класс cdrwView
- •6.5.Рисование внутри окна представления: Windows gdi
- •Функция-член OnDraw
- •Контекст устройства в Windows
- •Добавление кода рисования в программу drw
- •6.6.Первое знакомство с редакторами ресурсов
- •Содержимое файла drw.Rc
- •Работа с редактором диалоговых окон
- •6.7.Конфигурации Win32 Debug и Win32 Release
- •6.8.Активизация диагностических макросов
- •6.9.Предкомпилированные заголовочные файлы
- •6.10.Два способа запуска программы
- •7.Класс «вид» библиотеки mfc (версия mvs 2005)
- •7.1.Что такое «вид»
- •7.2.Интерфейсы sdi и mdi
- •7.3. Сценарий создания приложения с архитектурой документ-вид в среде mvs 2005
- •7.4.Класс cdrwView
- •7.5.Рисование внутри окна представления: Windows gdi
- •Функция-член OnDraw
- •Контекст устройства в Windows
- •Добавление кода рисования в программу drw
- •7.6.Конфигурации Win32 Debug и Win32 Release
- •7.7.Активизация диагностических макросов
- •7.8.Два способа запуска программы
- •8.Интерфейс графического устройства, цвет и шрифт
- •8.1.Классы контекста дисплея cClientDc и cWindowDc
- •8.2.Создание и уничтожение cdc-объектов
- •8.3.Состояние контекста устройства
- •8.4.Класс cPaintDc
- •8.5.Объекты gdi
- •8.6.Создание и уничтожение gdi-объектов
- •8.7.Управление gdi-объектами
- •8.8.Стандартные gdi-объекты
- •8.9.Время жизни контекста устройства
- •9.1.Приложение, основанное на диалоговом окне
- •9.2.Приложение без поддержки архитектуры документ-вид
- •9.3.Приложение с поддержкой архитектуры документ-вид
- •9.4.Краткая характеристика базовых классов класса вид
- •9.4.1.Класс cView
- •9.4.2.Класс cFormView
- •9.4.3.Класс cHtmlView
- •9.4.4.Класс cListView
- •9.4.5.Класс cRichEditView
- •9.4.6.Класс cScrollView
- •9.4.7.Класс cTreeView
- •10.2.Создание консоли
- •10.3.Закрытие консоли
- •10.4.Дескрипторы консоли
- •10.5.Входной буфер консоли
- •10.6.Буферы дисплея консоли
- •10.7.Размер буфера окна и дисплея
- •10.8.Скроллинг дисплейного буфера
- •10.9.Методы ввода/вывода в консольных приложениях
- •10.10.Режимы консоли
- •10.11.Высокоуровневый консольный ввод/вывод
- •10.12.Высокоуровневые режимы консоли
- •10.13.Высокоуровневые функции ввода и вывода консоли
- •10.15.Низкоуровневые режимы консоли
- •10.16.Низкоуровневые функции ввода консоли
- •10.14.Низкоуровневые функции ввода и вывода консоли
- •10.17.Низкоуровневые функции вывода консоли
- •10.18.Кодовые страницы в консольных приложениях
- •10.19.Пример консольного приложения ColorRusConsole
- •10.20.Использование графики в консольных приложениях
- •10.21.Изменение заголовка окна приложения и его прятание
- •11.Архитектура документ-вид и диалоговое окно
- •11.1.Как получить доступ к документу из диалогового окна
- •11.1.1.Первый способ
- •11.1.2.Второй способ
- •11.2.Как получить доступ к представлению из диалогового окна
- •11.3.Отображение данных в управляющих элементах диалогового окна и их получение (mvs 6.0)
- •11.4.Создание оконных подклассов для расширенного управления вводом данных
- •12.Обработка файлов
- •12.1.Обработка текстовых файлов (mvs 6.0)
- •12.2.Обработка текстовых файлов (mvs 2005)
- •12.3.Обработка двоичных файлов
- •12.4.Поиск файлов и каталогов по заданному пути и маске
- •12.5.Диалоги по выбору имени файла и каталога
- •13.Обработка сообщений Windows
- •13.1.Обработка сообщений в рамках одного приложения
- •13.2.Об обработке команд
- •13.3.Обработка сообщений в рамках системы
- •14.Разработка и использование собственных dll
- •14.1.Основы dll
- •14.1.1.Согласование импортируемых элементов с экспортируемыми
- •14.1.2.Явное и неявное связывание
- •14.1.3.Связывание по символьным именам против связывания по порядковым номерам
- •14.1.4.Точка входа в dll: функция DllMain
- •14.1.5.Описатели экземпляров и загрузка ресурсов
- •14.1.6.Порядок поиска dll клиентской программой
- •14.1.7.Отладка dll
- •14.1.9.Общие dll mfc-библиотеки
- •14.1.10.Dll-расширения: экспорт классов
- •14.1.11.Последовательность поиска ресурсов в dll-расширении
- •14.2.Разработка библиотеки
- •14.3.Разработка клиентского приложения, использующего библиотеку dll
- •15.Обработка растровых изображений
- •16.Обработка исключительных ситуаций
- •If (блок будет работать)
- •16.1.Введение в обработку исключительных ситуаций
- •16.2.Синтаксис обработки исключительных ситуаций
- •16.3.Синтаксис инициирования исключительных ситуаций
- •16.4.Примеры генерации и обработки исключительных ситуаций
- •17.Классы
- •17.1.Пример класса tVector
- •17.2.Класс tVector с перегруженными операциями
- •18.Шаблоны классов
- •18.1.Пример шаблона класса
- •18.2.Шаблон класса tVector
- •19.Стандартная библиотека, библиотеки mfc и atl
- •19.1.Состав стандартной библиотеки
- •19.2.Библиотеки mfc и atl
- •20.Коллекции
- •20.1.Обзор коллекций mfc
- •20.2.Шаблонные классы коллекций mfc
- •20.3.Использование массивов, списков и ассоциативных массивов
- •20.3.1.Использование простых массивов и списков
- •20.3.2.Члены класса cArray
- •Конструкторы
- •Атрибуты
- •Обработка
- •Доступ к элементам
- •Увеличение размера массива
- •Вставки и удаления
- •Операции
- •20.3.3.Члены класса cList
- •Параметры
- •Возвращаемое значение
- •Замечания
- •Параметры
- •Возвращаемое значение
- •20.3.4.Использование простых ассоциативных массивов
- •20.4.Использование шаблонов коллекций типизированных указателей
- •20.4.1.Использование массивов и списков типизированных указателей
- •20.4.2.Использование типизированных указателей на ассоциативные массивы
- •20.5.Использование контейнера vector
- •20.5.1.Конструкторы
- •Пример использования конструкторов
- •20.5.4.Иллюстрация использования класса vector
- •21.Алгоритмы
- •21.1.Общие соглашения
- •21.2.Итераторы
- •21.3.Функциональные объекты
- •21.4.Распределители
- •21.5.Состав библиотеки алгоритмов
- •21.6.Немодифицирующие алгоритмы
- •21.7.Пример использования шаблонной функции sort() из библиотеки алгоритмов
- •21.8.Сортировка массива объектов пользовательского класса
- •21.9.Еще одна иллюстрация некоторых алгоритмов на примере обработки числового массива
- •22.Профилирование программы в Microsoft Visual Studio 6.0
- •23.Некоторые функции api Win32
- •23.1.Получение информации о компьютере и операционной системе
- •23.1.1.Функция GetLogicalDrives
- •23.1.2.Функция GetDriveType
- •23.1.3.Функция GetDriveType
- •23.1.4.Функция GetDiskFreeSpaceEx
- •23.1.5.Функция GlobalMemoryStatus
- •23.1.6.Функции GetComputerName, GetUserNameA
- •23.1.7.Функции GetSystemDirectory, GetTempPath, GetWindowsDirectory, GetCurrentDirectory
- •23.1.8.Функция GetSystemInfo
- •24.Разное-всякое
- •24.1.Русификация приложений
- •24.2.Помощь и всплывающие подсказки
- •24.3.Использование ini-файла
- •24.3.1.Ansi-версия программы для среды mvs 6.0.
- •24.3.2.Unicode-версия программы для ис mvs-2005 и mvs-2008.
- •24.3.3.Ansi-версия программы для ис mvs-2005.
- •24.3.4.Ansi-версия программы для ис mvs-2008
- •24.4.Установка размеров и положения главного окна-рамки приложения
- •24.5.Создание дополнительного потока в консольном приложении
- •24.6.Интеллектуальные указатели
- •24.7.Управление формой курсора мыши
- •24.8.Как выйти из длительного цикла
- •24.9.Получение изображения содержимого окна
- •Сохранение изображения в файле
- •0, // Первая строка развертки, которая должна
- •0, // Число копируемых линий
- •Int I; // Количество выбираемых линий
- •0, // Первая строка развертки, которая должна быть выбрана
- •0, // Число копируемых линий
- •0, // Первая выбираемая линия для изображения назначения
- •0, // Режим использования
- •24.10.Подстройка очертания окна под контур изображения
- •24.11.Как корректно завершить приложение с графическим интерфейсом из него самого
- •24.12.Обработка ошибок ввода
- •25.Интегрированная среда Microsoft Visual Studio 2005
- •25.1.Терминология
- •25.2.Свойства решения и проекта
- •25.3.Что обозначают иконки на вкладке Class View
- •26.О справочной системе msdn версий 6.0 и 2005
- •26.1.Примеры приложений (версия 6.0)
- •26.2.Учебные пособия (tutorials)
- •26.3.Примеры приложений из msdn-2005
- •26.3.1.Примеры приложений mfc (mfc samples)
- •27.Процессы и потоки
- •27.1.Основные понятия Понятие приложений, процессов и потоков
- •Текущие диск и каталог для процесса
- •Определение версии системы
- •Когда полезно создавать потоки
- •Когда многопоточность неэффективна
- •Механизм многопоточности Windows
- •Приостановка, возобновление и переключение потоков
- •Приостановка и возобновление процессов
- •27.2.Функция потока
- •Функция CreateThread
- •Завершение потока
- •Часть2.Технология сом
- •28.Краткий обзор концепций программирования
- •29.Обзор технологии .Net и c#
- •29.1.Введение
- •29.2.Характеристика платформы .Net Framework
- •Среда разработки: Microsoft Visual Studio
- •Язык f#
- •29.3.Пример консольного приложения
- •29.4.Класс стек на основе связного списка
- •29.5.Чтение текстового файла
- •30.Предпосылки возникновения com
- •31.Межпроцессное взаимодействие
- •34.Введение в com технологии
- •34.1.Основные понятия и определения
- •34.2.Технология com как спецификация и реализация
- •34.3.Составляющие приложений com
- •35.Способы реализации сом серверов
- •35.1.Виды серверов и их основные характеристики
- •35.2.Алгоритм взаимодействия клиента с внутрипроцессным сервером
- •Последовательность действий при вызове клиентом внутрипроцессного сервера.
- •Последовательность действий при вызове клиентом локального или удаленного сервера
- •36.Интерфейсы
- •37.Доступ к серверу с помощью пользовательских интерфейсов
- •38.Доступ к серверу с помощью интерфейса iDispatch
- •38.1.Сценарий для версии mvs 6.0
- •38.2.Сценарий для версии mvs 2005
- •38.3.Доступ к серверу Excel в mvs 2005 с помощью диспетчерского интерфейса
- •39.Применение интеллектуальных указателей для доступа к серверам
- •39.1.Импорт библиотеки типов
- •39.2.Доступ к серверу SolidWorks 2003 с помощью интеллектуальных указателей
- •39.3.Доступ к серверу SolidWorks 2007 с помощью интеллектуальных указателей
- •39.4.Доступ к серверу Microsoft Word с помощью интеллектуальных указателей из консольного приложения
- •39.5.Доступ к серверу Microsoft Word с помощью интеллектуальных указателей из gui-приложения
- •40.Внедрение и связывание объектов
- •40.1.Понятие внедрения и связывания объектов
- •40.2.Серверы и контейнеры
- •41.Обработка ошибок
- •41.1.Функция SetErrorMode – управление реакцией программы на ошибочные состояния
- •41.2.Функции GetLastError и SetLastError – получение кода ошибки и его установка
- •41.3.Коды ошибок hresult
- •41.4.Получение текстов сообщений об ошибках
- •42.Типы данных сом
- •42.1.Типы данных методов и свойств сом объектов
- •43.Приложения
- •43.1.Словарь терминов
- •43.2.О регистрации внутрипроцессного сервера сом
- •5. Степанов а., Менг Ли. Руководство по стандартной библиотеке шаблонов (stl)/ Пер. На русский а.Суханова и а.Кутырина – м.: 1999.
- •Список литературы по платформе .Net
- •9. Дон Бокс, Крис Селлз. Основы платформы .Net, том 1. Общеязыковая исполняющая среда /Пер. С англ. – м.; сПб.: к.: Издательский дом "Вильямс", 2003. – с.288. Isbn 5-8459-0455-2
- •10. Деймьен Уоткинз, Марк Хаммонд, Брэд Эйбрамз. Программирование на платформе .Net среда /Пер. С англ. – м.; сПб.: к.: Издательский дом "Вильямс", 2003. – с.368. Isbn 5-8459-0456-0
- •11. Джеффри Рихтер. Clr via c#. Программирование на платформе Microsoft .Net Framework 2.0 на языке c#. Мастер-класс / Пер. С англ. – м.:Издательство «Русская редакция»; сПб.: Питер, 2007. - 656с.
- •12. Джеффри Рихтер. Программирование на платформе Microsoft .Net Framework / Пер. С англ. – м.:Издательско-торговый дом «Русская редакция», 2003 - 512с.
- •14. Пауэрс Ларс, Майкл Снелл. Microsoft Visual Studio 2008 / Пер. С англ. — сПб.:
- •Список литературы по технологии сом
- •13. Дейл Роджерсон. Основы сом/Пер. С англ.–2-е изд., исправл. И дополн.–м,:Изд.-торг. Дом «Русская редакция».–2000, 400с.
- •15. Дэвид Чеппел. Технология ActiveX и ole/ Пер. С англ. – м.: Издательский отдел "Русская редакция" тоо "Channel Traiding Ltd.", 1999. – 320с.
- •16. Бокс д. Сущность технологии сом. Библиотека программиста. — сПб.: Питер, 2001. — 400 с.: ил. (Есть в электронном формате)
- •17. К. Таваре, к. Фертитта, б. Ректор, к. Селлз. Библиотека atl 8: внутренняя структура и применение. Microsoft Visual Studio 2005. – м.; сПб.:, к.: Издательский дом "Вильямс", 2007, 736с.
1251 (Cyrillic (Windows) ) в кодировку 866 (Cyrillic dos).
Поддерживает символы как русского, так и украинского языков*/
char * Ukr(char Str[])
{
static char Buf[1024];
strcpy_s(Buf,strlen(Str)+1,Str);
/*в следующем цикле заменяем коды русских букв на коды украинских,
не изменяя кодов остальных символов*/
for(int i=0;i<strlen(Buf);i++)
switch (Buf[i])
{
case -78 : Buf[i]=73; break; // І
case -77 : Buf[i]=105; break; // і
case -86 : Buf[i]=242; break; // Є
case -70 : Buf[i]=243; break; // є
case -81 : Buf[i]=244; break; // Ї
case -65 : Buf[i]=245; break; // ї
case -88 : Buf[i]=240; break; // Ё
case -72 : Buf[i]=241; break; // ё
default :
{
if((Buf[i]<=-17)&&(Buf[i]>=-64)) Buf[i]-=64; //А..Я,а..п
else
if((Buf[i]<=-1)&&(Buf[i]>=-16)) Buf[i]-=16; //р..я
}
}
return Buf;
}
1.3.4.Некоторые полезные функции класса cString
1.3.4.1.CString::Compare
int Compare( LPCTSTR lpsz ) const;
Return Value
Zero if the strings are identical, < 0 if this CString object is less than lpsz, or > 0 if this CString object is greater than lpsz.
Parameters
lpsz
The other string used for comparison.
Remarks
Compares this CString object with another string using the generic-text function _tcscmp. The generic-text function _tcscmp, which is defined in TCHAR.H, maps to either strcmp, wcscmp, or _mbscmp depending on the character set that is defined at compile time. Each of these functions performs a case-sensitive comparison of the strings, and is not affected by locale. For more information, see https://msdn.microsoft.com/en-us/library/e0z9k731(v=vs.60).aspx in the Run-Time Library Reference.
Example
The following example demonstrates the use of CString::Compare.
// example for CString::Compare
CString s1( "abc" );
CString s2( "abd" );
ASSERT( s1.Compare( s2 ) == -1 ); // Compare with another CString.
ASSERT( s1.Compare( "abe" ) == -1 ); // Compare with LPTSTR string.
See Also CString::CompareNoCase, CString::Collate, CString::CollateNoCase
1.3.4.2.CStringT::Delete
Deletes a character or characters from a string starting with the character at the given index.
int Delete(
int iIndex,
int nCount = 1
);
Parameters
iIndex
The zero-based index of the first character in the CStringT object to delete.
nCount
The number of characters to be removed.
Return Value
The length of the changed string.
Remarks
If nCount is longer than the string, the remainder of the string will be removed.
Example
CAtlString str(_T("Soccer is best, but liquor is quicker!"));
_tprintf_s(_T("Before: %s\n"), (LPCTSTR)str);
int n = str.Delete(6, 3);
_tprintf_s(_T("After: %s\n"), (LPCTSTR)str);
ASSERT(n == str.GetLength());
1.3.4.3.CString::Empty
void Empty( );
Remarks
Makes this CString object an empty string and frees memory as appropriate.
For more information, see n Visual C++ Programmer’s Guide
Example
The following example demonstrates the use of CString::Empty.
// example for CString::Empty
CString s( "abc" );
s.Empty();
ASSERT( s.GetLength( ) == 0 );
See Also CString::IsEmpty
1.3.4.4.CString::Find
int Find( TCHAR ch ) const;
int Find( LPCTSTR lpszSub ) const;
int Find( TCHAR ch, int nStart ) const;
int Find( LPCTSTR pstr, int nStart ) const;
Return Value
The zero-based index of the first character in this CString object that matches the requested substring or characters; -1 if the substring or character is not found.
Parameters
ch
A single character to search for.
lpszSub
A substring to search for.
nStart
The index of the character in the string to begin the search with, or 0 to start from the beginning. The character at nStart is excluded from the search if nStart is not equal to 0.
pstr
A pointer to a string to search for.
Remarks
Searches this string for the first match of a substring. The function is overloaded to accept both single characters (similar to the run-time function strchr) and strings (similar to strstr).
Example
// First example demonstrating
// CString::Find ( TCHAR ch )
CString s( "abcdef" );
ASSERT( s.Find( 'c' ) == 2 );
ASSERT( s.Find( "de" ) == 3 );
// Second example demonstrating
// CString::Find( TCHAR ch, int nStart )
CString str("The stars are aligned");
int n = str.Find('e', 5);
ASSERT(n == 12);
See Also CString::ReverseFind, CString::FindOneOf
1.3.4.5.CString::Left
CString Left( int nCount ) const; throw( CMemoryException );
Return Value
A CString object containing a copy of the specified range of characters. Note that the returned CString object may be empty.
Parameters
nCount
The number of characters to extract from this CString object.
Remarks
Extracts the first (that is, leftmost) nCount characters from this CString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted. Left is similar to the Basic LEFT$ function (except that indexes are zero-based).
For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.
Example
The following example demonstrates the use of CString::Left.
// example for CString::Left
CString s( _T("abcdef") );
ASSERT( s.Left(2) == _T("ab") );
See Also CString::Mid, CString::Right
1.3.4.6.CString::Mid
CString Mid( int nFirst ) const; throw( CMemoryException );
CString Mid( int nFirst, int nCount ) const; throw( CMemoryException );
Return Value
A CString object that contains a copy of the specified range of characters. Note that the returned CString object may be empty.
Parameters
nFirst
The zero-based index of the first character in this CString object that is to be included in the extracted substring.
nCount
The number of characters to extract from this CString object. If this parameter is not supplied, then the remainder of the string is extracted.
Remarks
Extracts a substring of length nCount characters from this CString object, starting at position nFirst (zero-based). The function returns a copy of the extracted substring. Mid is similar to the Basic MID$ function (except that indexes are zero-based).
For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.
Example
The following example demonstrates the use of CString::Mid.
// example for CString::Mid
CString s( _T("abcdef") );
ASSERT( s.Mid( 2, 3 ) == _T("cde") );
See Also CString::Left, CString::Right
1.3.4.7.CString::Remove
int CString::Remove( TCHAR ch );
Return Value
The count of characters removed from the string. Zero if the string isn't changed.
Parameters
ch
The character to be removed from a string.
Remarks
Call this member function to remove instances of ch from the string. Comparisons for the character are case-sensitive.
Example
//remove the lower-case letter 't' from a sentence:
CString str("This is a test.");
int n = str.Remove('t');
ASSERT(n == 2);
ASSERT(str == "This is a es.");
See Also CString::Replace
1.3.4.8.CString::Replace
int Replace( TCHAR chOld, TCHAR chNew );
int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );
Return Value
The number of replaced instances of the character. Zero if the string isn't changed.
Parameters
chOld
The character to be replaced by chNew.
chNew
The character replacing chOld.
lpszOld
A pointer to a string containing the character to be replaced by lpszNew.
lpszNew
A pointer to a string containing the character replacing lpszOld.
Remarks
Call this member function to replace a character with another. The first prototype of the function replaces instances of chOld with chNew in-place in the string. The second prototype of the function replaces instances of the substring lpszOld with instances of the string lpszNew.
The string may grow or shrink as a result of the replacement; that is, lpszNew and lpszOld do not have to be equal in length. Both versions perform case-sensitive matches.
Example
//First example, with old and new equal in length.
CString strZap("C--");
int n = strZap.Replace('-', '+');
ASSERT(n == 2);
ASSERT(strZap == "C++");
//Second example, old and new are of different lengths.
CString strBang("Everybody likes ice hockey");
n = strBang.Replace("hockey", "golf");
ASSERT(n == 1);
n = strBang.Replace("likes", "plays");
ASSERT(n == 1);
n = strBang.Replace("ice", NULL);
ASSERT(n == 1);
ASSERT(strBang == "Everybody plays golf");
// note that you now have an extra space in your
// sentence. To remove the extra space, include it
// in the string to be replaced, i.e.,"ice ".
See Also CString::Remove
1.3.4.9.CString::ReverseFind
int ReverseFind( TCHAR ch ) const;
Return Value
The index of the last character in this CString object that matches the requested character; –1 if the character is not found.
Parameters
ch
The character to search for.
Remarks
Searches this CString object for the last match of a substring. The function is similar to the run-time function strrchr.
Example
// Example for CString::ReverseFind
CString s( "abcabc" );
ASSERT( s.ReverseFind( 'b' ) == 4 );
See Also CString::Find, CString::FindOneOf
1.3.4.10.CString::Right
CString Right( int nCount ) const; throw( CMemoryException );
Return Value
A CString object that contains a copy of the specified range of characters. Note that the returned CString object may be empty.
Parameters
nCount
The number of characters to extract from this CString object.
Remarks
Extracts the last (that is, rightmost) nCount characters from this CString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted. Right is similar to the Basic RIGHT$ function (except that indexes are zero-based).
For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.
Example
The following example demonstrates the use of CString::Right.
// example for CString::Right
CString s( _T("abcdef") );
ASSERT( s.Right(2) == _T("ef") );
See Also CString::Mid, CString::Left
1.3.4.11.CString::SetAt
void SetAt( int nIndex, TCHAR ch );
Parameters
nIndex
Zero-based index of the character in the CString object. The nIndex parameter must be greater than or equal to 0 and less than the value returned by GetLength. The Debug version of the Microsoft Foundation Class Library will validate the bounds of nIndex; the Release version will not.
ch
The character to insert.
Remarks
You can think of a CString object as an array of characters. The SetAt member function overwrites a single character specified by an index number. SetAt will not enlarge the string if the index exceeds the bounds of the existing string.
See Also CString::GetAt, CString::operator [ ]
1.3.4.12.CString::SetSysString
BSTR SetSysString( BSTR* pbstr ) const;
Return Value
The new string.
Parameters
pbstr
A pointer to a character string.
Remarks
Reallocates the BSTR pointed to by pbstr and copies the contents of the CString object into it, including the NULL character. The value of the BSTR referenced by pbstr may change. The function throws a CMemoryException if insufficient memory exists.
This function is normally used to change the value of strings passed by reference for OLE Automation.
For more information about OLE reallocation functions in Windows, see https://msdn.microsoft.com/en-us/library/ms221533(v=vs.60).aspx and https://msdn.microsoft.com/en-us/library/ms221481(v=vs.60).aspx in the Win32 SDK OLE Programmer’s Referenc.
Example
// create an OLE string
BSTR bstr = ::SysAllocString(L"Golf is fun!");
// create a CString and change the OLE
// string to the contents of the BSTR
CString str("Hockey is best!");
BSTR bstr2 = str.SetSysString(&bstr);
// Now, both bstr and bstr2 reference a single instance of
// the "Hockey" string. The "Golf" string has been freed.
ASSERT(bstr2 == bstr);
CString Overview | Class Members | Hierarchy Chart
1.3.4.13.CString::SpanExcluding
CString SpanExcluding( LPCTSTR lpszCharSet ) const; throw( CMemoryException );
Return Value
A substring that contains characters in the string that are not in lpszCharSet, beginning with the first character in the string and ending with the first character found in the string that is also in lpszCharSet (that is, starting with the first character in the string and up to but excluding the first character in the string that is found lpszCharSet). It returns the entire string if no character in lpszCharSet is found in the string.
Parameters
lpszCharSet
A string interpreted as a set of characters.
Remarks
Use this function to search the string for the first occurrence of any character in the specified set lpszCharSet. SpanExcluding extracts and returns all characters preceding the first occurrence of a character from lpszCharSet (in other words, the character from lpszCharSet and all characters following it in the string, are not returned). If no character from lpszCharSet is found in the string, then SpanExcluding returns the entire string.
Example
The following function returns the first portion of the src param.
// Portions are delimited by a semi-colon( ; ),
// a comma( , ), a period( . ), a dash( - ),
// or a colon( : ).
CString GetFirstPart( CString src)
{
return src.SpanExcluding( ";,.- :");
}
See Also CString::SpanIncluding
1.3.4.14.CString::SpanIncluding
CString SpanIncluding( LPCTSTR lpszCharSet ) const; throw( CMemoryException );
Return Value
A substring that contains characters in the string that are in lpszCharSet, beginning with the first character in the string and ending when a character is found in the string that is not in lpszCharSet. SpanIncluding returns an empty substring if the first character in the string is not in the specified set.
Parameters
lpszCharSet
A string interpreted as a set of characters.
Remarks
Call this member function to extract characters from the string, starting with the first character, that are in the set of characters identified by lpszCharSet. If the first character of the string is not in the character set, then SpanIncluding returns an empty string. Otherwise, it returns a sequence of consecutive characters which are in the set.
Example
The following example demonstrates the use of CString::SpanIncluding.
// example for CString::SpanIncluding
CString str( "cabbage" );
CString res = str.SpanIncluding( "abc" );
ASSERT( res == "cabba" );
res = str.SpanIncluding( "xyz" );
ASSERT( res.IsEmpty( ) );
See Also CString::SpanExcluding
1.3.4.15.CString::TrimLeft
void TrimLeft( );
void CString::TrimLeft( TCHAR chTarget );
void CString::TrimLeft( LPCTSTR lpszTargets );
Parameters
chTarget
The target characters to be trimmed.
lpszTargets
A pointer to a string containing the target characters to be trimmed.
Remarks
Call the version of this member function with no parameters to trim leading whitespace characters from the string. When used with no parameters, TrimLeft removes newline, space, and tab characters.
Use the versions of this function that accept parameters to remove a particular character or a particular group of characters from the beginning of a string.
For more information, see in Visual C++ Programmer’s Guide
Example
In this example, the string "\t\t ****Hockey is best!" becomes "Hockey is best!":
CString strBefore;
CString strAfter;
strBefore = _T("\t\t ****Hockey is best!");
strAfter = strBefore;
strAfter.TrimLeft(T_("\t *"));
_tprintf(_T("Before: \"%s\"\n"), (LPCTSTR) strBefore);
_tprintf(_T("After : \"%s\"\n"), (LPCTSTR) strAfter);
See Also CString::Mid, CString::Left, CString::Right, CString::MakeUpper, CString::MakeLower, CString::MakeReverse, CString::Format
1.3.4.16.CString::TrimRight
void TrimRight( );
void CString::TrimRight( TCHAR chTarget );
void CString::TrimRight( LPCTSTR lpszTargets );
Parameters
chTarget
The target characters to be trimmed.
lpszTargets
A pointer to a string containing the target characters to be trimmed.
Remarks
Call the version of this member function with no parameters to trim trailing whitespace characters from the string. When used with no parameters, TrimRight removes trailing newline, space, and tab characters from the string.
Use the versions of this function that accept parameters to remove a particular character or a particular group of characters from the end of a string.
Example
CString strBefore;
CString strAfter;
strBefore = "Hockey is Best!!!!";
strAfter = strBefore;
str.TrimRight('!');
printf("Before: \"%s\"\n", (LPCTSTR) strBefore);
printf("After : \"%s\"\n\n", (LPCTSTR) strAfter);
strBefore = "Hockey is Best?!?!?!?!";
strAfter = strBefore;
str.TrimRight("?!");
printf("Before: \"%s\"\n", (LPCTSTR) strBefore);
printf("After : \"%s\"\n\n", (LPCTSTR) strAfter);
In the first example above, the string reading, "Hockey is Best!!!!" becomes "Hockey is Best".
In the second example above, the string reading, , "Hockey is Best?!?!?!?!" becomes "Hockey is Best".
For more information, see in Visual C++ Programmer’s Guide
See Also CString::TrimLeft, CString::Mid, CString::Left, CString::Right, CString::MakeUpper, CString::MakeLower, CString::MakeReverse, CString::Format
