/*
    メモリ上のサウンドイメージ再生

       1999/10/ 4  宍戸 輝光
*/

#include <windows.h>

LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
HINSTANCE hInst;
HWND hwnd;
LPVOID lpSound;
BOOL bLoad=FALSE;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow){

	MSG  msg;
	WNDCLASSEX  wndclass ;

	hInst=hInstance; /* プロセスのハンドルを保存 */

	wndclass.cbSize        = sizeof(wndclass);
	wndclass.style         = CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc   = WndProc;
	wndclass.cbClsExtra    = 0;
	wndclass.cbWndExtra    = 0;
	wndclass.hInstance     = hInstance;
	wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION);
	wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wndclass.lpszMenuName  = NULL;
	wndclass.lpszClassName = "CWindow";
	wndclass.hIconSm       = LoadIcon (NULL, IDI_APPLICATION);

	RegisterClassEx (&wndclass);

	hwnd = CreateWindow ("CWindow","サウンド再生",
	  WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,240,240,
      NULL,NULL,hInstance,NULL);

	ShowWindow(hwnd,iCmdShow); /* ウインドウを表示 */
	UpdateWindow(hwnd);        /* 再描画 */

	while (GetMessage (&msg,NULL,0,0)) { /* メッセージループ */

		TranslateMessage(&msg);
		DispatchMessage(&msg);

	}

	return msg.wParam ;

}

LRESULT CALLBACK WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) {

	static HWND hwBtn;
	HANDLE fh;
	HDROP hDrop;
	static BYTE lpszFn[256];
	DWORD dummy;

	switch (iMsg) {

		case WM_CREATE:

			/* ボタン作成 */
			hwBtn=CreateWindow("Button","再生",
				WS_CHILD | WS_VISIBLE,8,8,80,32,hwnd,
				(HMENU)0,hInst,NULL);

			EnableWindow(hwBtn,FALSE);

			DragAcceptFiles(hwnd,TRUE); /* ドラッグ&ドロップ受入 */

			break;

		case WM_COMMAND:

			sndPlaySound(lpSound,SND_ASYNC|SND_MEMORY); /* 再生 */

			break;

		case WM_DROPFILES: /* ファイルがドロップされた時の処理 */

			hDrop=(HDROP)wParam; /* HDROPを取得 */
			DragQueryFile(hDrop,0,lpszFn,256); /* ファイル名を取得 */

			if (bLoad)
				GlobalFree(lpSound);

			fh=CreateFile(lpszFn,GENERIC_READ,0,NULL,OPEN_EXISTING,
			  FILE_ATTRIBUTE_NORMAL,NULL); /* ファイルオープン */

			lpSound=GlobalAlloc(GPTR,GetFileSize(fh,NULL)); /* バッファ確保 */

			ReadFile(fh,lpSound,GetFileSize(fh,NULL),&dummy,NULL);

			CloseHandle(fh);
			EnableWindow(hwBtn,TRUE);

			SetWindowText(hwnd,lpszFn);
			bLoad=TRUE;

			DragFinish(hDrop); /* ドラッグ&ドロップ終了処理 */

			break;

		case WM_DESTROY :

			if (bLoad)
				GlobalFree(lpSound);

			PostQuitMessage(0);

			break;

	}

	return DefWindowProc (hwnd, iMsg, wParam, lParam);

}