← Back to C Course | Chapter 13: Graphics | Lesson 8 of 10

C Mouse Input

Detecting Mouse Support

On the classic DOS-era BGI setup, the mouse isn't accessed through a modern event API but through low-level interrupts: populating a union REGS structure and issuing interrupt 0x33 with the appropriate function number is what initializes and communicates with the mouse driver.

Example: Detecting Mouse Support

c
#include <dos.h>
int main() {
	union REGS in, out;
	in.x.ax = 0;
	int86(0x33, &in, &out);
	return 0;
}

Getting Mouse Coordinates

Requesting mouse status with the interrupt function code for 'get position' (operation value 3) returns the cursor's current X and Y screen coordinates in the interrupt's output registers, which your program then reads out of that same union REGS structure.

Example: Getting Mouse Coordinates

c
#include <dos.h>
int main() {
	union REGS in, out;
	in.x.ax = 3;
	int86(0x33, &in, &out);
	int x = out.x.cx;
	int y = out.x.dx;
	return 0;
}

Handling Mouse Clicks

Mouse button state is reported through a value in the interrupt's output register after the status call: a value of 1 typically indicates the left button is pressed and 2 indicates the right button, letting you branch your program's behavior based on which button (if any) is down.

Example: Handling Mouse Clicks

c
#include <dos.h>
int main() {
	union REGS in, out;
	in.x.ax = 3;
	int86(0x33, &in, &out);
	if (out.x.bx == 1) {
		// left button pressed
	}
	return 0;
}

Creating Interactive Buttons

To build a clickable button, you define a rectangular region in screen coordinates representing that button's bounds, then on every detected click compare the reported mouse coordinates against that rectangle's edges to decide whether the click landed inside it.

Example: Creating Interactive Buttons

c
#include <dos.h>
int main() {
	union REGS in, out;
	in.x.ax = 3;
	int86(0x33, &in, &out);
	int x = out.x.cx, y = out.x.dx;
	if (x >= 50 && x <= 150 && y >= 50 && y <= 100) {
		// click inside button bounds
	}
	return 0;
}

Hiding the Mouse Cursor

Before your program exits (or whenever you want the cursor visually hidden), calling the mouse interrupt with operation value 2 hides the mouse cursor, which matters because leaving it visible while your program tears down its graphics mode can leave a stray cursor artifact on screen.

Example: Hiding the Mouse Cursor

c
#include <dos.h>
int main() {
	union REGS in, out;
	in.x.ax = 2;
	int86(0x33, &in, &out);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.