DWQA QuestionsCategory: ServerHow to use QT to simulate mouse click?
Sagahime asked 2 months ago

QT entry, windows development entry player.
I want to use QT to realize a function of simulating mouse click (Windows platform). Specifically, it is as follows: first obtain the handle of a window with a specific name, and then simulate clicking on a specific position of the window. It is required that the window can not be displayed in the front of the desktop (that is, it is a virtual click, rather than moving the mouse pointer to that position and then clicking)
According to the online content, I wrote a simple slot function as follows:

void MainWindow::clickTest()
{
    HWnd hwndgamewindow =:: findwindow (null, l "window name");
    gameWindow=QWidget::find((WId)hwndGameWindow);
    qDebug()<<(QString)(gameWindow->windowTitle());
    QPoint *pos=new QPoint(112,83);
    QMouseEvent *clickEvent=new QMouseEvent(QEvent::MouseButtonPress,*pos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
    QApplication::sendEvent(gameWindow,clickEvent);
}

When I trigger this slot function, the system reports a segment error and the program exits forcibly.
May I ask you what’s wrong? I would appreciate it if you could give me another way to realize the functions I described.,QWidget::find()Only applies to windows created by QT current process, notFindWindow()The query is the top-level window under the whole operating system.
Therefore, if you pass a window ID created by a non QT current process toQWidget::find(), it will return null.
To send messages to the windows of other processes, the general process is as follows

  1. useFindWindowFind the top-level window of the target window
  2. In the top-level window, useFindWindowExFind target window
  3. Construct the message to be sent
  4. useSendMessageorPostMessageSend message to target window

,Step by step to see if the previous steps find a null pointer or something

2 Answers
Li Yi answered 2 months ago

QWidget::find()Only applies to windows created by QT current process, notFindWindow()The query is the top-level window under the whole operating system.
Therefore, if you pass a window ID created by a non QT current process toQWidget::find(), it will return null.
To send messages to the windows of other processes, the general process is as follows

  1. useFindWindowFind the top-level window of the target window
  2. In the top-level window, useFindWindowExFind target window
  3. Construct the message to be sent
  4. useSendMessageorPostMessageSend message to target window
Sagahime replied 2 months ago

I see. I’ve been taught.

Cthulhu answered 2 months ago

Step by step to see if the previous steps find a null pointer or something

Sagahime replied 2 months ago

The “gamewindow” variable on the second line of the function is a null pointer. I just want to ask why it is a null pointer.. (the window handle returned by the findwindow function is valid)

Cthulhu replied 2 months ago

Probe with vs Spy + +