grig_p
grig_pOct. 31, 2017, 4:27 a.m.

Qt - WinAPI. How to show a running application on top of your application

There was at me somehow a problem to operate applications - the services written on Qt, from application - a kernel written also on Qt. And, if the service application is not running, then it should be started, and if it is running, its window should be brought to the foreground. QProcess is used to invoke applications.


It looks like this.
Process creation:

QProcess *app;
bool pw = false;
...
void createProcess()
{
    app = new QProcess(this);
    app->setProgram("MyProgram.exe");
    app->setArguments(QStringList() << "arg1" << "arg2");
    connect(app, SIGNAL(started()), this, SLOT(onProcStarted()));
    connect(app, SIGNAL(finished()), this, SLOT(onProcFinished()));
}

Call:

if (!pw)
{  //If the application is not running, then run it
    app->start(QIODevice::ReadOnly);
} 
else 
{   // If it's running, we'll show it from the top
    HWND hWnd = FindWindow(nullptr, L"Заголовок главного окна");
    if (hWnd > 0){
        ShowWindow(hWnd, SW_RESTORE);
        SetForegroundWindow(hWnd);
    }
}

Slots:

void onProcStarted()
{
    pw = true;
}

void onProcFinished(int)
{
    pw = false;
}

As I understood, QProcess does not know how to bring to the forefront the window of the running process. Therefore, I have to resort to WinApi. But showing the window in this form does not work. Moreover, the FindWindow function does not work. It does not return the correct handle. Although there is a window.

The solution was related to the direct indication of the encoding as follows:

QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QString s = codec->toUnicode("Заголовок главного окна");
LPCWSTR lps = (LPCWSTR)s.utf16();

HWND hWnd = FindWindow(nullptr, lps);
if (hWnd > 0) {
    ShowWindow(hWnd, SW_RESTORE);
    SetForegroundWindow(hWnd);
}
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Юрий
  • June 16, 2018, 11:19 a.m.

А можно по ID процесса  выводить на передний план окно?

myProcess->processId();
Evgenii Legotckoi
  • June 18, 2018, 3 a.m.

Если зарыться в API системы, то, думаю, что можно, тут тоже использовался WinAPI.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Ua

Qt - Test 001. Signals and slots

  • Result:84points,
  • Rating points4
Ua

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
ОК

Qt - Test 001. Signals and slots

  • Result:47points,
  • Rating points-6
Last comments
ИМ
Игорь МаксимовNov. 23, 2024, 12:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 2:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
NW
Nayo WaiJan. 30, 2025, 10:22 p.m.
не запускается компьютер!!! Не запускается компьютер (точнее работает блок , но сам монитор вообще жесть)В общем я ничего с интернета не скачивала в последнее время. На компе никаких левых пр…
n
nklyJan. 3, 2025, 3:52 p.m.
Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
M
MarselAug. 17, 2023, 2:26 a.m.
OAuth2.0 через VK, получение email Спасибо большое за помощь и простите за то что отнял время своей невнимательностью.
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 3:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 7:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]

Follow us in social networks