Примеры использования программирования мыши на C / C ++

Опубликовано: 5 Января, 2022

В этой статье мы обсудим некоторые варианты использования программирования с помощью мыши:

Отображение указателя мыши в графическом режиме :

Для отображения указателя мыши сначала включите графический режим с помощью функции initgraph () , если она успешно инициализирована, затем вызывает функцию initMouse (), чтобы проверить, доступна ли мышь или нет. Если функция initMouse () возвращает не равное 0, значит, она вернет ffffh, затем он вызывает функцию showMouse () и отображает курсор в окне консоли в графическом режиме. Ниже приведены используемые функции:

  • initMouse (): используется для инициализации мыши.
  • showMouse (): показывает указатель мыши на экране вывода.

Ниже представлена программа для того же:

C

// C program to display Mouse
// pointer in Graphics Mode
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdio.h>
union REGS in, out;
// Function to display the mouse
// pointer
void showMouse()
{
// Set service AX = 1 for
// displaying mouse
in.x.ax = 1;
int86(0X33, &in, &out);
}
// Function to initialize the mouse
// pointer
int initMouse()
{
// Set service AX = 0 for
// detecting mouse
in.x.ax = 0;
int86(0x33, &in, &out);
return out.x.ax;
}
// Driver Code
void main()
{
int status, gd = DETECT, gm;
clrscr();
initgraph(&gd, &gm,
"C:\TURBOC3\BGI" );
// Get the status of mouse pointer
status = initMouse();
// Check mouse is avilable or not
if (status == 0)
printf ( "Mouse support not"
" available. " );
else {
printf ( "Display mouse" );
showMouse();
}
getch();
// Close the graphics
closegraph();
}

C ++

// C++ program to display Mouse
// pointer in Graphics Mode
#include <bits/stdc++.h>
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdio.h>
using namespace std;
union REGS in, out;
// Function to display the mouse
// pointer
void showMouse()
{
// Set service AX = 1 for
// displaying mouse
in.x.ax = 1;
int86(0X33, &in, &out);
}
// Function to initialize the mouse
// pointer
int initMouse()
{
// Set service AX = 0 for
// detecting mouse
in.x.ax = 0;
int86(0x33, &in, &out);
return out.x.ax;
}
// Driver Code
void main()
{
int status, gd = DETECT, gm;
clrscr();
initgraph(&gd, &gm, "C:\TURBOC3\BGI" );
// Get the status of mouse pointer
status = initMouse();
// Check if mouse is avilable or not
if (status == 0)
cout << "Mouse support not"
<< " available. " ;
else {
cout << "Display mouse" ;
showMouse();
}
getch();
// Close the graphics
closegraph();
}

Выход:

Скрыть указатель мыши :

Чтобы скрыть указатель мыши, сначала проверьте состояние мыши, если она доступна, затем просто элемент управления войдет в цикл для задержки создания цикла 500 миллисекунд, затем появится мышь, затем исчезнет через 500 миллисекунд и снова появится через 500 миллисекунд. Эта последовательность будет продолжаться до тех пор, пока цикл не закончится. Функция задержки была использована, чтобы показать вам влияние функции hidemouse () .

  • initmouse (): используйте для инициализации мыши.
  • showmouse (): показывает указатель мыши на экране вывода.
  • hidemouse (): скрывает указатель мыши

Ниже представлена программа для того же:

C

// C program for hiding Mouse Pointer
#include <conio.h>
#include <dos.h>
#include <graphics.h>
union REGS in, out;
// Function to initialize the mouse
// pointer using graphics
int initMouse()
{
in.x.ax = 0;
int86(0X33, &in, &out);
return out.x.ax;
}
// Function to display the mouse
// pointer using graphics
void showMouse()
{
in.x.ax = 1;
int86(0X33, &in, &out);
}
// Function to hide the mouse
// pointer using graphics
void hideMouse()
{
// Set AX=2 to hide mouse
in.x.ax = 2;
int86(0X33, &in, &out);
}
// Driver Code
void main()
{
int status, i, gd = DETECT, gm;
// Initialize graphics
initgraph(&gd, &gm, "C:\TURBOC3\BGI" );
// Get the status of the mouse
status = initMouse();
// Check if mouse is available or not
if (status == 0)
printf ( "Mouse support "
"not available. " );
else {
for (i = 0; i <= 10; i++) {
// Pause execution for .5 sec
delay(500);
showMouse();
delay(500);
hideMouse();
}
}
getch();
// Close the graphics
closegraph();
}

C ++

// C++ program for hiding Mouse Pointer
#include <bits/stdc++.h>
#include <conio.h>
#include <dos.h>
#include <graphics.h>
using namespace std;
union REGS in, out;
// Function to initialize the mouse
// pointer using graphics
int initMouse()
{
in.x.ax = 0;
int86(0X33, &in, &out);
return out.x.ax;
}
// Function to display the mouse
// pointer using graphics
void showMouse()
{
in.x.ax = 1;
int86(0X33, &in, &out);
}
// Function to hide the mouse
// pointer using graphics
void hideMouse()
{
// Set AX=2 to hide mouse
in.x.ax = 2;
int86(0X33, &in, &out);
}
// Driver Code
void main()
{
int status, i, gd = DETECT, gm;
// Initialize graphics
initgraph(&gd, &gm, "C:\TURBOC3\BGI" );
// Get the status of the mouse
status = initMouse();
// Check if mouse is available or not
if (status == 0)
cout << "Mouse support "
<< "not available. " ;
else {
for (i = 0; i <= 10; i++) {
// Pause execution for .5 sec
delay(500);
showMouse();
delay(500);
hideMouse();
}
}
getch();
// Close the graphics
closegraph();
}

Выход:

Определите текущее положение мыши и нажатую кнопку :

В этой программе печатается текущее положение мыши, а также какая клавиша мыши в каком месте нажата, используя следующие функции:

  • initmouse (): используйте для инициализации мыши.
  • showmouse (): показывает курсор мыши на экране вывода.
  • getmouseposition (): выбирает координату мыши и нажатую клавишу в регистрах BX , CX , DX соответственно.
    • Если BX = 1 нажата левая клавиша
    • Если BX = 2 Нажата правая клавиша.
    • Если BX = 3 нажата центральная кнопка
    • CX = Координата X мыши
    • DX = Координата Y мыши

Ниже представлена программа для того же:

C

// C program to determine the current
// mouse position and button clicked
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdio.h>
union REGS in, out;
// Function to initialize the mouse
// pointer using graphics
int initMouse()
{
in.x.ax = 0;
int86(0X33, &in, &out);
return out.x.ax;
}
// Function to display the mouse
// pointer using graphics
void showMouse()
{
in.x.ax = 1;
int86(0X33, &in, &out);
}
// Function to get the current clicked
// mouse position on the screen
void getMousePosition( int * click,
int * x, int * y)
{
in.x.ax = 3;
int86(0X33, &in, &out);
// Get the coordinates
*click = out.x.bx;
// Update the x and y coordinates
*x = out.x.cx;
*y = out.x.dx;
}
// Driver Code
void main()
{
int status, i, gd = DETECT, gm;
// Initialize graphics
initgraph(&gd, &gm, "C:\TURBOC3\BGI" );
// Get the status of the mouse
status = initMouse();
// Check if mouse is available or not
if (status == 0)
printf ( "Mouse support "
"not available. " );
else {
showMouse();
// Get the current mouse position
getMousePosition(&click, &x, &y);
while (!kbhit()) {
getMousePosition(&click, &x, &y);
gotoxy(1, 1);
printf ( "X = %d, Y = %d" , x, y);
if (click == 1)
printf ( " Left click at "
"position = %d, %d " ,
x, y);
if (click == 2)
printf ( " Right click at "
"position = %d, %d " ,
x, y);
}
}
getch();
// Close the graphics
closegraph();
}

C ++

// C program to determine the current
// mouse position and button clicked
#include <bits/stdc++.h>
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdio.h>
using namespace std;
union REGS in, out;
// Function to initialize the mouse
// pointer using graphics
int initMouse()
{
in.x.ax = 0;
int86(0X33, &in, &out);
return out.x.ax;
}
// Function to display the mouse
// pointer using graphics
void showMouse()
{
in.x.ax = 1;
int86(0X33, &in, &out);
}
// Function to get the current clicked
// mouse position on the screen
void getMousePosition( int * click,
int * x, int * y)
{
in.x.ax = 3;
int86(0X33, &in, &out);
// Get the coordinates
*click = out.x.bx;
// Update the x and y coordinates
*x = out.x.cx;
*y = out.x.dx;
}
// Driver Code
void main()
{
int status, i, gd = DETECT, gm;
// Initialize graphics
initgraph(&gd, &gm, "C:\TURBOC3\BGI" );
// Get the status of the mouse
status = initMouse();
// Check if mouse is available or not
if (status == 0)
printf ( "Mouse support "
"not available. " );
else {
showMouse();
// Get the current mouse position
getMousePosition(&click, &x, &y);
while (!kbhit()) {
getMousePosition(&click, &x, &y);
gotoxy(1, 1);
printf ( "X = %d, Y = %d" , x, y);
if (click == 1)
cout << " Left click at "
<< "position = "
<< x << ", " << y;
if (click == 2)
cout << " Right click at "
<< "position = "
<< x << ", " << y;
}
}
getch();
// Close the graphics
closegraph();
}

Выход:

Хотите учиться на лучших видео и практических задачах, ознакомьтесь с Базовым курсом C для базового и продвинутого C.