Читаем Программирование КПК и смартфонов на .NET Compact Framework полностью

 ReleaseDC(hwnd, hdc);

 bmp.Dispose();

 g.Dispose();

}


private void timer1_Tick(object sender, EventArgs e) {

 // Делаем снимок экрана через 5 секунд

 Rectangle rect = new Rectangle(0, 0. 240, 240);

 Bitmap bmp = new Bitmap(rect.Width, rect.Height);

 Graphics g = Graphics.FromImage(bmp);

 IntPtr hwnd = GetDesktopWindow();

 IntPtr hdc = GetDC(hwnd);

 BitBlt(g.GetHdc(), 0, 0, rect.Width, rect.Height, hdc, rect.Left,

  rect.Top, SRCCOPY);

 bmp.Save(@"\My Documents\5sec.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

 // Освобождаем ресурсы

 ReleaseDC(hwnd, hdc);

 bmp.Dispose();

 g.Dispose();

 timer1.Enabled = false;

}


private void but5Sec_Click(object sender, EventArgs e) {

 timer1.Enabled = true;

}

Функция ScreenShot позволяет быстро получить участок экрана и сохранить его в графическом файле. В рассмотренном примере внешний вид списка сохраняется в файле listbox.bmp. Для этого достаточно было указать имя файла, объект Graphics и размеры списка ListBox. Для получения снимка экрана пример пришлось несколько усложнить, добавив вызовы функций GetDesktopWindow и GetDC.

Если нужно получить снимок другой программы, то придется воспользоваться таймером. После запуска таймера в распоряжении пользователя будет 5 секунд, чтобы запустить другое приложение. Основная программа будет работать в фоновом режиме и сделает снимок экрана.

Чтобы проверить работу приложения, нужно запустить программу, нажать каждую кнопку, а затем с помощью программы File Explorer найти сохраненные файлы.

ВНИМАНИЕ

Нужно проявлять определенную осторожность при работе с методом Bitmap.Save(). Дело в том, что в Windows Mobile 2003 и более ранних версиях операционных систем библиотека .NET Compact Framework не поддерживает сохранение графических файлов в форматах GIF, JPEG или PNG. Сохранять файлы можно только в формате BMP. Причем во время написания кода редактор не заметит ошибки и позволит запустить программу с неправильным вызовом метода. Однако при вызове метода возникнет исключение NotSupportedException. К счастью, в Windows Mobile 5.0 поддерживаются все четыре графических формата.

Метод Lockbits

В .NET Compact Framework 2.0 появилась ограниченная поддержка метода LockBits, при помощи которого можно манипулировать массивом пикселов изображения. Перечисление ImageLockMode в данном методе позволяет использовать значения ReadWrite, ReadOnly и WriteOnly. А перечисление PixelFormat поддерживает значения, перечисленные в следующем списке:

□ Format16bppRgb555;

□ Format16bppRgb565;

□ Format24bppRgb;

□ Format32bppRgb.

На сайте MSDN можно найти статью «How to: Use LockBits» с примером, в котором создается картинка и меняется интенсивность синих пикселов с помощью метода LockBits. В листинге 6.21 приведен пример, который для большей наглядности пришлось немного изменить.

Листинг 6.21

private Bitmap CreateBitmap(int width, int height) {

 Bitmap bmp = new Bitmap(@"\Windows\msn.gif");

 width = bmp.Size.Width;

 height = bmp.Size.Height;

 Graphics g = Graphics.FromImage(bmp);

 g.Dispose();

 return bmp;

}


protected override void OnPaint(PaintEventArgs e) {

 Bitmap bmp = CreateBitmap(100, 100);

 // Выводим картинку-оригинал

 e.Graphics.DrawImage(bmp, 0, 0);

 MakeMoreBlue(bmp);

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных