做一个winform钢琴项目,有代码
时间: 2023-08-01 08:06:13 浏览: 45
好的,以下是一个简单的Winform钢琴项目的代码:
首先,你需要在工具箱中添加一个Picturebox控件,用于显示钢琴键盘。然后,你可以使用Graphics类绘制钢琴键盘的图像。在KeyDown和KeyUp事件处理程序中,你可以检测按下或释放的按键,并播放相应的声音。
```
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PianoProject
{
public partial class Form1 : Form
{
private bool[] keyDown = new bool[13]; // 数组存储钢琴键是否按下
private SoundPlayer[] soundPlayers = new SoundPlayer[13]; // 每个键对应的声音播放器
public Form1()
{
InitializeComponent();
InitSoundPlayers(); // 初始化声音播放器
InitPianoKeys(); // 绘制钢琴键盘
}
private void InitSoundPlayers() // 初始化声音播放器
{
for (int i = 0; i < 13; i++)
{
soundPlayers[i] = new SoundPlayer("sound" + (i + 1) + ".wav");
}
}
private void InitPianoKeys() // 绘制钢琴键盘
{
Graphics g = pictureBox1.CreateGraphics();
g.Clear(Color.White);
int x = 0;
int y = 0;
int width = 40;
int height = 150;
for (int i = 0; i < 13; i++)
{
if (i == 1 || i == 3 || i == 6 || i == 8 || i == 10)
{
x += width;
}
else
{
x += (i == 0) ? 0 : width;
}
if (i == 1 || i == 3 || i == 6 || i == 8 || i == 10)
{
g.FillRectangle(Brushes.Black, x - width / 2, y, width, height / 2);
}
else
{
g.FillRectangle(Brushes.White, x, y, width, height);
}
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e) // 处理按键按下事件
{
switch (e.KeyCode)
{
case Keys.A:
PlaySound(0);
break;
case Keys.S:
PlaySound(1);
break;
case Keys.D:
PlaySound(2);
break;
case Keys.F:
PlaySound(3);
break;
case Keys.G:
PlaySound(4);
break;
case Keys.H:
PlaySound(5);
break;
case Keys.J:
PlaySound(6);
break;
case Keys.K:
PlaySound(7);
break;
case Keys.L:
PlaySound(8);
break;
case Keys.OemSemicolon:
PlaySound(9);
break;
case Keys.OemQuotes:
PlaySound(10);
break;
case Keys.OemPipe:
PlaySound(11);
break;
case Keys.OemBackslash:
PlaySound(12);
break;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e) // 处理按键释放事件
{
switch (e.KeyCode)
{
case Keys.A:
StopSound(0);
break;
case Keys.S:
StopSound(1);
break;
case Keys.D:
StopSound(2);
break;
case Keys.F:
StopSound(3);
break;
case Keys.G:
StopSound(4);
break;
case Keys.H:
StopSound(5);
break;
case Keys.J:
StopSound(6);
break;
case Keys.K:
StopSound(7);
break;
case Keys.L:
StopSound(8);
break;
case Keys.OemSemicolon:
StopSound(9);
break;
case Keys.OemQuotes:
StopSound(10);
break;
case Keys.OemPipe:
StopSound(11);
break;
case Keys.OemBackslash:
StopSound(12);
break;
}
}
private void PlaySound(int index) // 播放声音
{
if (!keyDown[index])
{
soundPlayers[index].Play();
keyDown[index] = true;
}
}
private void StopSound(int index) // 停止声音
{
if (keyDown[index])
{
soundPlayers[index].Stop();
keyDown[index] = false;
}
}
}
}
```
希望这个代码可以帮助你制作出一个Winform钢琴项目。