1. 程式人生 > >SDL之滑鼠訊息

SDL之滑鼠訊息

在SDL中有一個結構體SDL_Event存放SDL存放事件。將該結構體的地址傳入SDL_PollEvent,便可以知道發生了什麼事件。

#include "SDL.h"
#include "SDL_image.h"
int main(int argc, char* argv[])
{

	SDL_Init(SDL_INIT_VIDEO);
	SDL_Window* window = SDL_CreateWindow("Tutorial", 100, 100,
	600, 600, SDL_WINDOW_SHOWN);
	SDL_Surface* surface = SDL_GetWindowSurface(window);
	SDL_Surface* picture1 = IMG_Load("C:\\Users\\xxxx\\Desktop\\1.jpg");
	SDL_Surface* picture2 = IMG_Load("C:\\Users\\xxxx\\Desktop\\2.jpg");
	SDL_Event event;
	
	bool quit = false;
	SDL_Rect rect;
	rect.x = 0;
	rect.y = 0;
	//事件驅動
	while (quit == false)
	{
		while (SDL_PollEvent(&event))
		{
			//點選關閉按鈕事件
			if (SDL_QUIT == event.type)
			{
				printf("hello world");
				quit = true;
				
			}else if(SDL_MOUSEBUTTONDOWN == event.type)
			{
				//滑鼠按下事件
				printf("click");
				if (SDL_BUTTON_LEFT == event.button.button)
				{
					printf("左鍵按下");
					SDL_BlitSurface(picture1,NULL, surface,NULL);
					SDL_UpdateWindowSurface(window);
				}
				else if (SDL_BUTTON_RIGHT == event.button.button)
				{
					printf("右鍵按下");
					SDL_BlitSurface(picture2, NULL, surface, NULL);
					SDL_UpdateWindowSurface(window);
				}
			}
			else if (SDL_KEYDOWN == event.type)
			{
				//鍵盤按下事件
				printf("keybpard");
				SDL_FillRect(surface, NULL, 0);
				if (SDLK_UP == event.key.keysym.sym)
				{
					printf("上被點選");
					SDL_BlitSurface(picture1, NULL, surface, &rect);
				}
				else if (SDLK_LEFT == event.key.keysym.sym)
				{
					rect.x -= 10;
					SDL_BlitSurface(picture1, NULL, surface, &rect);
				}
				else if (SDLK_RIGHT == event.key.keysym.sym)
				{
					rect.x += 10;
					SDL_BlitSurface(picture1, NULL, surface, &rect);
				}
				else if (SDLK_DOWN == event.key.keysym.sym)
				{
					rect.y += 10;
					SDL_BlitSurface(picture1, NULL, surface, &rect);
				}
				SDL_UpdateWindowSurface(window);
			}
		}
	}

	SDL_FreeSurface(surface);
	SDL_FreeSurface(picture1);
	SDL_FreeSurface(picture2);
	SDL_DestroyWindow(window);
	SDL_Quit();
}