Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
28
Добавлен:
23.11.2019
Размер:
2.4 Mб
Скачать

Воспроизведение звука в приложении

Для добавления звука в приложение можно использовать пространство имен System.Media. Воспроизведение системных звуков в приложении, например стандартного звукового сигнала, осуществляется с помощью System.Media.SystemSounds.Beep.Play();.

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

Воспроизведение аудиофайла

  1. В меню Файл выберите команду Создать проект.

  2. В диалоговом окне Создание проекта выберите Приложение Windows Forms, а затем нажмите кнопку ОК.

Откроется новый проект Windows Forms.

  1. Из панели элементов перетащите в форму элемент управления Button.

  2. Дважды щелкните кнопку, чтобы создать обработчик событий Click по умолчанию, и добавьте следующий код. Этот код отображает диалоговое окно открытия файла и передает результаты в метод с именем playSound, который будет создан на следующем этапе.

    OpenFileDialog dialog = new OpenFileDialog();

    dialog.Filter = "Audio Files (.wav)|*.wav";

    if(dialog.ShowDialog() == DialogResult.OK)

    {

    string path = dialog.FileName;

    playSound(path);

    }

  3. Добавьте следующий код метода под27 обработчик событий button1_Click.

----

  1. Нажмите клавишу F5 для выполнения кода.

  2. Нажмите кнопку и выберите аудиофайл. После загрузки файла начнется воспроизведение звука.

Creating and Using Bitmaps and Icons

This topic is designed to help you find code that demonstrates how to perform common bitmap and icon programming tasks by using Visual C# Express Edition.

How to: Create a Bitmap at Run Time

This example creates and fills a Bitmap object, and then displays it in a PictureBox control. To run this example, create a Windows Forms Application project and drag a PictureBox control from the Toolbox to the form. The size of the Picture Box is not important; it will resize automatically to fit the bitmap. Paste the CreateBitmap method into the Form1 class, and call it from the Form1_Load event-handler method.

Example

void CreateBitmap()

{

const int colWidth = 10;

const int rowHeight = 10;

System.Drawing.Bitmap checks = new System.Drawing.Bitmap(

colWidth * 10, rowHeight * 10);

// The checkerboard consists of 10 rows and 10 columns.

// Each square in the checkerboard is 10 x 10 pixels.

// The nested for loops are used to calculate the position

// of each square on the bitmap surface, and to set the

// pixels to black or white.

// The two outer loops iterate through

// each square in the bitmap surface.

for (int columns = 0; columns < 10; columns++)

{

for (int rows = 0; rows < 10; rows++)

{

// Determine whether the current sqaure

// should be black or white.

Color color;

if (columns % 2 == 0)

color = rows % 2 == 0 ? Color.Black : Color.White;

else

color = rows % 2 == 0 ? Color.White : Color.Black;

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]