C++21键钢琴程序代码QZQ

#include <windows.h>
#include <mmsystem.h>
#include <cstdio>  // 包含 sprintf 所在的头文件

// 全局变量
HMIDIOUT hMidiOut;

// 定义按键时间(毫秒)和力度
const int NOTE_DURATION = 500; // 按键时间为 500 毫秒
const int NOTE_VELOCITY = 127; // 最大力度为 127

// 窗口过程函数
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
    case WM_CREATE: {
        // 打开 MIDI 输出设备
        if (midiOutOpen(&hMidiOut, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR) {
            MessageBox(hwnd, "无法打开 MIDI 输出设备", "错误", MB_OK | MB_ICONERROR);
            return -1;
        }

        // 定义初始位置和间距
        int x = 20;
        int y = 20;
        int spacing = 120;

        // 创建 21 个按钮
        for (int i = 0; i < 21; ++i) {
            char buttonText[20];
            sprintf(buttonText, "音符 %d", i + 1);
            CreateWindow("BUTTON", buttonText, WS_VISIBLE | WS_CHILD, x + i % 3 * spacing, y + i / 3 * 50, 100, 30, hwnd, (HMENU)(i + 1), NULL, NULL);
        }
        break;
    }
    case WM_COMMAND: {
        int note = LOWORD(wParam) + 59; // 音符编号从 60 开始
        // 发送 MIDI 音符开启消息(力度设置为 NOTE_VELOCITY)
        midiOutShortMsg(hMidiOut, 0x90 | (note << 8) | (NOTE_VELOCITY << 16));

        // 等待一段时间,模拟按键按下的时长
        Sleep(NOTE_DURATION);

        // 发送 MIDI 音符关闭消息(力度 0)
        midiOutShortMsg(hMidiOut, 0x80 | (note << 8) | (0 << 16));
        break;
    }
    case WM_DESTROY: {
        // 关闭 MIDI 输出设备
        midiOutClose(hMidiOut);
        PostQuitMessage(0);
        break;
    }
    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

// 主函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
    // 注册窗口类
    WNDCLASS wc = {};
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = "MidiPiano";
    RegisterClass(&wc);

    // 创建窗口
    HWND hwnd = CreateWindow(wc.lpszClassName, "MIDI 钢琴", WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 400, 400, NULL, NULL, hInstance, NULL);

    // 显示窗口
    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    // 消息循环
    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EasySoft易软

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值