Simulating mouse click
#include <windows.h>
using namespace std;
// Forward declaration of the LeftClick function
void LeftClick ( );

// Forward declaration of the MouseMove function
void MouseMove ( int x, int y );

int main()
{
    MouseMove(100, 100);
    LeftClick();
    return 0;
}

// LeftClick function
void LeftClick ( )
{
  INPUT    Input={0};
  // left down
  Input.type      = INPUT_MOUSE;
  Input.mi.dwFlags  = MOUSEEVENTF_LEFTDOWN;
  ::SendInput(1,&Input,sizeof(INPUT));

  // left up
  ::ZeroMemory(&Input,sizeof(INPUT));
  Input.type      = INPUT_MOUSE;
  Input.mi.dwFlags  = MOUSEEVENTF_LEFTUP;
  ::SendInput(1,&Input,sizeof(INPUT));
}

// MouseMove function
void MouseMove (int x, int y )
{
    double fScreenWidth    = ::GetSystemMetrics( SM_CXSCREEN )-1;
    double fScreenHeight  = ::GetSystemMetrics( SM_CYSCREEN )-1;
    double fx = x*(65535.0f/fScreenWidth);
    double fy = y*(65535.0f/fScreenHeight);
    INPUT  Input={0};
    Input.type      = INPUT_MOUSE;
    Input.mi.dwFlags  = MOUSEEVENTF_MOVE|MOUSEEVENTF_ABSOLUTE;
    Input.mi.dx = fx;
    Input.mi.dy = fy;
    ::SendInput(1,&Input,sizeof(INPUT));
}

Hi I was trying to use this code to simulate mouse click but i get "Unable to resolve identifier mi". Im not sure if im missing something. Im using netbeans IDE. Please help im new to cpp. Thanks in advance.

There's nothing wrong with your usage of INPUT::mi, and Visual Studio compiles it just fine (barring an unrelated warning about a narrowing conversion). What OS are you using? If it's Windows 2000 or later (highly likely) then perhaps there's a setting in NetBeans that's restricting features of the Win32 API. I'm just speculating though, as I'm not familiar with using NetBeans as an IDE/compiler. Maybe someone else can weigh in on it.

Im using windows 7 and Netbeans 6.8

Try adding

Input.mi.dwExtraInfo = GetMessageExtraInfo();

and put in some

UINT ret = //sendinput
assert(ret != 0);

That way if you get an assertion failure you can get an error message from it and go from there.

His code compiles fine. I don't know why Netbeans gives you compile time errors.

Alternatively, you can try what I use.. Should be fairly similar:

void ClickMouse(HWND Handle, int X, int Y, bool ClickLeft)
{
    UINT UP = ClickLeft ? WM_LBUTTONUP : WM_RBUTTONUP;
    UINT DOWN = ClickLeft ? WM_LBUTTONDOWN : WM_RBUTTONDOWN;
    WPARAM wParam = ClickLeft ? MK_LBUTTON : MK_RBUTTON;

    PostMessage(Handle, DOWN, wParam, MAKELPARAM(X, Y));
    PostMessage(Handle, UP, wParam, MAKELPARAM(X, Y));
}

I'll leave it to you to write the moving one. It's literally the same (different flags though). Only one PostMessage Required. You can also change PostMessage to SendMessage if you wish.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.