Esempio n. 1
0
void Sys_SetHighDPIMode(void)
{
  /* For Vista, Win7 and Win8 */
  BOOL(WINAPI * SetProcessDPIAware)(void) = NULL;

  /* Win8.1 and later */
  HRESULT(WINAPI * SetProcessDpiAwareness)
  (YQ2_PROCESS_DPI_AWARENESS dpiAwareness) = NULL;

  HINSTANCE userDLL = LoadLibrary("USER32.DLL");

  if (userDLL) {
    SetProcessDPIAware = (BOOL(WINAPI *)(void)) GetProcAddress(userDLL, "SetProcessDPIAware");
  }

  HINSTANCE shcoreDLL = LoadLibrary("SHCORE.DLL");

  if (shcoreDLL) {
    SetProcessDpiAwareness =
        (HRESULT(WINAPI *)(YQ2_PROCESS_DPI_AWARENESS)) GetProcAddress(shcoreDLL, "SetProcessDpiAwareness");
  }

  if (SetProcessDpiAwareness) {
    SetProcessDpiAwareness(YQ2_PROCESS_PER_MONITOR_DPI_AWARE);
  } else if (SetProcessDPIAware) {
    SetProcessDPIAware();
  }
}
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR /*lpCmdLine*/, int nCmdShow)
{
    SetProcessDPIAware();
    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, g_szTitle, ARRAYSIZE(g_szTitle));
    LoadString(hInstance, IDC_LINE, g_szWindowClass, ARRAYSIZE(g_szWindowClass));
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (InitInstance(hInstance, nCmdShow)) 
    {
        HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LINE));

        // Main message loop:
        MSG message;
        while (GetMessage(&message, NULL, 0, 0)) 
        {
            if (!TranslateAccelerator(message.hwnd, hAccelTable, &message)) 
            {
                TranslateMessage(&message);
                DispatchMessage(&message);
            }
        }
    }
    return 0;
}
Esempio n. 3
0
int _glfwPlatformInit(void)
{
    // To make SetForegroundWindow work as we want, we need to fiddle
    // with the FOREGROUNDLOCKTIMEOUT system setting (we do this as early
    // as possible in the hope of still being the foreground process)
    SystemParametersInfoW(SPI_GETFOREGROUNDLOCKTIMEOUT, 0,
                          &_glfw.win32.foregroundLockTimeout, 0);
    SystemParametersInfoW(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, UIntToPtr(0),
                          SPIF_SENDCHANGE);

    if (!loadLibraries())
        return GLFW_FALSE;

    createKeyTables();
    _glfwUpdateKeyNamesWin32();

    if (_glfwIsWindows10CreatorsUpdateOrGreaterWin32())
        SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
    else if (IsWindows8Point1OrGreater())
        SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
    else if (IsWindowsVistaOrGreater())
        SetProcessDPIAware();

    if (!_glfwRegisterWindowClassWin32())
        return GLFW_FALSE;

    if (!createHelperWindow())
        return GLFW_FALSE;

    _glfwInitTimerWin32();
    _glfwInitJoysticksWin32();

    _glfwPollMonitorsWin32();
    return GLFW_TRUE;
}
Esempio n. 4
0
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }
   SetProcessDPIAware();

   gHwnd = hWnd;

   gVsyncWin = new VSyncWin();
   gVsyncWin->VSyncInit();

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

  

   return TRUE;
}
Esempio n. 5
0
int main(int argc, char** argv)
{
//    QApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
    SetProcessDPIAware();

    QApplication qapp(argc, argv);

    int x = QApplication::desktop()->physicalDpiX();
    int y = QApplication::desktop()->physicalDpiY();
    double scaleX = 284.0/double(x);
    double scaleY = 285.0/double(y);

    std::cout << x << " " << y << std::endl;
    std::cout << QApplication::desktop()->logicalDpiX() << " " << QApplication::desktop()->logicalDpiY() << std::endl;



    QMainWindow window;
    QtOSGWidget* widget = new QtOSGWidget(1, 1, &window);
    window.setCentralWidget(widget);
    window.show();

    std::cout << scaleX << " " << scaleY << std::endl;
//    std::cout << pr << " " << ps << std::endl;

    return qapp.exec();
}
Esempio n. 6
0
// Based on the example provided by Eric Wasylishen
// https://discourse.libsdl.org/t/sdl-getdesktopdisplaymode-resolution-reported-in-windows-10-when-using-app-scaling/22389
void WIN_InitDPI()
{
	void* userDLL;
	void* shcoreDLL;

	shcoreDLL = SDL_LoadObject("SHCORE.DLL");
	if (shcoreDLL)
	{
		SetProcessDpiAwareness = (HRESULT(WINAPI *)(PROCESS_DPI_AWARENESS)) SDL_LoadFunction(shcoreDLL, "SetProcessDpiAwareness");
	}

	if (SetProcessDpiAwareness)
	{
		/* Try Windows 8.1+ version */
		HRESULT result = SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
		return;
	}

	userDLL = SDL_LoadObject("USER32.DLL");
	if (userDLL)
	{
		SetProcessDPIAware = (BOOL(WINAPI *)(void)) SDL_LoadFunction(userDLL, "SetProcessDPIAware");
	}

	if (SetProcessDPIAware)
	{
		/* Try Vista - Windows 8 version.
		This has a constant scale factor for all monitors.
		*/
		BOOL success = SetProcessDPIAware();
	}
}
Esempio n. 7
0
/******************************************************************
 *
 *  Initialize
 *
 *  This method is used to create and display the application
 *  window, and provides a convenient place to create any device
 *  independent resources that will be required.
 *
 ******************************************************************/
BOOL Initialize()
{
    WNDCLASSEX wcex;
    ATOM atom;
    LARGE_INTEGER freq;

    // Prepare the high resolution performance counter.
    SetThreadAffinityMask(GetCurrentThread(), 0);
    if (!QueryPerformanceFrequency(&freq)) {
        return FALSE;
    }
    glFrequency = freq.QuadPart;

    // Initialize the result array.
    gTimerRec[0].lElapsedMin = gTimerRec[1].lElapsedMin = MAXLONGLONG;


    // Register window class
    wcex.cbSize        = sizeof(WNDCLASSEX);
    wcex.style         = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc   = WndProc;
    wcex.cbClsExtra    = 0;
    wcex.cbWndExtra    = sizeof(LONG_PTR);
    wcex.hInstance     = ghInstance;
    wcex.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wcex.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = NULL;
    wcex.lpszMenuName  = NULL;
    wcex.lpszClassName = TEXT("TimerApp");
    wcex.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

    atom = RegisterClassEx(&wcex);
    if (atom == 0) {
        return FALSE;
    }

    SetProcessDPIAware();

    // Create & prepare the main window
    ghwnd = CreateWindow(
        (LPCTSTR)atom,
        TEXT("Coalescable Timer Sample"),
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        600,
        400,
        NULL,
        NULL,
        ghInstance,
        NULL);

    if (ghwnd == NULL) {
        return FALSE;
    }

    ShowWindow(ghwnd, SW_SHOWNORMAL);
    UpdateWindow(ghwnd);

    return TRUE;
}
Esempio n. 8
0
static int ShowDialog(int* delayMode)
{
    const static TASKDIALOG_BUTTON buttons[] = {
        { 100, L"&Start taking screenshots" },
        { 101, L"E&xit" },
    };

    const static TASKDIALOG_BUTTON radioButtons[] = {
        {   102, L"Wait for &delay\n"
            "Take a screenshot five seconds after this dialog disappears, then exit."
        },
        {   103, L"Wait for &key press\n"
            "Hide this dialog and wait for Ctrl+PrtScr to be pressed."
        },
    };

    const static TASKDIALOGCONFIG dialog = {
        .cbSize = sizeof(TASKDIALOGCONFIG),
        .hInstance = HINST_THISCOMPONENT,
        .dwFlags = TDF_SIZE_TO_CONTENT,
        .pszWindowTitle = L"Clearshot",
        .pszMainIcon = MAKEINTRESOURCE(101),
        .pszContent = L"Choose when the screenshot will be taken:",

        .cButtons = 2,
        .pButtons = buttons,
        .nDefaultButton = 100,

        .cRadioButtons = 2,
        .pRadioButtons = radioButtons,
        .nDefaultRadioButton = 102,
    };

    int result, option;

    TaskDialogIndirect(&dialog, &result, &option, NULL);

    *delayMode = (option == 102);
    return (result == 100);
}

int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, int cmdShow)
{
    SetProcessDPIAware();

    int delay,
        left = GetSystemMetrics(SM_XVIRTUALSCREEN),
        top = GetSystemMetrics(SM_YVIRTUALSCREEN),
        width = GetSystemMetrics(SM_CXVIRTUALSCREEN),
        height = GetSystemMetrics(SM_CYVIRTUALSCREEN);

    if (!ShowDialog(&delay))
        return 0;

    ShootAndSave(left, top, width, height);

    return 0;
}
// Program entry point
int APIENTRY wWinMain(_In_ HINSTANCE hinst, _In_opt_ HINSTANCE /*hinstPrev*/, _In_ LPWSTR /*lpCmdLine*/, _In_ int /*nCmdShow*/)
{
    // Initialize localized global strings
    if (LoadString(hinst, IDS_WINDOW, g_windowClass, MAX_LOADSTRING) == 0)
    {
        fprintf(stderr, "LoadString() failed with error code %u.\n", GetLastError());
        return -1;
    }
    if (LoadString(hinst, IDS_CAPTION, g_mainTitle, MAX_LOADSTRING) == 0)
    {
        fprintf(stderr, "LoadString() failed with error code %u.\n", GetLastError());
        return -1;
    }
    if (LoadString(hinst, IDS_TOUCHHITTESTING_ON, g_touchHitTestingOnText, MAX_LOADSTRING) == 0)
    {
        fprintf(stderr, "LoadString() failed with error code %u.\n", GetLastError());
        return -1;
    }
    if (LoadString(hinst, IDS_TOUCHHITTESTING_OFF, g_touchHitTestingOffText, MAX_LOADSTRING) == 0)
    {
        fprintf(stderr, "LoadString() failed with error code %u.\n", GetLastError());
        return -1;
    }
    if (LoadString(hinst, IDS_RESET, g_resetText, MAX_LOADSTRING) == 0)
    {
        fprintf(stderr, "LoadString() failed with error code %u.\n", GetLastError());
        return -1;
    }

    // D2D automatically handles high DPI settings
    SetProcessDPIAware();

    // Register Class
    if (!MyRegisterClass(hinst))
    {
        return -1;
    }

    // Initialize Application
    if (!InitInstance(hinst, SW_SHOWMAXIMIZED))
    {
        return -1;
    }

    // Main message loop
    MSG msg;
    while (GetMessage(&msg, nullptr, 0, 0) != 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    delete g_driver;
    g_driver = nullptr;

    return 0;
}
Esempio n. 10
0
HRESULT Initialize(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;
    ATOM atom;

    // Register window class
    wcex.cbSize        = sizeof(WNDCLASSEX);
    wcex.style         = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc   = WndProc;
    wcex.cbClsExtra    = 0;
    wcex.cbWndExtra    = sizeof(LONG_PTR);
    wcex.hInstance     = hInstance;
    wcex.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wcex.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = NULL;
    wcex.lpszMenuName  = NULL;
    wcex.lpszClassName = TEXT("InputSourceApp");
    wcex.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
    atom = RegisterClassEx(&wcex);

    SetProcessDPIAware();

    // Create window
    g_hwnd = CreateWindow(
        TEXT("InputSourceApp"),
        TEXT("Input Source Identification Sample"),
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        640,
        480,
        NULL,
        NULL,
        hInstance,
        NULL
        );

    if (g_hwnd)
    {
        ShowWindow(
            g_hwnd,
            SW_SHOWNORMAL
            );

        UpdateWindow(
            g_hwnd
            );
    }

    return g_hwnd ? S_OK : E_FAIL;
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
#if QT_VERSION > QT_VERSION_CHECK(5, 6, 0)
	QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);
#ifdef Q_OS_WIN32
	SetProcessDPIAware();
	HDC screen = GetDC(0);
	qreal dpix = GetDeviceCaps(screen, LOGPIXELSX);
	qreal dpiy = GetDeviceCaps(screen, LOGPIXELSY);
	qreal scale = dpiy / qreal(96);
	qputenv("QT_SCALE_FACTOR", QByteArray::number(scale));
	ReleaseDC(NULL, screen);
	qDebug() << "Current DPI x: " << dpix << " y: " << dpiy << " setting scale:" << scale;
#else
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
#endif
#endif

	CliApplication cliApp( argc, argv, APP );
	if( cliApp.isDiagnosticRun() )
	{
		return cliApp.run();
	}

	Common app( argc, argv, APP, ":/images/id_icon_128x128.png" );
#ifndef Q_OS_MAC
	if( app.isRunning() )
	{
		app.sendMessage( "" );
		return 0;
	}
#endif
	SSL_library_init();

	MainWindow w;
	Configuration::instance().checkVersion("QESTEIDUTIL");
#ifndef Q_OS_MAC
	QObject::connect( &app, SIGNAL(messageReceived(QString)), &w, SLOT(raiseAndRead()) );
#endif
	w.show();
	if(QWidget *data = w.findChild<QWidget*>("dataWidget"))
		data->setFixedSize(data->geometry().size()); // Hack for avoiding Qt Resize window IB-4242

	return app.exec();
}
Esempio n. 12
0
	SetupDisplay_Impl::SetupDisplay_Impl()
	{
		instance = this;
#if defined(WIN32) && !defined(__MINGW32__) // FIXME: Broken on MinGW (does not link)
		SetProcessDPIAware();
#endif

#if !defined __ANDROID__ && ! defined __APPLE__ && ! defined WIN32
		// The XInitThreads() function initializes Xlib support for concurrent threads.
		// This function must be the first Xlib function a multi-threaded program calls, and it must complete before any other Xlib call is made.
		XInitThreads();
#endif
		jpeg_provider = new ProviderType_Register<JPEGProvider>("jpeg");
		jpg_provider = new ProviderType_Register<JPEGProvider>("jpg");
		png_provider = new ProviderType_Register<PNGProvider>("png");
		targa_provider = new ProviderType_Register<TargaProvider>("targa");
		tga_provider = new ProviderType_Register<TargaProvider>("tga");

		FileResourceManager::add_cache_factory(std::function<void(ResourceManager &, const FileResourceDocument &)>(&SetupDisplay_Impl::add_cache_factory_file));
	}
Esempio n. 13
0
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	SetProcessDPIAware();
	
	if (!SetCurrentProcessPrivilege(SE_DEBUG_NAME, true))
	{
		ReturnMessage(L"进程调试权限获取失败");
		return -1;
	}
	
	GetModuleFileNameW(NULL, szAppPath, 260);
	wcsrchr(szAppPath, L'\\')[0] = NULL;

	wcscpy_s(szShortCutListPath, 260, szAppPath);
	wcscat_s(szShortCutListPath, 260, L"\\ShortCutList.ini");
	
	DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_NSudoDlg), NULL, NSudoDlgCallBack, 0L);

	return 0;
}
Esempio n. 14
0
///=====================================================
/// 
///=====================================================
HWND CreateAppWindow(HINSTANCE thisAppInstance, int nShowCmd){
	LPCWSTR GAME_NAME = TEXT("Dagger");

	WNDCLASSEX WindowDescription;
	memset(&WindowDescription, 0, sizeof(WNDCLASSEX));
	WindowDescription.cbSize = sizeof(WNDCLASSEX);
	WindowDescription.hInstance = thisAppInstance;
	WindowDescription.lpszClassName = GAME_NAME;
	WindowDescription.lpfnWndProc = GameMessageProcessingFunction; //processing function for Windows to call
	WindowDescription.style = CS_HREDRAW | CS_OWNDC | CS_VREDRAW;

	RegisterClassEx(&WindowDescription);

	SetProcessDPIAware();
	HWND desktopWindow = GetDesktopWindow();
	RECT desktopWindowRect;
	GetClientRect(desktopWindow, &desktopWindowRect); //can use to resize window proportionally to screen resolution

	RECT windowRect;
	windowRect.left = 100;
	windowRect.right = 1700;
	windowRect.top = 50;
	windowRect.bottom = 950;

	DWORD windowStyleFlags = WS_OVERLAPPEDWINDOW;
	DWORD windowStyleFlagsEx = WS_EX_APPWINDOW;
	AdjustWindowRectEx(&windowRect, windowStyleFlags, false, windowStyleFlagsEx);

	int width = windowRect.right - windowRect.left;
	int height = windowRect.bottom - windowRect.top;

	HWND windowHandle = CreateWindow(GAME_NAME, GAME_NAME, windowStyleFlags, windowRect.left, windowRect.top, width, height, NULL, NULL, thisAppInstance, NULL);
	
	if (windowHandle){
		ShowWindow(windowHandle, nShowCmd);
		UpdateWindow(windowHandle);
	}
	return windowHandle;
}
// Program entry point
int APIENTRY wWinMain(__in HINSTANCE hinst, __in_opt HINSTANCE hinstPrev, __in LPWSTR lpCmdLine,__in int nCmdShow)
{
    (void)HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
    UNREFERENCED_PARAMETER(hinstPrev);
    UNREFERENCED_PARAMETER(lpCmdLine);
    UNREFERENCED_PARAMETER(nCmdShow);
    BOOL success = TRUE;
    MSG msg;
    
    // Initialize global strings
    LoadString(hinst, IDS_WINDOW, g_tszWindowClass, MAX_LOADSTRING);
    LoadString(hinst, IDS_CAPTION, g_tszMainTitle, MAX_LOADSTRING);

    // D2D automatically handles high DPI settings
    SetProcessDPIAware();

    // Register Class
    MyRegisterClass(hinst);

    // Initialize Application
    if (!InitInstance(hinst, SW_SHOWMAXIMIZED)) 
    {
        wprintf(L"Failed to initialize application");
        success = FALSE;
    }
    
    if(success)
    {
        // Main message loop
        while (GetMessage(&msg, NULL, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    return success;
} 
Esempio n. 16
0
  void Init()
  {
    cDLL dll(TEXT("user32.dll"));
    if (dll.IsValid()) {
      BOOL (WINAPI *SetProcessDPIAware)() = nullptr;
      if (dll.LoadFunction("SetProcessDPIAware", &SetProcessDPIAware)) {
        std::wcout<<TEXT("WinMain Calling SetProcessDPIAware()")<<std::endl;
        SetProcessDPIAware();
      }
    }

    // Init common controls for modern looking theming
    INITCOMMONCONTROLSEX icce;
    icce.dwSize = sizeof(INITCOMMONCONTROLSEX);
    icce.dwICC =
      ICC_USEREX_CLASSES | // Combobox
      ICC_STANDARD_CLASSES // All other controls
    ;
    ::InitCommonControlsEx(&icce);

    // Init GDI+
    Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    Gdiplus::GdiplusStartup(&gGDIPlusToken, &gdiplusStartupInput, NULL);
  }
Esempio n. 17
0
//  Entry to the app
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR /*lpCmdLine*/, int /*nCmdShow*/)
{
    g_hInstance = hInstance;

    //  Mark that this process is DPI aware.
    SetProcessDPIAware();

    // Init COM and double-buffered painting
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (SUCCEEDED(hr))
    {
        hr = BufferedPaintInit();
        g_bDblBuffered = SUCCEEDED(hr);

        // Init volume monitor
        g_pVolumeMonitor = new (std::nothrow) CVolumeMonitor();
        if (g_pVolumeMonitor)
        {
            hr = g_pVolumeMonitor->Initialize();
            if (SUCCEEDED(hr))
            {
                // Get initial volume level so that we can figure out a good window size
                g_pVolumeMonitor->GetLevelInfo(&g_currentVolume);

                WNDCLASSEX wcex = { sizeof(wcex) };
                wcex.style          = CS_HREDRAW | CS_VREDRAW;
                wcex.lpfnWndProc    = WndProc;
                wcex.hInstance      = g_hInstance;
                wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
                wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
                wcex.lpszClassName  = g_szWindowClass;

                RegisterClassEx(&wcex);

                // Create the (only) window
                DWORD const dwStyle = WS_POPUP;     // no border or title bar
                DWORD const dwStyleEx = WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_NOACTIVATE;   // transparent, topmost, with no taskbar item
                g_hwndOSD = CreateWindowEx(dwStyleEx, g_szWindowClass, NULL, dwStyle, 0, 0, 0, 0, NULL, NULL, g_hInstance, NULL);
                if (g_hwndOSD)
                {
                    // Hide the window
                    ShowWindow(g_hwndOSD, SW_HIDE);

                    // Main message loop
                    MSG msg;
                    while (GetMessage(&msg, NULL, 0, 0))
                    {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                    }
                }

                if (g_bDblBuffered)
                    BufferedPaintUnInit();

                g_pVolumeMonitor->Dispose();
                g_pVolumeMonitor->Release();
            }
        }
        CoUninitialize();
    }

    return 0;
}
Esempio n. 18
0
const char *uiInit(uiInitOptions *o)
{
	STARTUPINFOW si;
	const char *ce;
	HICON hDefaultIcon;
	HCURSOR hDefaultCursor;
	NONCLIENTMETRICSW ncm;
	INITCOMMONCONTROLSEX icc;
	HRESULT hr;

	options = *o;

	initAlloc();

	nCmdShow = SW_SHOWDEFAULT;
	GetStartupInfoW(&si);
	if ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)
		nCmdShow = si.wShowWindow;

	SetProcessDPIAware();

	hDefaultIcon = LoadIconW(NULL, IDI_APPLICATION);
	if (hDefaultIcon == NULL)
		return ieLastErr("loading default icon for window classes");
	hDefaultCursor = LoadCursorW(NULL, IDC_ARROW);
	if (hDefaultCursor == NULL)
		return ieLastErr("loading default cursor for window classes");

	ce = initUtilWindow(hDefaultIcon, hDefaultCursor);
	if (ce != NULL)
		return initerr(ce, L"GetLastError() ==", GetLastError());

	if (registerWindowClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("registering uiWindow window class");

	ZeroMemory(&ncm, sizeof (NONCLIENTMETRICSW));
	ncm.cbSize = sizeof (NONCLIENTMETRICSW);
	if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICSW), &ncm, sizeof (NONCLIENTMETRICSW)) == 0)
		return ieLastErr("getting default fonts");
	hMessageFont = CreateFontIndirectW(&(ncm.lfMessageFont));
	if (hMessageFont == NULL)
		return ieLastErr("loading default messagebox font; this is the default UI font");

	if (initContainer(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("initializing uiWindowsMakeContainer() window class");

	hollowBrush = (HBRUSH) GetStockObject(HOLLOW_BRUSH);
	if (hollowBrush == NULL)
		return ieLastErr("getting hollow brush");

	ZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX));
	icc.dwSize = sizeof (INITCOMMONCONTROLSEX);
	icc.dwICC = wantedICCClasses;
	if (InitCommonControlsEx(&icc) == 0)
		return ieLastErr("initializing Common Controls");

	hr = CoInitialize(NULL);
	if (hr != S_OK && hr != S_FALSE)
		return ieHRESULT("initializing COM", hr);
	// LONGTERM initialize COM security
	// LONGTERM (windows vista) turn off COM exception handling

	hr = initDraw();
	if (hr != S_OK)
		return ieHRESULT("initializing Direct2D", hr);

	hr = initDrawText();
	if (hr != S_OK)
		return ieHRESULT("initializing DirectWrite", hr);

	if (registerAreaClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("registering uiArea window class");

	if (registerMessageFilter() == 0)
		return ieLastErr("registering libui message filter");

	if (registerD2DScratchClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("initializing D2D scratch window class");

	return NULL;
}
Esempio n. 19
0
	s32 proc()
	{
#if _WIN32
		SetProcessDPIAware();
#endif

#if defined(__APPLE__)
		SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1");
#endif

		// Initialize SDL
		if (SDL_Init(
			SDL_INIT_VIDEO
			| SDL_INIT_EVENTS
			| SDL_INIT_GAMECONTROLLER
			| SDL_INIT_HAPTIC
			| SDL_INIT_TIMER
			| SDL_INIT_JOYSTICK
		) < 0)
		{
			fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError());
			return -1;
		}

		Loader::data_directory = SDL_GetPrefPath("HelveticaScenario", "Yearning");

		SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");

		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);

		{
			SDL_DisplayMode display;
			SDL_GetDesktopDisplayMode(0, &display);
			Loader::settings_load(display.w, display.h);
		}

		if (SDL_SetRelativeMouseMode(SDL_TRUE) != 0)
		{
			fprintf(stderr, "Failed to set relative mouse mode: %s\n", SDL_GetError());
			return -1;
		}

		window = SDL_CreateWindow
		(
			"The Yearning",
			0,
			0,
			Settings::width, Settings::height,
			SDL_WINDOW_OPENGL
			| SDL_WINDOW_SHOWN
			| SDL_WINDOW_INPUT_GRABBED
			| SDL_WINDOW_INPUT_FOCUS
			| SDL_WINDOW_MOUSE_FOCUS
			| SDL_WINDOW_MOUSE_CAPTURE
			| SDL_WINDOW_ALLOW_HIGHDPI
			| (Settings::fullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_BORDERLESS)
		);

#if defined(__APPLE__)
		SDL_SetWindowGrab(window, SDL_TRUE);
#endif

		// Open a window and create its OpenGL context
		if (!window)
		{
			fprintf(stderr, "Failed to open SDL window. Most likely your GPU is out of date! %s\n", SDL_GetError());
			SDL_Quit();
			return -1;
		}

		SDL_GLContext context = SDL_GL_CreateContext(window);
		if (!context)
		{
			fprintf(stderr, "Failed to create GL context: %s\n", SDL_GetError());
			return -1;
		}

		if (SDL_GL_SetSwapInterval(Settings::vsync ? 1 : 0) != 0)
		{
			fprintf(stderr, "Failed to set OpenGL swap interval: %s\n", SDL_GetError());
			return -1;
		}

		{
			glewExperimental = true; // Needed for core profile

			GLenum glew_result = glewInit();
			if (glew_result != GLEW_OK)
			{
				fprintf(stderr, "Failed to initialize GLEW: %s\n", glewGetErrorString(glew_result));
				return -1;
			}
		}

		glGetError(); // Clear initial error caused by GLEW

		render_init();

		// Launch threads

		Sync<LoopSync> render_sync;

		LoopSwapper swapper_render_update = render_sync.swapper(0);
		LoopSwapper swapper_render = render_sync.swapper(1);

		Sync<PhysicsSync, 1> physics_sync;

		PhysicsSwapper swapper_physics = physics_sync.swapper();
		PhysicsSwapper swapper_physics_update = physics_sync.swapper();

		std::thread thread_physics(Physics::loop, &swapper_physics);

		std::thread thread_update(Loop::loop, &swapper_render_update, &swapper_physics_update);

		std::thread thread_ai(AI::loop);

		LoopSync* sync = swapper_render.get();

		r64 last_time = SDL_GetTicks() / 1000.0;

		b8 has_focus = true;

		SDL_PumpEvents();

		const u8* sdl_keys = SDL_GetKeyboardState(0);

		refresh_controllers();

		while (true)
		{
			render(sync);

			// Swap buffers
			SDL_GL_SwapWindow(window);

			SDL_PumpEvents();

			memcpy(sync->input.keys, sdl_keys, sizeof(sync->input.keys));

			sync->input.keys[(s32)KeyCode::MouseWheelDown] = false;
			sync->input.keys[(s32)KeyCode::MouseWheelUp] = false;

			SDL_Event sdl_event;
			while (SDL_PollEvent(&sdl_event))
			{
				if (sdl_event.type == SDL_QUIT)
					sync->quit = true;
				else if (sdl_event.type == SDL_MOUSEWHEEL)
				{ 
					b8 up = sdl_event.wheel.y > 0;
					if (sdl_event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED)
						up = !up;
					if (up)
						sync->input.keys[(s32)KeyCode::MouseWheelUp] = true;
					else
						sync->input.keys[(s32)KeyCode::MouseWheelDown] = true;
				} 
				else if (sdl_event.type == SDL_JOYDEVICEADDED
					|| sdl_event.type == SDL_JOYDEVICEREMOVED)
					refresh_controllers();
				else if (sdl_event.type == SDL_WINDOWEVENT)
				{
					if (sdl_event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED)
						has_focus = true;
					else if (sdl_event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
						has_focus = false;
				}
			}

			sync->input.focus = has_focus;

			s32 mouse_buttons = SDL_GetRelativeMouseState(&sync->input.cursor_x, &sync->input.cursor_y);

			sync->input.keys[(s32)KeyCode::MouseLeft] = mouse_buttons & (1 << 0);
			sync->input.keys[(s32)KeyCode::MouseMiddle] = mouse_buttons & (1 << 1);
			sync->input.keys[(s32)KeyCode::MouseRight] = mouse_buttons & (1 << 2);

			s32 active_gamepads = 0;
			for (s32 i = 0; i < MAX_GAMEPADS; i++)
			{
				SDL_GameController* controller = controllers[i];
				Gamepad* gamepad = &sync->input.gamepads[i];
				gamepad->active = controller != 0;
				gamepad->btns = 0;
				if (gamepad->active)
				{
					gamepad->left_x = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_LEFTX) / 32767.0f;
					gamepad->left_y = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_LEFTY) / 32767.0f;
					gamepad->right_x = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX) / 32767.0f;
					gamepad->right_y = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY) / 32767.0f;
					gamepad->left_trigger = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_TRIGGERLEFT) / 32767.0f;
					gamepad->right_trigger = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) / 32767.0f;
					if (gamepad->left_trigger > 0.5f)
						gamepad->btns |= Gamepad::Btn::LeftTrigger;
					if (gamepad->right_trigger > 0.5f)
						gamepad->btns |= Gamepad::Btn::RightTrigger;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_LEFTSHOULDER))
						gamepad->btns |= Gamepad::Btn::LeftShoulder;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER))
						gamepad->btns |= Gamepad::Btn::RightShoulder;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_LEFTSTICK))
						gamepad->btns |= Gamepad::Btn::LeftClick;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_RIGHTSTICK))
						gamepad->btns |= Gamepad::Btn::RightClick;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_A))
						gamepad->btns |= Gamepad::Btn::A;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_B))
						gamepad->btns |= Gamepad::Btn::B;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_X))
						gamepad->btns |= Gamepad::Btn::X;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_Y))
						gamepad->btns |= Gamepad::Btn::Y;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_BACK))
						gamepad->btns |= Gamepad::Btn::Back;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_START))
						gamepad->btns |= Gamepad::Btn::Start;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_UP))
						gamepad->btns |= Gamepad::Btn::DUp;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_DOWN))
						gamepad->btns |= Gamepad::Btn::DDown;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
						gamepad->btns |= Gamepad::Btn::DLeft;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
						gamepad->btns |= Gamepad::Btn::DRight;
					if (gamepad->rumble > 0.0f)
						SDL_HapticRumblePlay(haptics[i], gamepad->rumble, 33);
					gamepad->rumble = 0.0f;
					active_gamepads++;
				}
				else
				{
					gamepad->left_x = 0.0f;
					gamepad->left_y = 0.0f;
					gamepad->right_x = 0.0f;
					gamepad->right_y = 0.0f;
					gamepad->left_trigger = 0.0f;
					gamepad->right_trigger = 0.0f;
					gamepad->rumble = 0.0f;
				}
			}

			SDL_GetWindowSize(window, &sync->input.width, &sync->input.height);

			r64 time = (SDL_GetTicks() / 1000.0);
			sync->time.total = (r32)time;
			sync->time.delta = vi_min((r32)(time - last_time), 0.25f);
			last_time = time;

			b8 quit = sync->quit;

			sync = swapper_render.swap<SwapType_Read>();

			if (quit || sync->quit)
				break;
		}

		AI::quit();

		thread_update.join();
		thread_physics.join();
		thread_ai.join();

		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(window);

		// SDL sucks
		for (s32 i = 0; i < MAX_GAMEPADS; i++)
		{
			if (haptics[i])
				SDL_HapticClose(haptics[i]);
		}

		SDL_Quit();

		return 0;
	}
Esempio n. 20
0
int wmain(int argc, _TCHAR* argv[])
{
	//******** NSudoInitialize Start ********
	NSudoReturnMessage(TextRes.NSudo_AboutText);
	
	if (argc == 1) bGUIMode = true;

	SetProcessDPIAware();

	GetModuleFileNameW(NULL, szAppPath, 260);
	wcsrchr(szAppPath, L'\\')[0] = NULL;

	wcscpy_s(szShortCutListPath, 260, szAppPath);
	wcscat_s(szShortCutListPath, 260, L"\\ShortCutList.ini");

	if (!SetCurrentProcessPrivilege(SE_DEBUG_NAME, true))
	{
		if (bGUIMode)
		{
			wchar_t szExePath[260];

			GetModuleFileNameW(NULL, szExePath, 260);
			
			ShellExecuteW(NULL, L"runas", szExePath, NULL, NULL, SW_SHOW);
			return 0;

		}
		else
		{
			NSudoReturnMessage(TextRes.NSudo_Error_Text1);
			return -1;
		}
	}

	//******** NSudoInitialize End ********
	
	if (bGUIMode)
	{
		FreeConsole();

		DialogBoxParamW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDD_NSudoDlg), NULL, NSudoDlgCallBack, 0L);
	}
	else
	{
		bool bUserArgEnable = true;
		bool bPrivilegeArgEnable = true;
		bool bIntegrityArgEnable = true;
		bool bCMDLineArgEnable = true;

		wchar_t *szBuffer = NULL;

		HANDLE hUserToken = INVALID_HANDLE_VALUE;

		for (int i = 1; i < argc; i++)
		{
			if (_wcsicmp(argv[i], L"-?") == 0)
			{
				NSudoReturnMessage(TextRes.NSudoC_HelpText);
				return 0;
			}
			else if (bUserArgEnable && _wcsicmp(argv[i], L"-U:T") == 0)
			{
				NSudoGetTrustedInstallerToken(&hUserToken);
				bUserArgEnable = false;
			}
			else if (bUserArgEnable && _wcsicmp(argv[i], L"-U:S") == 0)
			{
				NSudoGetSystemToken(&hUserToken);
				bUserArgEnable = false;
			}
			else if (bUserArgEnable && _wcsicmp(argv[i], L"-U:C") == 0)
			{
				NSudoGetCurrentUserToken(&hUserToken);
				bUserArgEnable = false;
			}
			else if (bUserArgEnable && _wcsicmp(argv[i], L"-U:P") == 0)
			{
				NSudoGetCurrentProcessToken(&hUserToken);
				bUserArgEnable = false;
			}
			else if (bUserArgEnable && _wcsicmp(argv[i], L"-U:D") == 0)
			{
				NSudoCreateLUAToken(&hUserToken);
				bUserArgEnable = false;
			}
			else if (bPrivilegeArgEnable && _wcsicmp(argv[i], L"-P:E") == 0)
			{
				NSudoAdjustAllTokenPrivileges(hUserToken, true);
				bPrivilegeArgEnable = false;
			}
			else if (bPrivilegeArgEnable && _wcsicmp(argv[i], L"-P:D") == 0)
			{
				NSudoAdjustAllTokenPrivileges(hUserToken, false);
				bPrivilegeArgEnable = false;
			}
			else if (bIntegrityArgEnable && _wcsicmp(argv[i], L"-M:S") == 0)
			{
				SetTokenIntegrity(hUserToken, L"S-1-16-16384");
				bIntegrityArgEnable = false;
			}
			else if (bIntegrityArgEnable && _wcsicmp(argv[i], L"-M:H") == 0)
			{
				SetTokenIntegrity(hUserToken, L"S-1-16-12288");
				bIntegrityArgEnable = false;
			}
			else if (bIntegrityArgEnable && _wcsicmp(argv[i], L"-M:M") == 0)
			{
				SetTokenIntegrity(hUserToken, L"S-1-16-8192");
				bIntegrityArgEnable = false;
			}
			else if (bIntegrityArgEnable && _wcsicmp(argv[i], L"-M:L") == 0)
			{
				SetTokenIntegrity(hUserToken, L"S-1-16-4096");
				bIntegrityArgEnable = false;
			}
			else if (bCMDLineArgEnable)
			{
				wchar_t szPath[260];

				DWORD dwLength = GetPrivateProfileStringW(argv[i], L"CommandLine", L"", szPath, 260, szShortCutListPath);

				wcscmp(szPath, L"") != 0 ? szBuffer = szPath : szBuffer = argv[i];

				if (szBuffer) bCMDLineArgEnable = false;
			}

		}

		if (bUserArgEnable || bCMDLineArgEnable)
		{
			NSudoReturnMessage(TextRes.NSudo_Error_Text4);
			return -1;
		}
		else
		{
			if (NSudoImpersonateSystemToken())
			{
				if (!NSudoCreateProcess(hUserToken, szBuffer))
				{
					NSudoReturnMessage(TextRes.NSudo_Error_Text3);
				}

				RevertToSelf();
			}
		}

		CloseHandle(hUserToken);
	}

	return 0;
}
Esempio n. 21
0
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                       _In_opt_ HINSTANCE hPrevInstance,
                       _In_ LPTSTR    lpCmdLine,
                       _In_ int       nCmdShow)
{
  UNREFERENCED_PARAMETER(hInstance);
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpCmdLine);
  UNREFERENCED_PARAMETER(nCmdShow);
  debug_log("starting process");

  // Prevent error dialogs.
  _set_error_mode(_OUT_TO_STDERR);
  _CrtSetReportHook(CrtDbgHook);
  SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
      SEM_NOOPENFILEERRORBOX);

  // The Visual Studio debugger starts us in the build\ subdirectory by
  // default, which will prevent us from finding the test files in the html\
  // directory. This workaround will locate the html\ directory even if it's
  // in the parent directory so we will work in the debugger out of the box.
  WIN32_FIND_DATA find_data;
  HANDLE h = FindFirstFile("html", &find_data);
  if (h == INVALID_HANDLE_VALUE) {
    h = FindFirstFile("..\\html", &find_data);
    if (h != INVALID_HANDLE_VALUE) {
      SetCurrentDirectory("..");
    }
  }
  if (h != INVALID_HANDLE_VALUE) {
    FindClose(h);
  }

  // Prevent automatic DPI scaling.
  SetProcessDPIAware();

  if (__argc == 1) {
    debug_log("running server");
    HDC desktop = GetDC(NULL);
    assert(desktop);
    if (GetDeviceCaps(desktop, LOGPIXELSX) != 96) {
      MessageBox(NULL, "Warning: DPI scaling is enabled. Non-DPI-aware browsers will not be able to run the test.",
                 "Warning", MB_ICONWARNING | MB_OK);
    }
    ReleaseDC(NULL, desktop);
    run_server();
  }
  debug_log("opening native reference window");
  if (__argc != 3) {
    debug_log("Unrecognized number of arguments");
    return 1;
  }
  // The first argument is the magic pattern to draw on the window, encoded as hex.
  memset(pattern, 0, sizeof(pattern));
  if (!parse_hex_magic_pattern(__argv[1], pattern)) {
    debug_log("Failed to parse pattern");
    return 1;
  }
  // The second argument is the handle of the parent process.
  HANDLE parent_process = (HANDLE)_strtoui64(__argv[2], NULL, 16);
  message_loop(parent_process);
  return 0;
}
Esempio n. 22
0
int main( char *pszArg[] )
{
	ShowWindow(GetConsoleWindow(), SW_HIDE);
	SetProcessDPIAware();
	std::string strWindowTitle( "", 0x40 );
	strWindowTitle = "Guild Wars 2";

	Overlay::IOverlay *pOverlay = new Overlay::CD3D9Overlay( );
	pOverlay->GetSurface( )->PrepareFont( "Default", "Arial", 20, FW_BOLD, 0, 0, FALSE );
	pOverlay->GetSurface()->PrepareFont("Headline", "Arial", 25, FW_BOLD, 0, 0, FALSE);
	if( pOverlay->Create( strWindowTitle ) )
	{
		auto WaterMarkFn = []( Overlay::IOverlay *pOverlay, std::shared_ptr< Overlay::ISurface > pSurface )
		{
			//Move overlay if window is moved
			/*for (int i = 1; i <= barWidth; i++) {
				for (int j = 1; j <= barHeight; j++) {
					int x = i;
					int y = j;
					int col = createRGBA(posR(x, y), posG(x, y), posB(x, y), 255);
					pSurface->Rect(500 + i, 800 + j, 1, 1, col);
				}
			}*/
			pOverlay->ScaleOverlayWindow();
			processInput(pSurface);
			displayPercentualHP(pSurface);
			if (showMenu) {
				displayMenu(pSurface);
			}
			/**pSurface->Rect(800, 90, 100, 50, barColor);
			POINT p;
			GetPhysicalCursorPos(&p);
			HWND window = GetForegroundWindow();
			ScreenToClient(window, &p);
			std::stringstream s2;
			s2 << std::fixed << std::setprecision(1) << p.x << " | " << p.y;
			std::string col = s2.str() + "P";
			static char cola[1024];
			strncpy_s(cola, col.c_str(), sizeof(cola));
			pSurface->String(500, 90, "Default", createRGBA(0, 255, 0, 255), cola);
			strncpy_s(cola, std::to_string(barPosX).c_str(), sizeof(cola));
			pSurface->String(500, 120, "Default", createRGBA(0, 255, 0, 255), cola);
			strncpy_s(cola, std::to_string(barPosY).c_str(), sizeof(cola));
			pSurface->String(500, 150, "Default", createRGBA(0, 255, 0, 255), cola);
			strncpy_s(cola, std::to_string(barWidth).c_str(), sizeof(cola));
			pSurface->String(500, 180, "Default", createRGBA(0, 255, 0, 255), cola);
			strncpy_s(cola, std::to_string(barHeight).c_str(), sizeof(cola));
			pSurface->String(500, 210, "Default", createRGBA(0, 255, 0, 255), cola);
			*/
		};
		
		pOverlay->AddToCallback( WaterMarkFn );
		while (pOverlay->Render()) {
		}
	}else {

	}

	pOverlay->Shutdown();
	delete pOverlay; 
	return 0;

}