Beispiel #1
0
//-----------------------------------WinMain-----------------------------------------
//	Entry point for our windows application
//-----------------------------------------------------------------------------------
int WINAPI WinMain(	HINSTANCE hinstance,
					          HINSTANCE hprevinstance,
					          LPSTR lpcmdline,
					          int ncmdshow)
{

	WNDCLASSEX winclass; 
	HWND	   hwnd;	 
	MSG		   msg;		 

	// first fill in the window class stucture
	winclass.cbSize       = sizeof(WNDCLASSEX);
	winclass.style			  = CS_HREDRAW | CS_VREDRAW;
	winclass.lpfnWndProc	= WindowProc;
	winclass.cbClsExtra		= 0;
	winclass.cbWndExtra		= 0;
	winclass.hInstance		= hinstance;
	winclass.hIcon			  = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1));
	winclass.hCursor		  = LoadCursor(NULL, IDC_ARROW); 
	winclass.hbrBackground= NULL; 
	winclass.lpszMenuName	= NULL;
	winclass.lpszClassName= szWindowClassName;
	winclass.hIconSm      = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1));


	// register the window class
	if (!RegisterClassEx(&winclass))
	{
		MessageBox(NULL, "Error Registering Class!", "Error", 0);
    return 0;
	}

	// create the window (one that cannot be resized)
	if (!(hwnd = CreateWindowEx(NULL,									
								              szWindowClassName,						
								              szApplicationName,						
								              WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU,
                              GetSystemMetrics(SM_CXSCREEN)/2 - CParams::WindowWidth/2,
                              GetSystemMetrics(SM_CYSCREEN)/2 - CParams::WindowHeight/2,									
								              CParams::WindowWidth,
                              CParams::WindowHeight,				
								              NULL,									
								              NULL,								
								              hinstance,								
								              NULL)))	
	{
    MessageBox(NULL, "Error Creating Window!", "Error", 0);
		return 0;
	}
	
	//Show the window
	ShowWindow(hwnd, SW_SHOWDEFAULT );
	UpdateWindow(hwnd);

	//create a timer
	CTimer timer(CParams::iFramesPerSecond);

	//start the timer
	timer.Start();

	// Enter the message loop
	bool bDone = FALSE;

	while(!bDone)
	{
					
		while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) 
		{
			if( msg.message == WM_QUIT ) 
			{
				//Stop loop if it's a quit message
				bDone = TRUE;
			} 

			else 
			{
				TranslateMessage( &msg );
				DispatchMessage( &msg );
			}
		}
							
		if (timer.ReadyForNextFrame() || g_pController->FastRender())
		{	
		  if(!g_pController->Update())
			{
				//we have a problem, end app
				bDone = TRUE;
			}

			//this will call WM_PAINT which will render our scene
			InvalidateRect(hwnd, NULL, TRUE);
			UpdateWindow(hwnd);
    }					
					
	}//end while
	

    // Clean up everything and exit the app
    Cleanup();
    UnregisterClass( szWindowClassName, winclass.hInstance );
	
	return 0;

} // end WinMain
Beispiel #2
0
//内核配置
bool  CClientKernel::InitClientKernel(HWND hWnd, const std::string &CmdLine, CClientKernelSink* pIUnknownEx)
{

    if (CmdLine.empty()) return false;

    //获取框架
    m_hWndGameFrame=hWnd;
    m_pIClientKernelSink = pIUnknownEx;

    //创建窗口
    if (m_hWndChannel==NULL) 
    {
        WNDCLASS wc = { CS_HREDRAW | CS_VREDRAW, 
            CClientKernel::ChannelWndProc, 0, 0, GetModuleHandle(0),
            LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
            (HBRUSH)GetStockObject(BLACK_BRUSH), 0, "ChannelWND"};
        RegisterClass(&wc);

        //创建窗口
        m_hWndChannel = CreateWindowEx(0, "ChannelWND","ChannelWND",WS_CHILD,0,0,0,0,GetDesktopWindow(),0,GetModuleHandle(0),0);
    }

    //命令行处理
    if (CmdLine.empty()!=true)
    {
        std::string::size_type pos1;
        std::string::size_type pos2;
        std::string szRoomToken;
        std::string szComLine(CmdLine);

        pos1 = szComLine.find("/RoomToken:");
        if (pos1 != std::string::npos)
        {
            pos2 = szComLine.find_first_of("/", pos1+10);
            szRoomToken = szComLine.substr(pos1+11, pos2-pos1-12);
        }

        //共享内存
        if (!szRoomToken.empty())
        {
            m_hShareMemory=OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,szRoomToken.c_str());
            if (m_hShareMemory==NULL) return false;

            m_pShareMemory=(tagShareMemory *)MapViewOfFile(m_hShareMemory,FILE_MAP_ALL_ACCESS,0,0,0);
            if (m_pShareMemory==NULL) return false;

            if (m_pShareMemory->wDataSize<sizeof(tagShareMemory)) return false;
            m_pShareMemory->hWndGameFrame=m_hWndGameFrame;

            m_hWndGameServer = m_pShareMemory->hWndGameServer;

            SendData(IPC_MIAN_IPC_KERNEL,IPC_SUB_IPC_CLIENT_CONNECT);
        }
    }


    //更新标题
    UpdateGameTitle();

    return true;
}
Beispiel #3
0
bool BasicWindow::InitWindowsApp(HINSTANCE appHandle, int showStyle)
{
	int classStyle, bgColor, wndStyle, width, height, x, y;
	char caption[255];

	// Read integers from ini file: class style, bgcolor, window style, width, height and starting x and y.
	classStyle = GetPrivateProfileInt("Window", "class_style", 0, "./D3D11.ini");
	bgColor = GetPrivateProfileInt("Window", "bgcolor", 0, "./D3D11.ini");
	wndStyle = GetPrivateProfileInt("Window", "window_style", 0, "./D3D11.ini");
	width = GetPrivateProfileInt("Window", "width", 0, "./D3D11.ini");
	height = GetPrivateProfileInt("Window", "height", 0, "./D3D11.ini");
	x = GetPrivateProfileInt("Window", "x", 0, "./D3D11.ini");
	y = GetPrivateProfileInt("Window", "y", 0, "./D3D11.ini");

	// Make sure the width, height and starting x, y are valid numbers.
	width = width <=0 ? CW_USEDEFAULT : width;
	height = height <=0 ? CW_USEDEFAULT : height;
	x = x <=0 ? CW_USEDEFAULT : x;
	y = y <=0 ? CW_USEDEFAULT : y;

	// Read the window caption from file and store.
	GetPrivateProfileString("Window", "caption", "Ny Window", caption, 255, "./D3D11.ini");
	mCaption = caption;

	WNDCLASS wc;

	// If the window class is not already registered, register it.
	if(!GetClassInfo(appHandle, "BasicWindowClass", &wc))
	{
		wc.style = classStyle;						// Window class style: Redraw when movement or size changes.
		wc.lpfnWndProc = WindowProc;				// Pointer to the window procedure.
		wc.cbClsExtra = 0;							// No extra bytes allocated following the class structure.
		wc.cbWndExtra = 0;							// No extra bytes allocated followint the window instance.
		wc.hInstance = appHandle;					// Handle to the instance where the window procedure is contained.
		wc.hIcon = LoadIcon(0, IDI_APPLICATION);	// Handle to the class icon.
		wc.hCursor = LoadCursor(0, IDC_ARROW);		// Handle to the class cursor.
		wc.hbrBackground = (HBRUSH)bgColor;			// Handle to the class background brush.
		wc.lpszMenuName = 0;						// Resource name of the class menu.
		wc.lpszClassName = "BasicWindowClass";		// Name of the class for use when the window is created.

		// If the class registration failed, show a message and return failure.
		if(!RegisterClass(&wc))
		{
			std::stringstream ss;
			ss << "RegisterClass failed, error code: ";
			ss << GetLastError();

			ShowMessage(ss.str());
			return false;
		}
	}

	// Create the window and save a handle to it.
	mHandle = CreateWindow("BasicWindowClass",	// Name of the registered window class to use at creation.
						   mCaption.c_str(),	// The caption of the window.
						   wndStyle,			// Window style.
						   x,					// Initial x-position.
						   y,					// Initial y-position.
						   width,				// Width of the window in device units.
						   height,				// Height of the window in device units.
						   0,					// Handle to parent (there is no parent).
						   0,					// Handle to a menu (there is no menu).
						   appHandle,			// Application instance handle.
						   this);				// The value passed to the window through CREATESTRUCT's 
												// lpCreateParams member (used in WindowProc).

	// If the window creation failed, show a message and return failure.
	if(mHandle == 0)
	{
		std::stringstream ss;
		ss << "CreateWindow failed, error code: ";
		ss << GetLastError();

		ShowMessage(ss.str());
		return false;
	}

	// Show and update the window and return success.
	ShowWindow(mHandle, showStyle);
	UpdateWindow(mHandle);

	return true;
}
Beispiel #4
0
/*
 * imgEditInit - initialization
 */
static BOOL imgEditInit( HANDLE currinst, HANDLE previnst, int cmdshow )
{
    WNDCLASS    wc;
    HMENU       menu;
    HDC         hdc;
    BOOL        maximized;
    int         show_state;

    hdc = GetDC( NULL );
    ColorPlanes = GetDeviceCaps( hdc, PLANES );
    BitsPerPixel = GetDeviceCaps( hdc, BITSPIXEL );
    ReleaseDC( NULL, hdc );

    Instance = currinst;
    IEInitErrors( currinst );
    IEInitGlobalStrings();

    if( ImgedIsDDE ) {
        menu = LoadMenu( Instance, "IMGEDDDEMENU" );
    } else {
        menu = LoadMenu( Instance, "IMGEDMENU" );
    }

    hBitmapIcon = LoadIcon( Instance, "BitmapIcon" );
    hIconIcon = LoadIcon( Instance, "IconIcon" );
    hCursorIcon = LoadIcon( Instance, "CursorIcon" );
    hAccel = LoadAccelerators( Instance, "Accelerators" );

    IECtl3dInit( Instance );

#if defined( __NT__ )
    hBkBrush = CreateSolidBrush( GetSysColor( COLOR_BTNFACE ) );
#endif

    /*
     * set up window class
     */
    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)ImgEdFrameProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = LoadIcon( Instance, "APPLICON" );
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = NULL;
        wc.lpszMenuName = NULL;
        wc.lpszClassName = className;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    /*
     * This is the child of the MDI frame window (of it's client window actually).
     */
    if( !previnst ) {
        wc.style = CS_BYTEALIGNWINDOW | CS_CLASSDC | CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)DrawAreaWinProc;
        wc.cbClsExtra = sizeof( HCURSOR );
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = hBitmapIcon;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = DrawAreaClassB;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = CS_BYTEALIGNWINDOW | CS_CLASSDC | CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)DrawAreaWinProc;
        wc.cbClsExtra = sizeof( HCURSOR );
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = hIconIcon;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = DrawAreaClassI;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = CS_BYTEALIGNWINDOW | CS_CLASSDC | CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)DrawAreaWinProc;
        wc.cbClsExtra = sizeof( HCURSOR );
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = hCursorIcon;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = DrawAreaClassC;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)ViewWindowProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = ViewWinClass;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)ColorPalWinProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = PaletteClass;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    handCursor = LoadCursor( Instance, "HandCursor" );
    if( !previnst ) {
        wc.style = CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)ColorsWndProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = handCursor;
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = "ColorsClass";
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)ScreenWndProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = handCursor;
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = "ScreenClass";
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)CurrentWndProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = "CurrentClass";
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)BitmapPickProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = NULL;
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = BitmapPickClass;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    /*
     * Now make the main window.
     */
    LoadImgedConfig();
    maximized = ImgedConfigInfo.ismaximized;

    InitPalette();
    HMainWindow = CreateWindow(
        className,                              /* Window class name */
        IEAppTitle,                             /* Window caption */
        WS_OVERLAPPEDWINDOW | WS_BORDER | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
        | WS_DLGFRAME,                          /* Window style */
        ImgedConfigInfo.x_pos,                  /* Initial X position */
        ImgedConfigInfo.y_pos,                  /* Initial Y position */
        ImgedConfigInfo.width,                  /* Initial X size */
        ImgedConfigInfo.height,                 /* Initial Y size */
        (HWND)NULL,                             /* Parent window handle */
        (HMENU)menu,                            /* Window menu handle */
        Instance,                               /* Program instance handle */
        NULL );                                 /* Create parameters */

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

    if( maximized ) {
        if( cmdshow == SW_SHOW || cmdshow == SW_SHOWNORMAL ) {
            show_state = SW_SHOWMAXIMIZED;
        } else {
            show_state = cmdshow;
        }
    } else {
        show_state = cmdshow;
    }
    ShowWindow( HMainWindow, show_state );
    UpdateWindow( HMainWindow );

    if( !ImgedIsDDE && !NoTitleScreen ) {
        DisplayTitleScreen( Instance, HMainWindow, 2000, IEAppTitle );
    }

    CreateColorPal();
    InitTools( HMainWindow );
    GrayEditOptions();

#ifdef __NT__
    DragAcceptFiles( HMainWindow, TRUE );
#endif
    //SetActiveWindow( HMainWindow );
    BringWindowToTop( HMainWindow );
    return( TRUE );

} /* imgEditInit */
int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hInstP, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg={0};
    WNDCLASS wc;

    // Initialize COM
    if(FAILED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)))
    {
        Msg(TEXT("CoInitialize Failed!\r\n"));   
        exit(1);
    } 

    // Register the window class
    ZeroMemory(&wc, sizeof wc);
    wc.lpfnWndProc   = WndMainProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASSNAME;
    wc.lpszMenuName  = NULL;
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hIcon         = NULL;
    if(!RegisterClass(&wc))
    {
        Msg(TEXT("RegisterClass Failed! Error=0x%x\r\n"), GetLastError());
        CoUninitialize();
        exit(1);
    }

    // Create the main window.  The WS_CLIPCHILDREN style is required.
    ghApp = CreateWindow(CLASSNAME, APPLICATIONNAME,
                         WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_CLIPCHILDREN,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         DEFAULT_VIDEO_WIDTH, DEFAULT_VIDEO_HEIGHT,
                         0, 0, hInstance, 0);

    if(ghApp)
    {
        HRESULT hr;

        // Create DirectShow graph and start capturing video
        hr = CaptureVideo();
        if (FAILED (hr))
        {
            CloseInterfaces();
            DestroyWindow(ghApp);
        }
        else
        {
            // Don't display the main window until the DirectShow
            // preview graph has been created.  Once video data is
            // being received and processed, the window will appear
            // and immediately have useful video data to display.
            // Otherwise, it will be black until video data arrives.
            ShowWindow(ghApp, nCmdShow);
        }       

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

    // Release COM
    CoUninitialize();

    return (int) msg.wParam;
}
Beispiel #6
0
bool Engine::InitWindow()
{
	

	WNDCLASSEX wc;
	//DEVMODE dmScreenSettings;
	int posX, posY,screenWidth,screenHeight;
	bool FULL_SCREEN = false;

	//ApplicationHandle = this;
	
	m_instance = GetModuleHandle(NULL);

	m_appname = L"AllenEngine";

	
	wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wc.lpfnWndProc = WindowProc;
    wc.hInstance = m_instance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);//(HBRUSH)COLOR_WINDOW; //Background Colour
    wc.lpszClassName = m_appname; //Application Name
	wc.cbClsExtra	= 0;
	wc.cbWndExtra	= 0;
	wc.hIcon		= LoadIcon(NULL, IDI_WINLOGO);
	wc.hIconSm		= wc.hIcon;	
	wc.lpszMenuName = NULL;
	

	RegisterClassEx(&wc);//Windows class needs to be registered
	
	screenWidth = 800;
	screenHeight = 600;

	posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) /2;
	posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
	

	m_hwnd = CreateWindowEx(
		WS_EX_APPWINDOW,
        m_appname,    // name of the window class
        m_appname, // title of the window
        WS_OVERLAPPEDWINDOW,// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP,    // window style
        posX,    // x-position of the window
        posY,    // y-position of the window
        screenWidth,    // width of the window
        screenHeight,    // height of the window
        NULL,    // we have no parent window, NULL
        NULL,    // we aren't using menus, NULL
        m_instance,    // application handle
        NULL);    // used with multiple windows, NULL

	
	
	ShowWindow(m_hwnd, SW_SHOW);
	SetForegroundWindow(m_hwnd);
	SetFocus(m_hwnd);

	//ShowCursor(false);

	return true;
}
HWND VulkanBase::setupWindow(HINSTANCE hinstance, WNDPROC wndproc) {
	this->windowInstance = hinstance;

	bool fullscreen = false;

	for (int32_t i = 0; i < __argc; i++)
		if (__argv[i] == std::string("-fullscreen"))
			fullscreen = true;

	WNDCLASSEX wndClass;

	wndClass.cbSize = sizeof(WNDCLASSEX);
	wndClass.style = CS_HREDRAW | CS_VREDRAW;
	wndClass.lpfnWndProc = wndproc;
	wndClass.cbClsExtra = 0;
	wndClass.cbWndExtra = 0;
	wndClass.hInstance = hinstance;
	wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wndClass.lpszMenuName = NULL;
	wndClass.lpszClassName = name.c_str();
	wndClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);

	if (!RegisterClassEx(&wndClass)){
		std::cout << "Could not register window class!\n";
		fflush(stdout);
		exit(1);
	}

	int screenWidth = GetSystemMetrics(SM_CXSCREEN);
	int screenHeight = GetSystemMetrics(SM_CYSCREEN);

	if (fullscreen){
		DEVMODE dmScreenSettings;
		memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
		dmScreenSettings.dmSize = sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth = screenWidth;
		dmScreenSettings.dmPelsHeight = screenHeight;
		dmScreenSettings.dmBitsPerPel = 32;
		dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

		if ((width != screenWidth) && (height != screenHeight)){
			if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL){
				if (MessageBox(NULL, "Fullscreen Mode not supported!\n Switch to window mode?", "Error", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
					fullscreen = FALSE;
				else
					return FALSE;
			}
		}

	}

	DWORD dwExStyle;
	DWORD dwStyle;

	if (fullscreen){
		dwExStyle = WS_EX_APPWINDOW;
		dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
	}
	else{
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
	}

	RECT windowRect;
	if (fullscreen){
		windowRect.left = (long)0;
		windowRect.right = (long)screenWidth;
		windowRect.top = (long)0;
		windowRect.bottom = (long)screenHeight;
	} else {
		windowRect.left = (long)screenWidth / 2 - width / 2;
		windowRect.right = (long)width;
		windowRect.top = (long)screenHeight / 2 - height / 2;
		windowRect.bottom = (long)height;
	}

	AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle);

	std::string windowTitle = getWindowTitle();
	window = CreateWindowEx(0,
		name.c_str(),
		windowTitle.c_str(),
		dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
		windowRect.left,
		windowRect.top,
		windowRect.right,
		windowRect.bottom,
		NULL,
		NULL,
		hinstance,
		NULL);

	if (!window){
		printf("Could not create window!\n");
		fflush(stdout);
		return 0;
		exit(1);
	}

	ShowWindow(window, SW_SHOW);
	SetForegroundWindow(window);
	SetFocus(window);

	return window;
}
int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow)
{
  WNDCLASSEX wcex;
  MSG        Msg;
  HWND       hWnd;

  // Initialize the COM system
  CoInitialize(NULL);

  // Create the window class here and register it
  wcex.cbSize        = sizeof(wcex);
  wcex.style         = CS_CLASSDC;
  wcex.lpfnWndProc   = WindowProc;
  wcex.cbClsExtra    = 0;
  wcex.cbWndExtra    = 0;
  wcex.hInstance     = hInst;
  wcex.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
  wcex.hCursor       = LoadCursor(NULL, IDC_ARROW);
  wcex.hbrBackground = NULL;
  wcex.lpszMenuName  = NULL;
  wcex.lpszClassName = g_szClass;
  wcex.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
  if(!RegisterClassEx(&wcex))
    return FALSE;

  // Create the main window
  hWnd = CreateWindow(g_szClass, g_szCaption,
              WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
              0, 0, 640, 480,
              NULL, NULL, hInst, NULL);
  if(!hWnd)
    return FALSE;
  ShowWindow(hWnd, SW_NORMAL);
  UpdateWindow(hWnd);

  // Call init function and enter message pump
  if(DoInit(hWnd) == TRUE) {

    // Start message pump, waiting for user to exit
    ZeroMemory(&Msg, sizeof(MSG));
    while(Msg.message != WM_QUIT) {
      if(PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
      }

      // Render a single frame
      DoFrame();
    }
  }

  // Call shutdown
  DoShutdown();
 
  // Unregister the window class
  UnregisterClass(g_szClass, hInst);

  // Shut down the COM system
  CoUninitialize();

  return 0;
}
Beispiel #9
0
int WINAPI wWinMain ( HINSTANCE hInstance , HINSTANCE prevInstance , LPWSTR cmdLine , int cmdShow )
{
	UNREFERENCED_PARAMETER ( prevInstance );
	UNREFERENCED_PARAMETER ( cmdLine );

	WNDCLASSEX wndClass = { 0 };
	wndClass.cbSize = sizeof ( WNDCLASSEX );
	wndClass.style = CS_HREDRAW | CS_VREDRAW;
	wndClass.lpfnWndProc = WndProc;
	wndClass.hInstance = hInstance;
	wndClass.hCursor = LoadCursor ( NULL , IDC_ARROW );
	wndClass.hbrBackground = ( HBRUSH ) ( COLOR_WINDOW + 1 );
	wndClass.lpszMenuName = NULL;
	wndClass.lpszClassName = "DX11BookWindowClass";
	
	if( !RegisterClassEx( &wndClass ))
	{
		return -1;
	}

	RECT rc = { 0 , 0 , 640 , 480 };
	AdjustWindowRect( &rc , WS_OVERLAPPEDWINDOW , FALSE );

	HWND hwnd = CreateWindowEx ( WS_EX_OVERLAPPEDWINDOW, "DX11BookWindowClass" , "Blank Direct3D 11 Window" , WS_OVERLAPPEDWINDOW ,
		CW_USEDEFAULT , CW_USEDEFAULT , rc.right - rc.left , rc.bottom - rc.top , NULL , NULL , hInstance , NULL );

/*
	HWND hwnd = CreateWindowA ( "DX11BookWindowClass" , "Blank Direct 3D 11 Window" , WS_OVERLAPPEDWINDOW , CW_USEDEFAULT , CW_USEDEFAULT , rc.right - rc.left , 
		rc.bottom - rc.top , NULL , NULL , hInstance , NULL );
*/


	if( !hwnd )
		return -1;

	ShowWindow( hwnd , cmdShow );

	std :: auto_ptr< Dx11DemoBase >demo ( new ColorInversionDemo());


	//Demo Initialize
	bool result = demo ->Initialize ( hInstance , hwnd );

	//Error reporting if there is an issue 
	if( result == false )
		return -1;
	MSG msg = { 0 };

	while ( msg.message != WM_QUIT )
	{
		if( PeekMessage ( &msg , 0 , 0 , 0 , PM_REMOVE ))
		{
			TranslateMessage( & msg );
			DispatchMessage ( & msg );
		}
		else 
		{
			//Update and draw
			demo ->Update (0.0f);
			demo ->Render ( );
		}
	}

	//demo shutdown
	demo ->Shutdown( );

	return static_cast<int>( msg.wParam );


}
Beispiel #10
0
int APIENTRY
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
  WNDCLASS  wc;
  HWND      hwndFW;

	hInst = hInstance;
	LoadString(hInst, IDS_TITLE, szTitle, MAX_BUF);

  // Parse the command line
  ParseCommandLine(lpCmdLine);
  
  /*  Allow multiple installer instances with the 
      provision that each instance is guaranteed 
      to have its own unique setup directory 
   */
  if(FindWindow("NSExtracting", "Extracting...") != NULL ||
    (hwndFW = FindWindow(CLASS_NAME_SETUP_DLG, NULL)) != NULL ||
    (hwndFW = FindWindow(CLASS_NAME_SETUP, NULL)) != NULL)
  {
    if (gbAllowMultipleInstalls)
    {
      char szTempPath[MAX_BUF];
      GetFullTempPathName("", MAX_BUF, szTempPath);
      DWORD dwLen = lstrlen(gszWizTempDir);

      for(int i = 1; i <= 100 && (FileExists(szTempPath) != FALSE); i++)
      {
        itoa(i, (gszWizTempDir + dwLen), 10);
        GetFullTempPathName("", MAX_BUF, szTempPath);
      }

      if (FileExists(szTempPath) != FALSE)
      {
        MessageBox(NULL, "Cannot create temp directory", NULL, MB_OK | MB_ICONEXCLAMATION);
        exit(1);
      }
    }
    else
    {
      if (hwndFW!=NULL)
      {
        ShowWindow(hwndFW, SW_RESTORE);
        SetForegroundWindow(hwndFW);
      }
      return(1);
    }
  }

	// Figure out the total size of the resources
	EnumResourceNames(NULL, "FILE", (ENUMRESNAMEPROC)SizeOfResourcesProc, 0);

  // Register a class for the gauge
  memset(&wc, 0, sizeof(wc));
  wc.lpfnWndProc   = (WNDPROC)GaugeWndProc;
  wc.hInstance     = hInstance;
  wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
  wc.lpszClassName = "NSGauge";
  RegisterClass(&wc);

  // Register a class for the main dialog
  memset(&wc, 0, sizeof(wc));
  wc.style         = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
  wc.lpfnWndProc   = DefDlgProc;
  wc.cbClsExtra    = 0;
  wc.cbWndExtra    = DLGWINDOWEXTRA;
  wc.hInstance     = hInstance;
  wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
  wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  wc.lpszClassName = "NSExtracting";
  RegisterClass(&wc);

  if(dwMode != SILENT)
  {
	  // Display the dialog box
	  dlgInfo.hWndDlg = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_EXTRACTING), NULL, (DLGPROC)DialogProc);
	  UpdateWindow(dlgInfo.hWndDlg);
  }

	// Extract the files
	EnumResourceNames(NULL, "FILE", (ENUMRESNAMEPROC)ExtractFilesProc, 0);
	
	// Launch the install program and wait for it to finish
	RunInstaller();
	return 0;  
}
Beispiel #11
0
/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Full screen Mode				*
 *	height			- Height Of The GL Window Or Full screen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Full screen Mode (TRUE) Or Windowed Mode (FALSE)	*/
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullScreenFlag)
{
	GLuint		PixelFormat;				// Holds the results after searching for a match
	WNDCLASS	wc;							// Windows class structure
	DWORD		dwExStyle;					// Window extended style
	DWORD		dwStyle;					// Window style
	RECT		WindowRect;					// Grabs rectangle upper left/lower right values
	WindowRect.left		= (long)0;			// Set left value to 0
	WindowRect.right	= (long)width;		// Set right value to requested width
	WindowRect.top		= (long)0;			// Set top value to 0
	WindowRect.bottom	= (long)height;		// Set bottom value to requested height

	g_bFullscreen = fullScreenFlag;			// Set the global full screen flag

	hInstance			= GetModuleHandle(NULL);					// Grab an instance for out window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;		// Redraw on size, and own DC for window
	wc.lpfnWndProc		= (WNDPROC) WndProc;						// WndProc handles messages
	wc.cbClsExtra		= 0;										// No extra window data
	wc.cbWndExtra		= 0;										// No extra window data
	wc.hInstance		= hInstance;								// Set the instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);				// Load the default icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);				// Load the arrow pointer
	wc.hbrBackground	= NULL;										// No background required for GL
	wc.lpszMenuName		= NULL;										// We don't want a menu
	wc.lpszClassName	= CLASSNAME;								// Set the class name

	if (!RegisterClass(&wc))										// Attempt to register the window class
	{
		MessageBox(NULL, MSG_REGISTERCLASSFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}
	if (g_bFullscreen)
	{
		DEVMODE dmScreenSettings;									// Device mode
		memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));		// Makes sure memory's cleared
		dmScreenSettings.dmSize       = sizeof(dmScreenSettings);	// Size of the devmode structure
		dmScreenSettings.dmPelsWidth  = width;						// Selected screen width
		dmScreenSettings.dmPelsHeight = height;						// Selected screen height
		dmScreenSettings.dmBitsPerPel = bits;						// Selected bits per pixel
		dmScreenSettings.dmFields     = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
		// Try to set selected mode and get results. NOTE: CDS_FULLSCREEN gets rid of start bar.
		if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
		{
			// If the mode failed, offer two options. Quit or use windowed mode.
			if (MessageBox(NULL, MSG_FULLSCREENNOTSUPPORT,
				ARTIST_NAME, MB_YESNO|MB_ICONEXCLAMATION) == IDYES)
			{
				g_bFullscreen = FALSE;				// Windowed mode selected. Fullscreen = FALSE
			}
			else
			{
				// Pop up a message box letting user know the program is closing.
				MessageBox(NULL, MSG_PROGRAMNOTCLOSE,
					ERR_ERROR, MB_OK | MB_ICONSTOP);
				return FALSE;					// Return FALSE
			}
		}
	}
	if (g_bFullscreen)										// Are we still in fullscreen mode?
	{
		dwExStyle = WS_EX_APPWINDOW;					// Window extended style
		dwStyle   = WS_POPUP;							// Windows Style
		ShowCursor(FALSE);								// Hide mouse pointer
	}
	else
	{
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;	// Windows Extended style
		dwStyle   = WS_OVERLAPPEDWINDOW;				// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust window to true requested size
	// Create the window
	if (!(hWnd = CreateWindowEx(dwExStyle,							// Extended style for the window
		CLASSNAME,													// Class name
		title,														// Window title
		dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,				// Defined window style
		0, 0,														// Window position
		WindowRect.right - WindowRect.left,							// Calculate window width
		WindowRect.bottom - WindowRect.top,							// Calculate window height
		NULL,														// No parent window
		NULL,														// No menu
		hInstance,													// Instance
		NULL)))														// Don't pass anything to WM_CREATE
	{
		KillGLWindow();												// Reset the display
		MessageBox(NULL, MSG_CREATEWINDOWFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}
	static PIXELFORMATDESCRIPTOR pfd =								// pfd tells widows how we want things to be
	{
		sizeof(PIXELFORMATDESCRIPTOR),								// Size of this pixel format descriptor
		1,															// Version number
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,	// Format must support window/opengl/double buffering
		PFD_TYPE_RGBA,												// Request an RGBA format
		bits,														// Select our color depth
		0, 0, 0, 0, 0, 0,											// Color bits ignored
		0,															// No Alpha buffer
		0,															// Shift bit ignored
		0,															// No accumulation buffer
		0, 0, 0, 0,													// Accumulation bits ignored
		DEPTHBUFFER,												// 16bit z-buffer (depth buffer)
		0,															// No stencil buffer
		0,															// No auxiliary buffer
		PFD_MAIN_PLANE,												// Main drawing layer
		0,															// Reserved
		0, 0, 0														// Layer masks ignored
	};
	if (!(hDC = GetDC(hWnd)))										// Did we get a device context
	{
		KillGLWindow();												// Reset the display
		MessageBox(NULL, MSG_CREATEGLDCFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}
	if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))				// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();												// Reset The Display
		MessageBox(NULL, MSG_FINDPIXELFORMATFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat, &pfd))						// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();												// Reset The Display
		MessageBox(NULL, MSG_SETPIXELFORMATFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))								// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();												// Reset The Display
		MessageBox(NULL, MSG_CREATEGLRCFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))									// Try To Activate The Rendering Context
	{
		KillGLWindow();												// Reset The Display
		MessageBox(NULL, MSG_ACTIVEGLRCFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);										// Show The Window
	SetForegroundWindow(hWnd);										// Slightly Higher Priority
	SetFocus(hWnd);													// Sets Keyboard Focus To The Window
	ReSizeGLScene(width, height);									// Set Up Our Perspective GL Screen

	if (!InitGL())													// Initialize Our Newly Created GL Window
	{
		KillGLWindow();												// Reset The Display
		MessageBox(NULL, MSG_INITFAILED, 
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}
Beispiel #12
0
void DoMain (HINSTANCE hInstance)
{
	LONG WinWidth, WinHeight;
	int height, width, x, y;
	RECT cRect;
	TIMECAPS tc;
	DEVMODE displaysettings;

	try
	{
#ifdef _MSC_VER
		_set_new_handler (NewFailure);
#endif

		Args = new DArgs(__argc, __argv);

		// Under XP, get our session ID so we can know when the user changes/locks sessions.
		// Since we need to remain binary compatible with older versions of Windows, we
		// need to extract the ProcessIdToSessionId function from kernel32.dll manually.
		HMODULE kernel = GetModuleHandle ("kernel32.dll");

		if (Args->CheckParm("-stdout"))
		{
			// As a GUI application, we don't normally get a console when we start.
			// If we were run from the shell and are on XP+, we can attach to its
			// console. Otherwise, we can create a new one. If we already have a
			// stdout handle, then we have been redirected and should just use that
			// handle instead of creating a console window.

			StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
			if (StdOut != NULL)
			{
				// It seems that running from a shell always creates a std output
				// for us, even if it doesn't go anywhere. (Running from Explorer
				// does not.) If we can get file information for this handle, it's
				// a file or pipe, so use it. Otherwise, pretend it wasn't there
				// and find a console to use instead.
				BY_HANDLE_FILE_INFORMATION info;
				if (!GetFileInformationByHandle(StdOut, &info))
				{
					StdOut = NULL;
				}
			}
			if (StdOut == NULL)
			{
				// AttachConsole was introduced with Windows XP. (OTOH, since we
				// have to share the console with the shell, I'm not sure if it's
				// a good idea to actually attach to it.)
				typedef BOOL (WINAPI *ac)(DWORD);
				ac attach_console = kernel != NULL ? (ac)GetProcAddress(kernel, "AttachConsole") : NULL;
				if (attach_console != NULL && attach_console(ATTACH_PARENT_PROCESS))
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
					DWORD foo; WriteFile(StdOut, "\n", 1, &foo, NULL);
					AttachedStdOut = true;
				}
				if (StdOut == NULL && AllocConsole())
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
				}
				FancyStdOut = true;
			}
		}

		// Set the timer to be as accurate as possible
		if (timeGetDevCaps (&tc, sizeof(tc)) != TIMERR_NOERROR)
			TimerPeriod = 1;	// Assume minimum resolution of 1 ms
		else
			TimerPeriod = tc.wPeriodMin;

		timeBeginPeriod (TimerPeriod);

		/*
		killough 1/98:

		This fixes some problems with exit handling
		during abnormal situations.

		The old code called I_Quit() to end program,
		while now I_Quit() is installed as an exit
		handler and exit() is called to exit, either
		normally or abnormally.
		*/

		atexit (call_terms);

		atterm (I_Quit);

		// Figure out what directory the program resides in.
		char *program;

#ifdef _MSC_VER
		if (_get_pgmptr(&program) != 0)
		{
			I_FatalError("Could not determine program location.");
		}
#else
		char progbuff[1024];
		GetModuleFileName(0, progbuff, sizeof(progbuff));
		progbuff[1023] = '\0';
		program = progbuff;
#endif

		progdir = program;
		program = progdir.LockBuffer();
		*(strrchr(program, '\\') + 1) = '\0';
		FixPathSeperator(program);
		progdir.Truncate((long)strlen(program));
		progdir.UnlockBuffer();
/*
		height = GetSystemMetrics (SM_CYFIXEDFRAME) * 2 +
				GetSystemMetrics (SM_CYCAPTION) + 12 * 32;
		width  = GetSystemMetrics (SM_CXFIXEDFRAME) * 2 + 8 * 78;
*/
		width = 512;
		height = 384;

		// Many Windows structures that specify their size do so with the first
		// element. DEVMODE is not one of those structures.
		memset (&displaysettings, 0, sizeof(displaysettings));
		displaysettings.dmSize = sizeof(displaysettings);
		EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &displaysettings);
		x = (displaysettings.dmPelsWidth - width) / 2;
		y = (displaysettings.dmPelsHeight - height) / 2;

		if (Args->CheckParm ("-0"))
		{
			x = y = 0;
		}

		WNDCLASS WndClass;
		WndClass.style			= 0;
		WndClass.lpfnWndProc	= LConProc;
		WndClass.cbClsExtra		= 0;
		WndClass.cbWndExtra		= 0;
		WndClass.hInstance		= hInstance;
		WndClass.hIcon			= LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1));
		WndClass.hCursor		= LoadCursor (NULL, IDC_ARROW);
		WndClass.hbrBackground	= NULL;
		WndClass.lpszMenuName	= NULL;
		WndClass.lpszClassName	= (LPCTSTR)WinClassName;
		
		/* register this new class with Windows */
		if (!RegisterClass((LPWNDCLASS)&WndClass))
			I_FatalError ("Could not register window class");
		
		/* create window */
		char caption[100];
		mysnprintf(caption, countof(caption), ""GAMESIG" %s "X64, GetVersionString());
		Window = CreateWindowEx(
				WS_EX_APPWINDOW,
				(LPCTSTR)WinClassName,
				(LPCTSTR)caption,
				WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN,
				x, y, width, height,
				(HWND)   NULL,
				(HMENU)  NULL,
						hInstance,
				NULL);

		if (!Window)
			I_FatalError ("Could not open window");

		if (kernel != NULL)
		{
			typedef BOOL (WINAPI *pts)(DWORD, DWORD *);
			pts pidsid = (pts)GetProcAddress (kernel, "ProcessIdToSessionId");
			if (pidsid != 0)
			{
				if (!pidsid (GetCurrentProcessId(), &SessionID))
				{
					SessionID = 0;
				}
				hwtsapi32 = LoadLibraryA ("wtsapi32.dll");
				if (hwtsapi32 != 0)
				{
					FARPROC reg = GetProcAddress (hwtsapi32, "WTSRegisterSessionNotification");
					if (reg == 0 || !((BOOL(WINAPI *)(HWND, DWORD))reg) (Window, NOTIFY_FOR_THIS_SESSION))
					{
						FreeLibrary (hwtsapi32);
						hwtsapi32 = 0;
					}
					else
					{
						atterm (UnWTS);
					}
				}
			}
		}

		GetClientRect (Window, &cRect);

		WinWidth = cRect.right;
		WinHeight = cRect.bottom;

		CoInitialize (NULL);
		atterm (UnCOM);

		C_InitConsole (((WinWidth / 8) + 2) * 8, (WinHeight / 12) * 8, false);

		I_DetectOS ();
		D_DoomMain ();
	}
	catch (class CNoRunExit &)
	{
		I_ShutdownGraphics();
		if (FancyStdOut && !AttachedStdOut)
		{ // Outputting to a new console window: Wait for a keypress before quitting.
			DWORD bytes;
			HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE);

			ShowWindow (Window, SW_HIDE);
			WriteFile(StdOut, "Press any key to exit...", 24, &bytes, NULL);
			FlushConsoleInputBuffer(stdinput);
			SetConsoleMode(stdinput, 0);
			ReadConsole(stdinput, &bytes, 1, &bytes, NULL);
		}
		else if (StdOut == NULL)
		{
			ShowErrorPane(NULL);
		}
		exit(0);
	}
	catch (class CDoomError &error)
	{
		I_ShutdownGraphics ();
		RestoreConView ();
		if (error.GetMessage ())
		{
			ShowErrorPane (error.GetMessage());
		}
		exit (-1);
	}
}
Beispiel #13
0
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) {
	
	MyDirectX = new DirectX();
	WNDCLASSEX wndClass;

	wndClass.cbSize = sizeof( WNDCLASSEX );
	wndClass.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
	wndClass.cbClsExtra = 0;
	wndClass.cbWndExtra = 0;
	wndClass.hbrBackground = ( HBRUSH )GetStockObject( BLACK_BRUSH );
	wndClass.hInstance = hInstance;
	wndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION );
	wndClass.hIconSm = LoadIcon( NULL, IDI_WINLOGO );
	wndClass.hCursor = LoadCursor( NULL, IDC_ARROW );
	wndClass.lpfnWndProc = ( WNDPROC )WndProc;
	wndClass.lpszClassName = "MainWndClass";
	wndClass.lpszMenuName = ( LPCSTR )NULL;

	if( !RegisterClassEx( &wndClass ) ) {
		MessageBox( HWND_DESKTOP, "Cannot register the main window\nclass.", "Error", MB_OK | MB_ICONERROR );
		return 0;
	}

	HWND hWndMain = CreateWindowEx(
		WS_EX_STATICEDGE,
		"MainWndClass",
		"DirectX Tutorial #1",
		WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		800, 600,
		HWND_DESKTOP,
		( HMENU )NULL,
		( HINSTANCE )hInstance,
		( LPVOID* )NULL
	);

	if( !hWndMain ) {
		MessageBox( HWND_DESKTOP, "Cannot create the main window.", "Error", MB_OK | MB_ICONERROR );
		UnregisterClass( "MainWndClass", hInstance );
		return 0;
	}

	ShowWindow( hWndMain, SW_SHOWNORMAL );
	UpdateWindow( hWndMain );

	MyDirectX->Init( hWndMain );

	MSG msg = {0};

	while( msg.message != WM_QUIT ) {
		
		if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}

		// Do game rendering/updating here
		MyDirectX->Render( );

	}

	MyDirectX->CleanDirectX( );
	delete [] MyDirectX;
	UnregisterClass( "MainWndClass", hInstance );
	return 0;

}
Beispiel #14
0
int APIENTRY _tWinMain(HINSTANCE hinst,	HINSTANCE foo1, LPTSTR foo2, int foo3) {
	MSG msg;
	WNDCLASSEX wcex = {sizeof(wcex)};
	HANDLE htray;
	HMENU hmenu;
	MENUITEMINFO mi = {sizeof(mi)};
	INITCOMMONCONTROLSEX icex;
	RECT rect;
	int style;
	HWND hwnd;

	wcex.lpfnWndProc = WndProc;
	wcex.lpszClassName = WINDOW_CLASS;
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	RegisterClassEx(&wcex);

	icex.dwSize = sizeof(icex);
	icex.dwICC = ICC_DATE_CLASSES;
	InitCommonControlsEx(&icex);

	hwnd = CreateWindowEx(WS_EX_NOACTIVATE | WS_EX_TOPMOST, WINDOW_CLASS, WINDOW_TITLE, 0,
		0, 0, 0, 0, NULL, NULL, hinst, NULL);
	if (!hwnd) return 1;
	style = GetWindowLong(hwnd, GWL_STYLE);
	if (style & WS_CAPTION)  { 
		style ^= WS_CAPTION;
		SetWindowLong(hwnd, GWL_STYLE, style);
		SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
	}

	hcal = CreateWindowEx(0, MONTHCAL_CLASS, _T(""),
		WS_CHILD | WS_VISIBLE | MCS_NOTODAY | MCS_NOTRAILINGDATES | MCS_SHORTDAYSOFWEEK | MCS_NOSELCHANGEONNAV,
		0, 0, 0, 0, hwnd, NULL, hinst, NULL);
	MonthCal_GetMinReqRect(hcal, &rect);
	SetWindowPos(hcal, NULL, 0, 0, rect.right, rect.bottom, SWP_NOZORDER | SWP_NOMOVE);
	SetWindowPos(hwnd, NULL, 0, 0, rect.right, rect.bottom, SWP_NOZORDER | SWP_NOMOVE);

	tti.hwnd = hwnd;
	tti.hcal = hcal;
	tti.hnotify = CreateEvent(NULL, TRUE, FALSE, NULL);
	tti.exit = FALSE;
	htray = CreateThread(NULL, 0, &TrayThreadProc, &tti, 0, NULL);
	if (!htray) return 1;

	hsubmenu = CreateMenu();
	mi.fMask = MIIM_STRING | MIIM_ID;
	mi.wID = 1;
	mi.dwTypeData = EXIT_STRING;
	InsertMenuItem(hsubmenu, 0, TRUE, &mi);
	hmenu = CreateMenu();
	mi.fMask = MIIM_SUBMENU;
	mi.hSubMenu = hsubmenu;
	InsertMenuItem(hmenu, 0, TRUE, &mi);

	WM_TASKBARCREATED = RegisterWindowMessageA(_T("TaskbarCreated"));
	
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	DestroyMenu(hmenu);
	DestroyMenu(hsubmenu);

	WaitForSingleObject(htray, 1000);
	CloseHandle(htray);

	return (int)msg.wParam;
}
void Sys_BeginWait(void) {
	waitcursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
}
Beispiel #16
0
/////////////////////////////////////////////////////////
// createGemWindow
//
/////////////////////////////////////////////////////////
GEM_EXTERN int createGemWindow(WindowInfo &info, WindowHints &hints)
{
  static int firstTime = 1;

  // Register the frame class
  HINSTANCE hInstance = GetModuleHandle(NULL);
  if (!hInstance) {
    error("GEM: Unable to get module instance");
    return(0);
  }
  if (firstTime) {
    WNDCLASS wndclass;
    wndclass.style         = 0;
    wndclass.lpfnWndProc   = (WNDPROC)MainWndProc;
    wndclass.cbClsExtra    = 0;
    wndclass.cbWndExtra    = 0;
    wndclass.hInstance     = hInstance;
    wndclass.hCursor       = LoadCursor(NULL, IDC_CROSS);
    wndclass.hIcon         = LoadIcon(NULL, IDI_WINLOGO);
    wndclass.hbrBackground = NULL;
    wndclass.lpszMenuName  = NULL;
    wndclass.lpszClassName = "GEM";

    if (!RegisterClass(&wndclass) ) {
      error("GEM: Unable to register window class");
      return(0);
    }
    firstTime = 0;
  }

  DWORD dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  DWORD style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;

  hints.real_w = hints.width;
  hints.real_h = hints.height;

  int x = hints.x_offset;
  int y = hints.y_offset;

  bool fullscreen=(hints.fullscreen!=0);
  if (fullscreen) {
    DEVMODE dmScreenSettings;                                                           // Device Mode

    if (!EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmScreenSettings)) {
      error("GEM: couldn't get screen capabilities!");
    }
    int w = dmScreenSettings.dmPelsWidth;
    int h = dmScreenSettings.dmPelsHeight;

    x=y=0;

    memset(&dmScreenSettings,0,
           sizeof(dmScreenSettings));       // Makes Sure Memory's Cleared
    dmScreenSettings.dmSize=sizeof(
                              dmScreenSettings);           // Size Of The Devmode Structure
    dmScreenSettings.dmPelsWidth        =
      hints.width;                  // Selected Screen Width
    dmScreenSettings.dmPelsHeight       =
      hints.height;                 // Selected Screen Height
    dmScreenSettings.dmBitsPerPel       =
      32;                                   // Selected Bits Per Pixel
    dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
    // Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
    if (ChangeDisplaySettings(&dmScreenSettings,
                              CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) {
      dmScreenSettings.dmPelsWidth      = w;
      dmScreenSettings.dmPelsHeight     = h;
      if (ChangeDisplaySettings(&dmScreenSettings,
                                CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) {
        error("GEM: couldn't switch to fullscreen");
        fullscreen=false;
      } else {
        hints.real_h=h;
        hints.real_w=w;
      }
    }
  }
  if (fullscreen) {
    dwExStyle  = WS_EX_APPWINDOW;
    style     |= WS_POPUP;
  } else {
    dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
    if (hints.border) {
      style |= WS_OVERLAPPEDWINDOW;
    } else {
      style |= WS_POPUP;
    }
  }

  info.fs = fullscreen;//hints.fullscreen;

  // Since Windows uses some of the window for the border, etc,
  //            we have to ask how big the window should really be
  RECT newSize;
  newSize.left = x;
  newSize.top = y;
  newSize.right = hints.real_w+x;
  newSize.bottom = hints.real_h+y;

  AdjustWindowRectEx(&newSize, style, FALSE, dwExStyle); // no menu

  if (newSize.left<0 && x>=0) {
    newSize.right-=newSize.left;
    newSize.left=0;
  }
  if (newSize.top<0 && y>=0) {
    newSize.bottom-=newSize.top;
    newSize.top=0;
  }

  // Create the window
  info.win = CreateWindowEx (
               dwExStyle,
               "GEM",
               hints.title,
               style,
               newSize.left,
               newSize.top,
               newSize.right - newSize.left,
               newSize.bottom - newSize.top,
               NULL,
               NULL,
               hInstance,
               NULL);

  if (!info.win)  {
    error("GEM: Unable to create window");
    return(0);
  }

  // create the device context
  info.dc = GetDC(info.win);
  if (!info.dc)  {
    error("GEM: Unable to create device context");
    destroyGemWindow(info);
    return(0);
  }

  // set the pixel format for the window
  if (!bSetupPixelFormat(info.dc, hints))  {
    error("GEM: Unable to set window pixel format");
    destroyGemWindow(info);
    return(0);
  }

  // create the OpenGL context
  info.context = wglCreateContext(info.dc);
  if (!info.context)  {
    error("GEM: Unable to create OpenGL context");
    destroyGemWindow(info);
    return(0);
  }

  // do we share display lists?
  if (hints.shared) {
    wglShareLists(hints.shared, info.context);
  }

  // make the context the current rendering context
  if (!wglMakeCurrent(info.dc, info.context))   {
    error("GEM: Unable to make OpenGL context current");
    destroyGemWindow(info);
    return(0);
  }

  if (!hints.actuallyDisplay) {
    return(1);
  }

  // show and update main window
  if (fullscreen) {
    ShowWindow(info.win,
               SW_SHOW);                               // Show The Window
    SetForegroundWindow(
      info.win);                              // Slightly Higher Priority
    SetFocus(info.win);
  } else {
    ShowWindow(info.win, SW_SHOWNORMAL);
  }

  UpdateWindow(info.win);

  return(1);
}
// WinMain
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int cmdShow){
	argv =CommandLineToArgvW(GetCommandLineW(),&argc);

	directory = getDirectory();
	srand(time(0));
#ifdef _DEBUG
	console();
#endif
	loadSaves();
	int height=768,width =1024;
	calcSizes(768-menuHeight,1024-border);

	WNDCLASSEX wc;

	//HDC hDC;
	HGLRC hRC;

	// register window class
	//definere et vindues classe og dens parametre/udsende
	wc.cbSize		 = sizeof(WNDCLASSEX);
	wc.style = 0;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	//alt tab icon + windows linie icon
	wc.hIcon = LoadIcon( GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1) );
	//look of the cursor
	wc.hCursor = LoadCursor( NULL, IDC_ARROW );
	//background color
	wc.hbrBackground = (HBRUSH)GetSysColorBrush(COLOR_3DFACE);
	//menu bar
	wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
	wc.lpszClassName = "main";
	//icon venstre top hjørne
	//følgende virker også, loader dog default 32x32 icon
	//LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
	wc.hIconSm		 = (HICON)LoadImage(GetModuleHandle(NULL),MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, 16, 16, 0);
	if(!RegisterClassEx(&wc)){
		MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
		return 0;
	}

	// create main window
	hWnd = CreateWindowEx( WS_EX_CLIENTEDGE,
		"main", "Walking With Dinosaurs",
		WS_THICKFRAME | WS_CAPTION | WS_VISIBLE | WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX |WS_CLIPCHILDREN |WS_MAXIMIZEBOX,
		GetSystemMetrics(SM_CXMAXIMIZED)/2-SM_CXFIXEDFRAME/2-width/2-listWidth, GetSystemMetrics(SM_CYMAXIMIZED)/2-SM_CYFIXEDFRAME/2-height/2, 1024, 768,
		NULL, NULL, hInstance, NULL );

	//simulations window
	// register window class
	wc.cbSize		 = sizeof(WNDCLASSEX);
	//cs_owndc svaes the cach, used for painting outside normal routine
	wc.style = CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
	wc.hCursor = LoadCursor( NULL, IDC_ARROW );
	wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "blank";
	if(!RegisterClassEx(&wc)){
		MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
		return 0;
	}

	blank = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("blank"), "", WS_CHILD | WS_VISIBLE ,listWidth,bAreaHeight,simWidth,simHeight, hWnd,(HMENU)IDC_SIM, GetModuleHandle(NULL), NULL);

	EnableOpenGL( blank, &hDC, &hRC );

	//selection listbox
	hWndList = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("listbox"), "", WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_AUTOVSCROLL|LBS_NOTIFY,0, 0, listWidth, listHeight, hWnd,  (HMENU)IDC_LISTBOX, GetModuleHandle(NULL), NULL);
	for(int i=0;i<(int)saves.size();i++){
		SendMessage(hWndList, LB_ADDSTRING, 0, (LPARAM)saves.at(i)->name.c_str());
	}
	SendMessage(hWndList,LB_SETCURSEL,0,0);

	//init creature/world
	WWDPhysics = new Physics();
	readDNA(&saves.at(0)->dna,WWDPhysics);
	WWDPhysics->runSimStartUp();
	WWDPhysics->reshape(simWidth,simHeight);

	//settings area
	int row1=10,row2=35, row3 =60;
	int col1 =160,col2=col1+170,col3=500,col4=col3+170, col5=340,col6=col5+170;
	HWND hWndFitS=CreateWindowEx(NULL,TEXT("STATIC"),	"Fitness Test",WS_CHILD|WS_VISIBLE,	col1, row1, 100, 18, hWnd, (HMENU)IDC_TEST_STATIC, GetModuleHandle(NULL),	NULL);
	HWND hwndCombo = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("combobox"), "", WS_CHILD | WS_VISIBLE| CBS_DROPDOWNLIST ,col2, row1-5, 150, 24, hWnd,  (HMENU)IDC_FITNESSTYPE_COMBOBOX, GetModuleHandle(NULL), NULL);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"Move");
	SendMessage(hwndCombo,CB_SETITEMDATA, 0, move);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"Iterative Move");
	SendMessage(hwndCombo,CB_SETITEMDATA, 1, iterateMove);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"Dwarfslayer Move");
	SendMessage(hwndCombo,CB_SETITEMDATA, 2, dwarfslayerMove);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"Fat Loving Move");
	SendMessage(hwndCombo,CB_SETITEMDATA, 3, fatLovingMove);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"Box Loving Move");
	SendMessage(hwndCombo,CB_SETITEMDATA, 4, boxLovingMove);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"Jump");
	SendMessage(hwndCombo,CB_SETITEMDATA, 5, jump);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"Combi");
	SendMessage(hwndCombo,CB_SETITEMDATA, 6, combi);

	SendMessage(hwndCombo,CB_ADDSTRING, 0, (LPARAM)"None");
	SendMessage(hwndCombo,CB_SETITEMDATA, 7, none);

	SendMessage(hwndCombo,CB_SETCURSEL,0,0);
	WWDPhysics->addFitnessFunction(move,1);

	HWND hWndButton=CreateWindowEx(NULL,TEXT("BUTTON"),	"RUN", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON,
		col1, row3, 100, 24,
		hWnd, (HMENU)IDC_RUN_BUTTON, GetModuleHandle(NULL),	NULL);

	HWND hWndResetButton=CreateWindowEx(NULL,TEXT("BUTTON"),	"Reset Simulation", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON,
		col3, row3, 150, 24,
		hWnd, (HMENU)IDC_RESET_BUTTON, GetModuleHandle(NULL),	NULL);

	HGDIOBJ hfDefault=GetStockObject(DEFAULT_GUI_FONT);
	SendMessage(hWndButton,WM_SETFONT, (WPARAM)hfDefault, MAKELPARAM(FALSE,0));

	HWND hWndNoG=CreateWindowEx(NULL,TEXT("STATIC"),"Number of Generations",WS_CHILD|WS_VISIBLE,	col1, row2, 150, 18,
		hWnd, (HMENU)IDC_NOG_STATIC, GetModuleHandle(NULL),	NULL);

	HWND hWndNoGS=CreateWindowEx(NULL,TEXT("EDIT"),	"50",WS_CHILD|WS_VISIBLE|ES_NUMBER,	col2, row2, 42, 18,
		hWnd, (HMENU)IDC_NOG_EDIT, GetModuleHandle(NULL),	NULL);

	HWND hWndPopS=CreateWindowEx(NULL,TEXT("STATIC"),	"Population Size",WS_CHILD|WS_VISIBLE,	col3, row1, 150, 18,
		hWnd, (HMENU)IDC_POP_STATIC, GetModuleHandle(NULL),	NULL);
	HWND hWndPop=CreateWindowEx(NULL,TEXT("EDIT"),	"100",WS_CHILD|WS_VISIBLE |ES_NUMBER,	col4, row1, 42, 18,
		hWnd, (HMENU)IDC_POP_EDIT, GetModuleHandle(NULL),	NULL);

	HWND hWndViewRate=CreateWindowEx(NULL,TEXT("STATIC"),	"Simulation view precision",WS_CHILD|WS_VISIBLE,	col3, row2, 200, 18,
		hWnd, (HMENU)IDC_VIEW_STATIC, GetModuleHandle(NULL),	NULL);

	HWND hWndViewRateB=CreateWindowEx(NULL,TEXT("BUTTON"),	"",WS_CHILD|WS_VISIBLE | BS_CHECKBOX,	col4, row2, 100, 18,
		hWnd, (HMENU)IDC_VIEW_CHECKBOX, GetModuleHandle(NULL),	NULL);
	SendMessage(hWndViewRateB, BM_SETCHECK, BST_CHECKED,0);
	fixedSteps=true;
	EnableWindow(hWndViewRateB,false);


	MSG msg = messageLoop(hDC, hRC);
	return msg.wParam;
}
INT WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR szCmdLine, int iCmdShow)
{
	WNDCLASSEX winClass ;

	winClass.lpszClassName = "Vertex Alpha";
	winClass.cbSize        = sizeof(WNDCLASSEX);
	winClass.style         = CS_HREDRAW | CS_VREDRAW;
	winClass.lpfnWndProc   = MsgProc;
	winClass.hInstance     = hInstance;
	winClass.hIcon	       = NULL ;
	winClass.hIconSm	   = NULL ;
	winClass.hCursor       = LoadCursor(NULL, IDC_ARROW) ;
	winClass.hbrBackground = NULL ;
	winClass.lpszMenuName  = NULL ;
	winClass.cbClsExtra    = 0;
	winClass.cbWndExtra    = 0;

	RegisterClassEx (&winClass) ;  

	HWND hWnd = CreateWindowEx(NULL,  
		winClass.lpszClassName,		// window class name
		"Vertex Alpha",					// window caption
		WS_OVERLAPPEDWINDOW, 		// window style
		32,							// initial x position
		32,							// initial y position
		600,						// initial window width
		600,						// initial window height
		NULL,						// parent window handle
		NULL,						// window menu handle
		hInstance,					// program instance handle
		NULL) ;						// creation parameters

	// Create window failed
	if(hWnd == NULL)
	{
		MessageBoxA(hWnd, "Create Window failed!", "Error", 0) ;
		return -1 ;
	}

	// Initialize Direct3D
	if( SUCCEEDED(InitD3D(hWnd)))
	{ 
		// Show the window
		ShowWindow( hWnd, SW_SHOWDEFAULT );
		UpdateWindow( hWnd );

		MSG msg ; 
		ZeroMemory( &msg, sizeof(msg) );
		PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );

		// Get last time
		static DWORD lastTime = timeGetTime();

		while (msg.message != WM_QUIT)  
		{
			if(PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0)
			{
				TranslateMessage (&msg) ;
				DispatchMessage (&msg) ;
			}
			else // Render the game if there is no message to process
			{
				// Get current time
				DWORD currTime  = timeGetTime();

				// Calculate time elapsed
				float timeDelta = (currTime - lastTime) * 0.001f;

				// Render
				Render() ;

				// Update last time to current time for next loop
				lastTime = currTime;
			}
		}
	}

	UnregisterClass(winClass.lpszClassName, hInstance) ;
	return 0;
}
Beispiel #19
0
int
puglCreateWindow(PuglView* view, const char* title)
{
	PuglInternals* impl = view->impl;

	if (!title) {
		title = "Window";
	}

	// FIXME: This is nasty, and pugl should not have static anything.
	// Should class be a parameter?  Does this make sense on other platforms?
	static int wc_count = 0;
	char classNameBuf[256];
	_snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d\n", title, wc_count++);

	impl->wc.style         = CS_OWNDC;
	impl->wc.lpfnWndProc   = wndProc;
	impl->wc.cbClsExtra    = 0;
	impl->wc.cbWndExtra    = 0;
	impl->wc.hInstance     = 0;
	impl->wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	impl->wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
	impl->wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	impl->wc.lpszMenuName  = NULL;
	impl->wc.lpszClassName = classNameBuf;
	RegisterClass(&impl->wc);

	int winFlags = WS_POPUPWINDOW | WS_CAPTION;
	if (view->resizable) {
		winFlags |= WS_SIZEBOX;
	}

	// Adjust the overall window size to accomodate our requested client size
	RECT wr = { 0, 0, view->width, view->height };
	AdjustWindowRectEx(&wr, winFlags, FALSE, WS_EX_TOPMOST);

	impl->hwnd = CreateWindowEx(
		WS_EX_TOPMOST,
 		classNameBuf, title,
		(view->parent ? WS_CHILD : winFlags),
		CW_USEDEFAULT, CW_USEDEFAULT, wr.right-wr.left, wr.bottom-wr.top,
		(HWND)view->parent, NULL, NULL, NULL);

	if (!impl->hwnd) {
		free(impl);
		free(view);
		return 1;
	}
		
#ifdef _WIN64
	SetWindowLongPtr(impl->hwnd, GWLP_USERDATA, (LONG_PTR)view);
#else
 	SetWindowLongPtr(impl->hwnd, GWL_USERDATA, (LONG)view);
#endif

	impl->hdc = GetDC(impl->hwnd);

	PIXELFORMATDESCRIPTOR pfd;
	ZeroMemory(&pfd, sizeof(pfd));
	pfd.nSize      = sizeof(pfd);
	pfd.nVersion   = 1;
	pfd.dwFlags    = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = 24;
	pfd.cDepthBits = 16;
	pfd.iLayerType = PFD_MAIN_PLANE;

	int format = ChoosePixelFormat(impl->hdc, &pfd);
	SetPixelFormat(impl->hdc, format, &pfd);

	impl->hglrc = wglCreateContext(impl->hdc);
	wglMakeCurrent(impl->hdc, impl->hglrc);

	return 0;
}
Beispiel #20
0
/*
================
Con_CreateConsole

create win32 console
================
*/
void Con_CreateConsole( void )
{
#ifdef _WIN32
	HDC	hDC;
	WNDCLASS	wc;
	RECT	rect;
	int	nHeight;
	int	swidth, sheight, fontsize;
	int	DEDSTYLE = WS_POPUPWINDOW | WS_CAPTION;
	int	CONSTYLE = WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_BORDER|WS_EX_CLIENTEDGE|ES_LEFT|ES_MULTILINE|ES_AUTOVSCROLL|ES_READONLY;
	string	FontName;

	wc.style         = 0;
	wc.lpfnWndProc   = (WNDPROC)Con_WndProc;
	wc.cbClsExtra    = 0;
	wc.cbWndExtra    = 0;
	wc.hInstance     = host.hInst;
	wc.hIcon         = LoadIcon( host.hInst, MAKEINTRESOURCE( IDI_ICON1 ));
	wc.hCursor       = LoadCursor( NULL, IDC_ARROW );
	wc.hbrBackground = (void *)COLOR_3DSHADOW;
	wc.lpszClassName = SYSCONSOLE;
	wc.lpszMenuName  = 0;

	if( Sys_CheckParm( "-log" ) && host.developer != 0 )
		s_wcd.log_active = true;

	if( host.type == HOST_NORMAL )
	{
		rect.left = 0;
		rect.right = 536;
		rect.top = 0;
		rect.bottom = 364;
		Q_strncpy( FontName, "Fixedsys", sizeof( FontName ));
		Q_strncpy( s_wcd.title, va( "Xash3D %g", XASH_VERSION ), sizeof( s_wcd.title ));
		Q_strncpy( s_wcd.log_path, "engine.log", sizeof( s_wcd.log_path ));
		fontsize = 8;
	}
	else // dedicated console
	{
		rect.left = 0;
		rect.right = 640;
		rect.top = 0;
		rect.bottom = 392;
		Q_strncpy( FontName, "System", sizeof( FontName ));
		Q_strncpy( s_wcd.title, "Xash Dedicated Server", sizeof( s_wcd.title ));
		Q_strncpy( s_wcd.log_path, "dedicated.log", sizeof( s_wcd.log_path ));
		s_wcd.log_active = true; // always make log
		fontsize = 14;
	}

	Sys_InitLog();
	if( !RegisterClass( &wc ))
	{
		// print into log
		MsgDev( D_ERROR, "Can't register window class '%s'\n", SYSCONSOLE );
		return;
	} 

	AdjustWindowRect( &rect, DEDSTYLE, FALSE );

	hDC = GetDC( GetDesktopWindow() );
	swidth = GetDeviceCaps( hDC, HORZRES );
	sheight = GetDeviceCaps( hDC, VERTRES );
	ReleaseDC( GetDesktopWindow(), hDC );

	s_wcd.windowWidth = rect.right - rect.left;
	s_wcd.windowHeight = rect.bottom - rect.top;

	s_wcd.hWnd = CreateWindowEx( WS_EX_DLGMODALFRAME, SYSCONSOLE, s_wcd.title, DEDSTYLE, ( swidth - 600 ) / 2, ( sheight - 450 ) / 2 , rect.right - rect.left + 1, rect.bottom - rect.top + 1, NULL, NULL, host.hInst, NULL );
	if( s_wcd.hWnd == NULL )
	{
		MsgDev( D_ERROR, "Can't create window '%s'\n", s_wcd.title );
		return;
	}

	// create fonts
	hDC = GetDC( s_wcd.hWnd );
	nHeight = -MulDiv( fontsize, GetDeviceCaps( hDC, LOGPIXELSY ), 72 );
	s_wcd.hfBufferFont = CreateFont( nHeight, 0, 0, 0, FW_LIGHT, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_MODERN|FIXED_PITCH, FontName );
	ReleaseDC( s_wcd.hWnd, hDC );

	if( host.type == HOST_DEDICATED )
	{
		// create the input line
		s_wcd.hwndInputLine = CreateWindowEx( WS_EX_CLIENTEDGE, "edit", NULL, WS_CHILD|WS_VISIBLE|WS_BORDER|ES_LEFT|ES_AUTOHSCROLL, 0, 366, 550, 25, s_wcd.hWnd, (HMENU)INPUT_ID, host.hInst, NULL );

		s_wcd.hwndButtonSubmit = CreateWindow( "button", NULL, BS_PUSHBUTTON|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 552, 367, 87, 25, s_wcd.hWnd, (HMENU)SUBMIT_ID, host.hInst, NULL );
		SendMessage( s_wcd.hwndButtonSubmit, WM_SETTEXT, 0, ( LPARAM ) "submit" );
          }
          
	// create the scrollbuffer
	GetClientRect( s_wcd.hWnd, &rect );

	s_wcd.hwndBuffer = CreateWindowEx( WS_EX_DLGMODALFRAME|WS_EX_CLIENTEDGE, "edit", NULL, CONSTYLE, 0, 0, rect.right - rect.left, min(365, rect.bottom), s_wcd.hWnd, (HMENU)EDIT_ID, host.hInst, NULL );
	SendMessage( s_wcd.hwndBuffer, WM_SETFONT, (WPARAM)s_wcd.hfBufferFont, 0 );

	if( host.type == HOST_DEDICATED )
	{
		s_wcd.SysInputLineWndProc = (WNDPROC)SetWindowLong( s_wcd.hwndInputLine, GWL_WNDPROC, (long)Con_InputLineProc );
		SendMessage( s_wcd.hwndInputLine, WM_SETFONT, ( WPARAM )s_wcd.hfBufferFont, 0 );
          }

	// show console if needed
	if( host.con_showalways )
	{          
		// make console visible
		ShowWindow( s_wcd.hWnd, SW_SHOWDEFAULT );
		UpdateWindow( s_wcd.hWnd );
		SetForegroundWindow( s_wcd.hWnd );

		if( host.type != HOST_DEDICATED )
			SetFocus( s_wcd.hWnd );
		else SetFocus( s_wcd.hwndInputLine );
		s_wcd.status = true;
          }
	else s_wcd.status = false;
#endif

	if( Sys_CheckParm( "-log" ) && host.developer != 0 )
	{
		s_wcd.log_active = true;
		Q_strncpy( s_wcd.log_path, "engine.log", sizeof( s_wcd.log_path ));
	}

	Sys_InitLog();
}
Beispiel #21
0
BOOL initInstance(
  HINSTANCE hinst, 
  UINT resPoolID, 
  int nCmdShow,
  LPSTR lpCmdLine)
  {
   HWND  hwnd;
   TCHAR ClassName [MAX_RESOURCESTRING + 1] ;
   int n;
   COPYDATASTRUCT theCDS;
   char *fileName;
   size_t length;
   
   hMainAccel = LoadAccelerators(hinst, "ClipsAcc");
   
   n = LoadString (hinst, resPoolID, ClassName, DIM(ClassName)) ;
   
   VERIFY(n != 0);

   /*========================================*/
   /* Determine if there is a prior instance */
   /* of the main frame window.              */
   /*========================================*/
   
   hwnd = FindWindow(ClassName,NULL);
   
   /*===================================================*/
   /* Register all application-specific window classes. */
   /*===================================================*/
   
   if (! registerWindowClasses (hinst, resPoolID))
     { return FALSE; }

   /*=====================================*/
   /* Initialize the Common Controls DLL. */
   /*=====================================*/
   
   InitCommonControls();

   /*=============================================*/
   /* Create the application's main frame window. */
   /*=============================================*/
   
   hMainFrame = createMainFrameWindow (hinst, nCmdShow);

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

   /*======================================================*/
   /* Constrain this application to run a single instance. */
   /*======================================================*/
   
   if (hwnd != NULL) 
     {
      /*=====================================================*/
      /* A previous instance of this application is running. */
      /* Activate the previous instance, tell it what the    */
      /* user requested this instance to do, then abort      */
      /* initialization of this instance.                    */
      /*=====================================================*/                   

      if (IsIconic (hwnd))
        { ShowWindow(hwnd,SW_RESTORE); }

      SetForegroundWindow(hwnd);

      /*=====================================================*/
      /* Send an application-defined message to the previous */
      /* instance (or use some other type of IPC mechanism)  */
      /* to tell the previous instance what to do.           */         
      /* Determining what to do generally depends on how the */
      /* user started this instance.                         */
      /*=====================================================*/

      length = strlen(lpCmdLine);
      fileName = (char *) malloc(length - 1);
      if (fileName == NULL) return FALSE;
      strncpy(fileName,&lpCmdLine[1],length-2);
      fileName[length-2] = 0;

      theCDS.dwData = CD_FILENAME;
      theCDS.cbData = length - 1;
      theCDS.lpData = fileName;

      SendMessage(hwnd,WM_COPYDATA,
                  (WPARAM)(HWND) hMainFrame,
                  (LPARAM) (LPVOID) &theCDS);
                   
      free(fileName);
      
      /*=======================================*/
      /* Abort this instance's initialization. */
      /*=======================================*/
      
      return FALSE;
     }

   /*==================================*/
   /* Go ahead and show the main frame */
   /* at this point in initialization. */
   /*==================================*/
   
   ShowWindow(hMainFrame,nCmdShow);
   UpdateWindow(hMainFrame);

   /*================================*/
   /* Initialize text child windows. */
   /*================================*/
   
   if (! text_InitInstance(hinst))
     { return FALSE; }

   /*===================================*/
   /* Initialize display child windows. */
   /*===================================*/
   
   if (! display_InitInstance(hinst))
     { return FALSE; }

   /*====================================*/
   /* Initialize display child windoows. */
   /*====================================*/
   
   if (! status_InitInstance(hinst))
     { return FALSE; }

   /*===================*/
   /* Set up the menus. */
   /*===================*/ 

   hMainAccel = LoadAccelerators(hinst,"ClipsAcc");
   haccel = hMainAccel;       

   if (FORWARD_WM_MDISETMENU(MDIClientWnd,TRUE,hMainMenu,
                             NULL,SendMessage) != 0)
     {
      SendMessage(hMainFrame, UWM_SET_ACCELERATOR, 0, (LPARAM) hMainAccel);
      DrawMenuBar(hMainFrame);
      PostMessage(hMainFrame, UWM_UPDATE_TOOLBAR, 0, 0);
     }

   /*======================================*/
   /* Initialize find/replace information. */
   /*======================================*/
   
   InitFindReplace(hwnd);

   hHourGlass = LoadCursor(NULL,IDC_WAIT);
   
   /* Initialize cursors. */
   
   WAIT[0] = LoadCursor((HINSTANCE) hinst, "CURSOR0" );
   WAIT[1] = LoadCursor((HINSTANCE) hinst, "CURSOR1" );
   WAIT[2] = LoadCursor((HINSTANCE) hinst, "CURSOR2" );
   WAIT[3] = LoadCursor((HINSTANCE) hinst, "CURSOR3" );
   WAIT[4] = LoadCursor((HINSTANCE) hinst, "CURSOR4" );
   WAIT[5] = LoadCursor((HINSTANCE) hinst, "CURSOR5" );
   WAIT[6] = LoadCursor((HINSTANCE) hinst, "CURSOR6" );
   WAIT[7] = LoadCursor((HINSTANCE) hinst, "CURSOR7" );
   WAIT[8] = LoadCursor((HINSTANCE) hinst, "CURSOR8" );
   WAIT[9] = LoadCursor((HINSTANCE) hinst, IDC_WAIT );

   QUERY = LoadCursor((HINSTANCE) hinst,"CLIPS_QUERY");
   ARROW = LoadCursor(NULL,IDC_ARROW);
   
   SetCursor(ARROW);
   
   /*====================================================*/
   /* Fill in non-variant fields of OPENFILENAME struct. */
   /*====================================================*/

   ofn.lStructSize       = sizeof(OPENFILENAME);
   ofn.hwndOwner       = hMainFrame;
   ofn.lpstrFilter     = "CLIPS Files (*.CLP)\0*.CLP\0Batch Files (*.BAT)\0*.BAT\0Text Files (*.TXT)\0*.TXT\0All Files (*.*)\0*.*\0";
   ofn.lpstrCustomFilter = NULL;
   ofn.nMaxCustFilter          = 0;
   ofn.nFilterIndex    = 1;
   ofn.lpstrFile         = szFileName;
   ofn.nMaxFile        = MAXFILENAME;
   ofn.lpstrInitialDir   = NULL;
   ofn.lpstrFileTitle    = szFileTitle;
   ofn.nMaxFileTitle     = MAXFILENAME;
   ofn.lpstrTitle        = NULL;
   ofn.lpstrDefExt       = "CLP";
   ofn.Flags             = OFN_HIDEREADONLY;

   /*==============================*/
   /* Initialize the print dialog. */
   /*==============================*/

   InitializePrintDialog(hMainFrame);

   /*============================*/
   /* Create the display window. */
   /*============================*/
   
#if DEFTEMPLATE_CONSTRUCT
   factsWindow_New(hMainFrame);
#endif
#if DEFRULE_CONSTRUCT
   agendaWindow_New(hMainFrame);
#endif
#if OBJECT_SYSTEM
   instancesWindow_New(hMainFrame);
#endif
#if DEFGLOBAL_CONSTRUCT 
   globalsWindow_New(hMainFrame);
#endif
#if DEFRULE_CONSTRUCT
   focusWindow_New(hMainFrame);
#endif
   displayWindow_New(hMainFrame);
   SendMessage(DialogWindow,WM_MDIACTIVATE,0,(LPARAM) DialogWindow);

   return TRUE;
  }
Beispiel #22
0
static void
windows_init(void *output)
{
  struct lstopo_windows_output *woutput = output;
  WNDCLASS wndclass;
  HWND toplevel, faketoplevel;
  unsigned width, height;
  HFONT font;

  /* make sure WM_DESTROY on the faketoplevel won't kill the program */
  woutput->toplevel = NULL;

  /* create the toplevel window, with random size for now */
  memset(&wndclass, 0, sizeof(wndclass));
  wndclass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
  wndclass.hCursor = LoadCursor(NULL, IDC_SIZEALL);
  wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  wndclass.lpfnWndProc = WndProc;
  wndclass.lpszClassName = "lstopo";

  RegisterClass(&wndclass);

  /* compute the maximal needed size, this may require the toplevel window in the future */
  woutput->max_x = 0;
  woutput->max_y = 0;
  woutput->drawing = 0;
  faketoplevel = CreateWindow("lstopo", "lstopo", WS_OVERLAPPEDWINDOW,
			      CW_USEDEFAULT, CW_USEDEFAULT,
			      10, 10, NULL, NULL, NULL, NULL);
  BeginPaint(faketoplevel, &woutput->ps);
  font = CreateFont(fontsize, 0, 0, 0, 0, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, NULL);
  SelectObject(woutput->ps.hdc, (HGDIOBJ) font);
  output_draw(&woutput->loutput);
  DeleteObject(font);
  EndPaint(faketoplevel, &woutput->ps);
  DestroyWindow(faketoplevel);
  woutput->drawing = 1;

  /* now create the actual toplevel with the sizes */
  width = woutput->max_x;
  height = woutput->max_y;

  win_width = width + 2*GetSystemMetrics(SM_CXSIZEFRAME);
  win_height = height + 2*GetSystemMetrics(SM_CYSIZEFRAME) + GetSystemMetrics(SM_CYCAPTION);

  if (win_width > GetSystemMetrics(SM_CXFULLSCREEN))
    win_width = GetSystemMetrics(SM_CXFULLSCREEN);

  if (win_height > GetSystemMetrics(SM_CYFULLSCREEN))
    win_height = GetSystemMetrics(SM_CYFULLSCREEN);

  toplevel = CreateWindow("lstopo", "lstopo", WS_OVERLAPPEDWINDOW,
		  CW_USEDEFAULT, CW_USEDEFAULT,
		  win_width, win_height, NULL, NULL, NULL, NULL);
  woutput->toplevel = toplevel;

  the_width = width;
  the_height = height;

  the_scale = 1.0f;

  the_fontsize = fontsize;
  the_gridsize = gridsize;

  /* and display the window */
  ShowWindow(toplevel, SW_SHOWDEFAULT);

  printf("\n");
  printf("Keyboard shortcuts:\n");
  printf(" Zoom-in or out .................... + -\n");
  printf(" Try to fit scale to window ........ f F\n");
  printf(" Reset scale to default ............ 1\n");
  printf(" Scroll vertically ................. Up Down PageUp PageDown\n");
  printf(" Scroll horizontally ............... Left Right Ctrl+PageUp/Down\n");
  printf(" Scroll to the top-left corner ..... Home\n");
  printf(" Scroll to the bottom-right corner . End\n");
  printf(" Exit .............................. q Q Esc\n");
  printf("\n\n");
}
Beispiel #23
0
void __declspec(dllexport) show(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop)
{
  TCHAR fn[MAX_PATH];
  TCHAR temp[64];
  TCHAR *sleep=temp;

 
  EXDLL_INIT();

  popstring(sleep);
  popstring(fn);

  sleep_val=0;
  while (*sleep >= _T('0') && *sleep <= _T('9'))
  {
    sleep_val*=10;
    sleep_val+=*sleep++-_T('0');
  }

  if (fn[0] && sleep_val>0)
  {
    MSG msg;
    TCHAR classname[4]=_T("_sp");
    static WNDCLASS wc;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = g_hInstance;
    wc.hCursor = LoadCursor(NULL,IDC_ARROW);
    wc.lpszClassName = classname;
    if (RegisterClass(&wc)) 
    {
      TCHAR fn2[MAX_PATH];
      lstrcpy(fn2,fn);
      lstrcat(fn,_T(".bmp"));
      lstrcat(fn2,_T(".wav"));
      g_hbm=LoadImage(NULL,fn,IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION|LR_LOADFROMFILE);
      if (g_hbm) 
      {
        HWND myWnd;

        PlaySound(fn2,NULL,SND_ASYNC|SND_FILENAME|SND_NODEFAULT);

        myWnd = CreateWindowEx(WS_EX_TOOLWINDOW,classname,classname,
          0,0,0,0,0,(HWND)hwndParent,NULL,g_hInstance,NULL);

        while (IsWindow(myWnd) && GetMessage(&msg,myWnd,0,0))
        {
          DispatchMessage(&msg);
        }

        // Stop currently playing wave, we want to exit
        PlaySound(0,0,0);

        DeleteObject(g_hbm);

        UnregisterClass(classname, g_hInstance);

      }
    }
  }
  wsprintf(temp,_T("%d"),g_rv);
  pushstring(temp);
}
Beispiel #24
0
/**
 * @brief Handle dialog messages.
 * @param [in] hDlg Handle to the dialog.
 * @param [in] iMsg The message.
 * @param [in] wParam The command in the message.
 * @param [in] lParam The optional parameter for the command.
 * @return TRUE if the message was handled, FALSE otherwise.
 */
INT_PTR FillWithDialog::DlgProc(HWindow* pDlg, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
	switch (iMsg)
	{
	case WM_INITDIALOG:
		{
			HEdit* pEditt = static_cast<HEdit *>(pDlg->GetDlgItem(IDC_HEX));//get the handle to the hex edit box
			pEditt->LimitText(FW_MAX);//limit the amount of text the user can enter
			pEditt->SetWindowText(pcFWText);//init hex text
			pEditt->SetFocus();//give the hex box focus
			pEditt->EnableWindow(!curtyp);
			oldproc = static_cast<LONG_PTR>(pEditt->SetWindowLongPtr(GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(HexProc)));//override the old proc to be HexProc
			EnableDlgItem(pDlg, IDC_HEXSTAT, !curtyp);

			HComboBox* typ = static_cast<HComboBox *>(pDlg->GetDlgItem(IDC_TYPE));
			typ->AddString(_T("Input"));
			typ->AddString(_T("File"));
			typ->SetCurSel(curtyp);//set cursel to previous

			//en/disable filename box and browse button
			HWindow* fn = pDlg->GetDlgItem(IDC_FN);
			fn->SetWindowText(szFWFileName);
			fn->EnableWindow(curtyp);
			EnableDlgItem(pDlg, IDC_BROWSE, curtyp);
			EnableDlgItem(pDlg, IDC_FILESTAT, curtyp);

			hfon = CreateFont(16, 0, 0, 0, FW_NORMAL, 0, 0, 0,
			                  DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
			                  DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Symbol"));
			inittxt(pDlg);
			switch (asstyp)
			{
			case 0:
				pDlg->CheckDlgButton(IDC_EQ, BST_CHECKED);
				break;
			case 1:
				pDlg->CheckDlgButton(IDC_OR, BST_CHECKED);
				break;
			case 2:
				pDlg->CheckDlgButton(IDC_AND, BST_CHECKED);
				break;
			case 3:
				pDlg->CheckDlgButton(IDC_XOR, BST_CHECKED);
				break;
			}
			return 0;//stop the system from setting focus to the control handle in (HWND) wParam because we already set focus above
		}
	case WM_COMMAND:
		switch (wParam)
		{
		case IDOK: //ok pressed
			{
				if (curtyp)
				{//1-file
					pDlg->GetDlgItemText(IDC_FN, szFWFileName, _MAX_PATH);//get file name
					FWFile = _topen(szFWFileName, _O_RDONLY | _O_BINARY);
					if (FWFile == -1)
					{//if there is error opening
						MessageBox(pDlg, GetLangString(IDS_ERR_OPENING_FILE), MB_ICONERROR);//tell user but don't close dlgbox
						return 1;//didn't process this message
					}//if
					FWFilelen = _filelength(FWFile);
					if (FWFilelen == 0)
					{//if filelen is zero
						MessageBox(pDlg, GetLangString(IDS_FILL_ZERO_SIZE_FILE), MB_ICONERROR);//tell user but don't close dlgbox
						_close(FWFile);//close file
						return 1;//didn't process this message
					}//if
					else if (FWFilelen == -1)
					{//error returned by _filelength
						MessageBox(pDlg, GetLangString(IDS_ERR_OPENING_FILE), MB_ICONERROR);//tell user but don't close dlgbox
						_close(FWFile);//close file
						return 1;//didn't process this message
					}//elseif
				}
				else
				{//0-input
					if (!buflen)
					{//no hex input
						MessageBox(pDlg, GetLangString(IDS_FILL_ZERO_SIZE_STR), MB_ICONERROR);//tell user but don't close dlgbox
						return 1;//didn't process this message
					}//if
					int i = pDlg->GetDlgItemText(IDC_HEX, pcFWText, FW_MAX);
					if (i == 0 || i == FW_MAX - 1)
					{//error
						MessageBox(pDlg, GetLangString(IDS_FILL_TOO_MANY_BYTES), MB_ICONERROR);//tell user but don't close dlgbox
						return 1;//didn't process this message
					}//if
					hexstring2charstring();//just in case
					//pcFWText[(aa?buflen:buflen*2)]='\0';//access violation if i do it in the above function
				}
				if (pDlg->IsDlgButtonChecked(IDC_EQ))
					asstyp = 0;
				else if (pDlg->IsDlgButtonChecked(IDC_OR))
					asstyp = 1;
				else if (pDlg->IsDlgButtonChecked(IDC_AND))
					asstyp = 2;
				else if (pDlg->IsDlgButtonChecked(IDC_XOR))
					asstyp = 3;

				// go ahead
				SetCursor(LoadCursor(nullptr, IDC_WAIT));
				BYTE (*fnc)(int);
				int iStartOfSelSetting;
				int iEndOfSelSetting;
				int iimax;
				if (curtyp)
				{//1-file
					fnc = file;
					iimax = FWFilelen;
				}//if
				else
				{//0-input
					fnc = input;
					iimax = buflen;
				}//else

				if (bSelected)
				{
					iStartOfSelSetting = iGetStartOfSelection();
					iEndOfSelSetting = iGetEndOfSelection();
				}
				else
				{
					iStartOfSelSetting = 0;
					iEndOfSelSetting = m_dataArray.GetUpperBound();
				}

				SimpleArray<BYTE> olddata(iEndOfSelSetting - iStartOfSelSetting + 1, &m_dataArray[iStartOfSelSetting]);
				int i = iStartOfSelSetting;
				int ii = 0;
				switch (asstyp)
				{// use switch instead of pointers to funcs that just call an operator as its faster
				case 0:
					while (i <= iEndOfSelSetting)
					{
						m_dataArray[i++] = fnc(ii++);
						ii %= iimax;
					}
					break;
				case 1:
					while (i <= iEndOfSelSetting)
					{
						m_dataArray[i++] |= fnc(ii++);
						ii %= iimax;
					}
					break;
				case 2:
					while (i <= iEndOfSelSetting)
					{
						m_dataArray[i++] &= fnc(ii++);
						ii %= iimax;
					}
					break;
				case 3:
					while (i <= iEndOfSelSetting)
					{
						m_dataArray[i++] ^= fnc(ii++);
						ii %= iimax;
					}
					break;
				}
				push_undorecord(iStartOfSelSetting, olddata, olddata.GetLength(), &m_dataArray[iStartOfSelSetting], olddata.GetLength());
				if (curtyp)
					_close(FWFile);//close file
				SetCursor(LoadCursor(nullptr, IDC_ARROW));
				bFilestatusChanged = true;
				repaint();//you tell me
			}
			// fall through
		case IDCANCEL: //cancel pressed
			DeleteObject(hfon);// won't need till next time
			pDlg->EndDialog(wParam);//tell CMD_fw not to carry out the fill with operation
			return 1;//did process this message
		case MAKEWPARAM(IDC_TYPE, CBN_SELCHANGE):
			//thing to fill selection with changes
			curtyp = static_cast<char>(pDlg->SendDlgItemMessage(IDC_TYPE, CB_GETCURSEL, 0, 0));//get cursel
			EnableDlgItem(pDlg, IDC_FN, curtyp);//en/disable fnamebox and browse button
			EnableDlgItem(pDlg, IDC_BROWSE, curtyp);
			EnableDlgItem(pDlg, IDC_FILESTAT, curtyp);
			curtyp = !curtyp;//flip it for the others
			EnableDlgItem(pDlg, IDC_HEX, curtyp);//en/disable hexboxand relateds
			EnableDlgItem(pDlg, IDC_HEXSTAT, curtyp);
			curtyp = !curtyp;//restore original value -not for below -accurate value needed elsewhere
			//set text in boxes down below
			inittxt(pDlg);
			break;
		case IDC_BROWSE:
			{
				//prepare OPENFILENAME for the file open common dlg box
				szFWFileName[0] = '\0';
				OPENFILENAME ofn;
				ZeroMemory(&ofn, sizeof ofn);
				ofn.lStructSize = sizeof ofn;
				ofn.hwndOwner = pDlg->m_hWnd;
				ofn.lpstrFilter = GetLangString(IDS_OPEN_ALL_FILES);
				ofn.lpstrFile = szFWFileName;
				ofn.nMaxFile = _MAX_PATH ;
				ofn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_FILEMUSTEXIST;
				//show open dlgbox and if file good save name & path in edit box
				if (GetOpenFileName(&ofn))
					pDlg->SetDlgItemText(IDC_FN, ofn.lpstrFile);
			}
			return TRUE;
		case MAKEWPARAM(IDC_HEX, EN_UPDATE): //hexedit updated
			pDlg->GetDlgItemText(IDC_HEX, pcFWText, FW_MAX);//gettext
			hexstring2charstring();//convert to char string
			//set text in boxes down below
			inittxt(pDlg);
			return TRUE;
		}
		break;

	case WM_HELP:
		OnHelp(pDlg);
		break;
	}
	return FALSE;
}
Beispiel #25
0
Flasher::Flasher(int port)
{
	// Create a dummy window.  We don't use it for anything except
	// receiving socket events, so a seperate listening thread would
	// probably be easier!

	WNDCLASSEX wndclass;

	wndclass.cbSize			= sizeof(wndclass);
	wndclass.style			= CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc	= Flasher::WndProc;
	wndclass.cbClsExtra		= 0;
	wndclass.cbWndExtra		= 0;
	wndclass.hInstance		= pApp->m_instance;
	wndclass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	wndclass.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground	= (HBRUSH) GetStockObject(WHITE_BRUSH);
	wndclass.lpszMenuName	= (const char *) NULL;
	wndclass.lpszClassName	= FLASHER_CLASS_NAME;
	wndclass.hIconSm		= LoadIcon(NULL, IDI_APPLICATION);

	TRY_CATCH
		RegisterClassForced(wndclass);
	CATCH_LOG()


	m_hwnd = CreateWindow(FLASHER_CLASS_NAME,
				FLASHER_CLASS_NAME,
				WS_OVERLAPPEDWINDOW,
				CW_USEDEFAULT,
				CW_USEDEFAULT,
				200, 200,
				NULL,
				NULL,
				pApp->m_instance,
				NULL);

	// record which client created this window
	SetWindowLong(m_hwnd, GWL_USERDATA, (LONG) this);

	// Select a font for displaying user name
	LOGFONT lf;
	memset(&lf, 0, sizeof(lf));
	lf.lfHeight = FLASHFONTHEIGHT;
	lf.lfWeight = FW_BOLD;
	lf.lfItalic = 1;
	lf.lfPitchAndFamily = VARIABLE_PITCH | FF_SWISS;
	lf.lfFaceName[0] = '\0';
	m_hfont = CreateFontIndirect(&lf);
	if (m_hfont == NULL) 
	{
		//vnclog.Print(1, _T("FAILED TO SELECT FLASHER FONT!\n"));
		Log.Add(_ERROR_, "FAILED TO SELECT FLASHER FONT!");
	}

	// Create a listening socket
    struct sockaddr_in addr;

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    m_sock = socket(AF_INET, SOCK_STREAM, 0);
	if (!m_sock) throw WarningException(sz_G1);
    
	try {
		int one = 1, res = 0;

		// If we use the SO_REUSEADDR option then you can run multiple daemons
		// because the bind doesn't return an error.  Only one gets the accept,
		// but when that process dies it hands back to another.  This may or may
		// not be desirable.  We don't use it.

		//int res = setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (const char *) &one, sizeof(one));
		//if (res == SOCKET_ERROR) 
		//	throw WarningException("Error setting Flasher socket options");
		
		res = bind(m_sock, (struct sockaddr *)&addr, sizeof(addr));
		if (res == SOCKET_ERROR)
			throw WarningException(sz_G2);
		
		res = listen(m_sock, 5);
		if (res == SOCKET_ERROR)
			throw WarningException(sz_G3);
	} catch (...) {
		closesocket(m_sock);
		m_sock = 0;
		throw;
	}
	
	// Send a message to specified window on an incoming connection
	WSAAsyncSelect (m_sock,  m_hwnd,  WM_SOCKEVENT, FD_ACCEPT | FD_CLOSE);
}
Beispiel #26
0
int
_tmain(int argc, const TCHAR *argv)
{
	HWND w;
	HINSTANCE hinst = GetModuleHandle(NULL);

	{
		WNDCLASS wc;
		wc.style = CS_HREDRAW|CS_VREDRAW;
		wc.lpfnWndProc = window_proc;
		wc.cbClsExtra = 0;
		wc.cbWndExtra = 0;
		wc.hInstance = hinst;
		wc.hIcon = NULL;
		wc.hCursor = LoadCursor(NULL, IDC_ARROW);
		wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
		wc.lpszMenuName = NULL;
		wc.lpszClassName = _T("MainWindowClass");
		RegisterClass(&wc);
	}

	// CreateWindow
	// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632679(v=vs.85).aspx
	// > If an overlapped window is created with the WS_VISIBLE
	// > style bit set and the x parameter is set to
	// > CW_USEDEFAULT, then the y parameter determines how the
	// > window is shown. If the y parameter is CW_USEDEFAULT,
	// > then the window manager calls ShowWindow with the SW_SHOW
	// > flag after the window has been created. If the y
	// > parameter is some other value, then the window manager
	// > calls ShowWindow with that value as the nCmdShow
	// > parameter.

	// ShowWindow
	// http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
	// > Controls how the window is to be shown.
	// >	This parameter is ignored the first time an
	// >	application calls ShowWindow, if the program that
	// >	launched the application provides a STARTUPINFO
	// >	structure.
	// > Otherwise, the first time ShowWindow is called, the value
	// > should be the value obtained by the WinMain function in
	// > its nCmdShow parameter. In subsequent calls, this
	// > parameter can be one of the following values.

	w = CreateWindow(_T("MainWindowClass"), _T("hello"),
		WS_OVERLAPPEDWINDOW|WS_VISIBLE,
		CW_USEDEFAULT, SW_SHOW, CW_USEDEFAULT, 0,
		NULL, NULL, hinst, NULL);

	while (1) {
		MSG msg;
		BOOL b = GetMessage(&msg, NULL, 0, 0);
		if (b == 0) {
			return msg.wParam;
		}
		if (b == -1) {
			return 1;
		}
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return 0;
}
/* ************************************
* 功能	显示一个窗口
**************************************/
int WINAPI WinMain(HINSTANCE hinstance, 
                   HINSTANCE hPrevInstance, 
                   LPSTR lpCmdLine, 
                   int nCmdShow) 
{     
    WNDCLASSEX wcx;         // 窗口类
    HWND hwnd;              //  窗口句柄     
    MSG msg;                // 消息
    BOOL fGotMessage;       // 是否成功获取消息
    hinst = hinstance;      // 应用程序实例句柄,保存为全局变量

    // 填充窗口类的数据结构
    wcx.cbSize = sizeof(wcx);          // 结构体的大小
    wcx.style = CS_HREDRAW | 
        CS_VREDRAW;                    // 样式:大小改变时重绘界面 
    wcx.lpfnWndProc = MainWndProc;     // 窗口消息处理函数 
    wcx.cbClsExtra = 0;                // 不使用类内存
    wcx.cbWndExtra = 0;                // 不使用窗口内存 
    wcx.hInstance = hinstance;         // 所属的应用程序实例句柄 
    wcx.hIcon = LoadIcon(NULL, 
        IDI_APPLICATION);              // 图标:默认
    wcx.hCursor = LoadCursor(NULL, 
        IDC_ARROW);                    // 光标:默认
    wcx.hbrBackground = (HBRUSH)GetStockObject( 
        WHITE_BRUSH);                  // 背景:白色
    wcx.lpszMenuName =  NULL;          // 菜单:不使用
    wcx.lpszClassName = "MainWClass";  // 窗口类名 
    wcx.hIconSm = (HICON)LoadImage(hinstance, // 小图标
        MAKEINTRESOURCE(5),
        IMAGE_ICON, 
        GetSystemMetrics(SM_CXSMICON), 
        GetSystemMetrics(SM_CYSMICON), 
        LR_DEFAULTCOLOR); 

    // 注册窗口类
    if(!RegisterClassEx(&wcx))
    {
        return 1;
    }

    // 创建窗口 
    hwnd = CreateWindow( 
        "MainWClass",        // 窗口名
        "CH 2-3",            // 窗口标题 
        WS_OVERLAPPEDWINDOW, // 窗口样式  
        CW_USEDEFAULT,       // 水平位置X:默认 
        CW_USEDEFAULT,       // 垂直位置Y:默认
        CW_USEDEFAULT,       // 宽度:默认
        CW_USEDEFAULT,       // 高度:默认 
        (HWND) NULL,         // 父窗口:无 
        (HMENU) NULL,        // 菜单:使用窗口类的菜单 
        hinstance,           // 应用程序实例句柄 
        (LPVOID) NULL);      // 窗口创建时数据:无 

    if (!hwnd) 
    {
        return 1; 
    }

    // 显示窗口 
    ShowWindow(hwnd, nCmdShow); 
    UpdateWindow(hwnd); 
    
    // 消息循环
    while (
        (fGotMessage = GetMessage(&msg, (HWND) NULL, 0, 0)) != 0 
        && fGotMessage != -1) 
    { 
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    } 
    return msg.wParam; 

} 
Beispiel #28
0
BOOL CALLBACK OptionsProc(HWND hdlg,UINT msg,WPARAM wparam,LPARAM lparam)
	{	
	switch(msg){
		case WM_INITDIALOG:{
			DWORD style;
			g_opHdlg=hdlg;
			bOptionsInit=TRUE;
			TranslateDialogDefault(hdlg); 
			if(g_iButtonsCount!=DBGetContactSettingByte(NULL, PLGNAME,"ButtonsCount", 0))
				{
				LOGFONT logFont;
				HFONT hFont;
				bNeedRestart=TRUE;
				EnableWindow(GetDlgItem(hdlg,IDC_BUTTONSLIST),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_BLISTADD),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_BLISTREMOVE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_MENUTREE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_MTREEADD),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_MTREEREMOVE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_RCLICKVALUE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_BUTTONNAME),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_INQMENU),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_MENUNAME),FALSE);	
				ShowWindow(GetDlgItem(hdlg,IDC_WARNING),SW_SHOW);

				hFont = (HFONT)SendMessage(GetDlgItem(hdlg, IDC_WARNING), WM_GETFONT, 0, 0);
				GetObject(hFont, sizeof logFont, &logFont);
				logFont.lfWeight = FW_BOLD;
				hFont = CreateFontIndirect(&logFont);
				SendMessage(GetDlgItem(hdlg, IDC_WARNING), WM_SETFONT, (WPARAM)hFont, 0);
				break;
				}
			
			g_iOPButtonsCount=g_iButtonsCount;

			hButtonsList=GetDlgItem(hdlg,IDC_BUTTONSLIST);
			hMenuTree=GetDlgItem(hdlg,IDC_MENUTREE);

			style = GetWindowLong(hButtonsList,GWL_STYLE);
			style |=TVS_NOHSCROLL;
			SetWindowLong(hButtonsList,GWL_STYLE, style);

			style = GetWindowLong(hMenuTree,GWL_STYLE);
			style |=TVS_NOHSCROLL;			
			SetWindowLong(hMenuTree,GWL_STYLE, style);
			BuildButtonsList(hButtonsList);
			
			if(!TreeView_GetCount(hButtonsList)) EnableWindow(GetDlgItem(hdlg,IDC_RCLICKVALUE),FALSE);

			oldBNameProc = (WNDPROC) SetWindowLong(GetDlgItem(hdlg,IDC_BUTTONNAME), GWL_WNDPROC, (LONG) EditSubclassProc);
			oldMNameProc = (WNDPROC) SetWindowLong(GetDlgItem(hdlg,IDC_MENUNAME)  , GWL_WNDPROC, (LONG) EditSubclassProc);

			
			EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),FALSE);
			EnableWindow(GetDlgItem(hdlg,IDC_INQMENU),FALSE);
			EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),FALSE);
			CheckDlgButton(hdlg,IDC_RAUTOSEND,(g_bRClickAuto=DBGetContactSettingByte(NULL,PLGNAME,"RClickAuto",0)));
			CheckDlgButton(hdlg,IDC_LAUTOSEND,(g_bLClickAuto=DBGetContactSettingByte(NULL,PLGNAME,"LClickAuto",0)));
			CheckDlgButton(hdlg,IDC_ENABLEQUICKMENU,(g_bQuickMenu=DBGetContactSettingByte(NULL, PLGNAME,"QuickMenu", 1)));
		
			bOptionsInit=FALSE;
			}break;

		case WM_LBUTTONUP:
			if(drag) {
				TVHITTESTINFO hti; 
				HTREEITEM htiAfter=NULL;
				ButtonData* bd=NULL;
				TVITEM tvi;
				RECT rc;
				BYTE height;
				BOOLEAN bAsChild = FALSE;

				TreeView_SetInsertMark(hMenuTree, NULL, 0 );
				ReleaseCapture();
				SetCursor( LoadCursor( NULL, IDC_ARROW ) );

				hti.pt.x = ( SHORT )LOWORD( lparam );
				hti.pt.y = ( SHORT )HIWORD( lparam );
				ClientToScreen(hdlg,&hti.pt);
				ScreenToClient(hMenuTree,&hti.pt);
				TreeView_HitTest( hMenuTree, &hti );

				if(TreeView_GetParent(hMenuTree,hti.hItem)&&TreeView_GetChild(hMenuTree,hDragItem))
					break;

				if(TreeView_GetChild(hMenuTree,hti.hItem)&&TreeView_GetChild(hMenuTree,hDragItem))
					break;


					if( hti.flags & TVHT_ABOVE ) {
						htiAfter = TVI_FIRST;
						}
					else
						if( hti.flags & ( TVHT_NOWHERE|TVHT_BELOW ) ) {
							htiAfter = TVI_LAST;
							}
						else
							if( hti.flags & ( TVHT_ONITEM|TVHT_ONITEMRIGHT ) ) {
								// check where over the item, the pointer is
								if( !TreeView_GetItemRect( hMenuTree, hti.hItem, &rc, FALSE ) ) {
									drag=0;
									break;
									}
								height = ( BYTE )( rc.bottom - rc.top );

								if( hti.pt.y - ( height / 3 ) < rc.top ) {
									HTREEITEM hItem = hti.hItem;

									if( !( hti.hItem = TreeView_GetPrevSibling( hMenuTree, hItem ) ) ) {
										if( !( hti.hItem = TreeView_GetParent(hMenuTree, hItem ) ))
											htiAfter = TVI_FIRST;
										else
											bAsChild = TRUE;
										}
									}
								else 
									if( hti.pt.y + ( height / 3 ) <= rc.bottom ) {
										bAsChild = TRUE;
										}
								}	


							if(TreeView_GetChild(hMenuTree,hDragItem)&&bAsChild)
								break;


							if(hti.hItem){
 									tvi.hItem=hti.hItem;
 									tvi.mask=TVIF_PARAM |TVIF_HANDLE;
 									TreeView_GetItem(hMenuTree,&tvi);
									if((bd=(ButtonData*)tvi.lParam)&&(bd->fEntryOpType&QMF_EX_SEPARATOR))
										bAsChild = FALSE;
							 }

							if(TreeView_GetParent(hMenuTree,hti.hItem))
 								bAsChild = FALSE;


							MoveItem( hDragItem, htiAfter?htiAfter:hti.hItem, bAsChild );
							SendMessage(GetParent(hdlg),PSM_CHANGED,0,0);
							drag=0;

				}
			break; 

		///////////////////////////////////
		//From UserInfoEx by DeathAxe
		//
		case WM_MOUSEMOVE:
			{
			if (!drag) break;
				{
				TVHITTESTINFO hti;

				hti.pt.x=(short)LOWORD(lparam);
				hti.pt.y=(short)HIWORD(lparam);
				ClientToScreen(hdlg,&hti.pt);
				ScreenToClient(hMenuTree,&hti.pt);
				TreeView_HitTest(hMenuTree,&hti);
				if( hti.flags & ( TVHT_ONITEM|TVHT_ONITEMRIGHT ) ) {
					RECT rc;
					BYTE height;

					if( TreeView_GetItemRect(hMenuTree, hti.hItem, &rc, FALSE ) ) {
						height = ( BYTE )( rc.bottom - rc.top );

						if( hti.pt.y - ( height / 3 ) < rc.top ) {
							SetCursor( LoadCursor( NULL, IDC_ARROW ) );
							TreeView_SetInsertMark( hMenuTree, hti.hItem, 0 );
							}
						else
							if( hti.pt.y + ( height / 3 ) > rc.bottom ) {
								SetCursor( LoadCursor( NULL, IDC_ARROW ) );
								TreeView_SetInsertMark( hMenuTree, hti.hItem, 1 );
								}
							else {
								TreeView_SetInsertMark( hMenuTree, NULL, 0 );
								SetCursor( LoadCursor( GetModuleHandle(NULL), MAKEINTRESOURCE( 183 ) ) );
								}
						}
					}
				else {
					if( hti.flags & TVHT_ABOVE ) SendMessage( hMenuTree, WM_VSCROLL, MAKEWPARAM( SB_LINEUP, 0 ), 0 );
					if( hti.flags & TVHT_BELOW ) SendMessage( hMenuTree, WM_VSCROLL, MAKEWPARAM( SB_LINEDOWN, 0 ), 0 );
					TreeView_SetInsertMark( hMenuTree, NULL, 0 );
					}
				}
			}break;
			/////////////
		case WM_DESTROY:
			if (g_varhelpDlg)
				DestroyWindow(g_varhelpDlg);
			g_varhelpDlg=NULL;
			break;

		case WM_NOTIFY:{
			switch(((LPNMHDR)lparam)->idFrom)	{
		case 0:{
			if (((LPNMHDR)lparam)->code == PSN_APPLY ) {
				if(!bNeedRestart){
				SetMenuEntryProperties(hdlg);
				SaveMenuTree(hdlg); 
				}
				DBWriteContactSettingByte(NULL,PLGNAME,"RClickAuto",(BYTE)(g_bRClickAuto=IsDlgButtonChecked(hdlg,IDC_RAUTOSEND)));
				DBWriteContactSettingByte(NULL,PLGNAME,"LClickAuto",(BYTE)(g_bLClickAuto=IsDlgButtonChecked(hdlg,IDC_LAUTOSEND)));
				DBWriteContactSettingByte(NULL,PLGNAME,"QuickMenu",(BYTE)(g_bQuickMenu=IsDlgButtonChecked(hdlg,IDC_ENABLEQUICKMENU)));
				return 1;
				}
			else if (((LPNMHDR)lparam)->code == PSN_RESET ) {
					if(!bNeedRestart)
						RestoreModuleData(hdlg);
				return 1;
				}
			}
			break; 

		case IDC_MENUTREE:
			switch (((LPNMHDR)lparam)->code){

		case TVN_KEYDOWN:{
			TV_KEYDOWN* pTVKeyDown = (TV_KEYDOWN*) ((LPNMHDR)lparam);
			if ( pTVKeyDown->wVKey == VK_F2 )
				TreeView_EditLabel(hMenuTree,TreeView_GetSelection(hMenuTree));
			else if ( pTVKeyDown->wVKey == VK_DELETE )
					SendMessage(hdlg,WM_COMMAND,IDC_MTREEREMOVE,0);
			}break;

		case TVN_BEGINLABELEDITA:
		case TVN_BEGINLABELEDITW:
			hwndEdit=TreeView_GetEditControl(hMenuTree);
			oldEditProc = (WNDPROC) SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG) LabelEditSubclassProc);
			break;

		case TVN_ENDLABELEDITA:
		case TVN_ENDLABELEDITW:
			{
			TVITEM tvi;
			ButtonData* bd=NULL;
			TCHAR strbuf[256];
			TCHAR szLabel[256];

			SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG) oldEditProc);

			tvi.pszText = strbuf;
			tvi.cchTextMax = sizeof(strbuf);
			tvi.mask=TVIF_TEXT |TVIF_HANDLE|TVIF_PARAM;
			tvi.hItem=TreeView_GetSelection(hMenuTree);
			TreeView_GetItem(hMenuTree,&tvi);

			GetWindowText(hwndEdit, szLabel, sizeof(szLabel));
			hwndEdit=NULL;
			if(!_tcslen(szLabel)) break;
			if (bd = (ButtonData*)tvi.lParam){
				if(!_tcscmp(szLabel,_T("---"))){
					if(TreeView_GetChild(hMenuTree,tvi.hItem))
						break;
					else{
						bd->fEntryOpType=QMF_EX_SEPARATOR;
						EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),FALSE);
						EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),FALSE);
						SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),_T(""));
						}
					}
				else {
					bd->fEntryOpType&=~QMF_EX_SEPARATOR;
						EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),TRUE);
						EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),TRUE);
						SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),bd->pszOpValue/*?bd->pszOpValue:bd->pszValue*/);
					}

				bd->pszOpName=mir_tstrdup(szLabel);
				
				tvi.pszText=szLabel;
				TreeView_SetItem(hMenuTree, &tvi);
				SendMessage(GetParent(hdlg),PSM_CHANGED,0,0);
				}
			}break;

		case NM_KILLFOCUS:
			TreeView_EndEditLabelNow(hButtonsList, 1);
			break;

		case TVN_BEGINDRAGA:
		case TVN_BEGINDRAGW:
			SetCapture(hdlg);
			drag=1;
			hDragItem=((LPNMTREEVIEW)lparam)->itemNew.hItem;
			TreeView_SelectItem(hMenuTree,hDragItem);
			break;

		case TVN_SELCHANGINGA:
		case TVN_SELCHANGINGW:
			{
			TVITEM tvi;
			HTREEITEM hti;
			ButtonData* bd;

			hti=TreeView_GetSelection(hMenuTree);

			if (hti==NULL)
				break;

			tvi.hItem=hti;
			tvi.mask=TVIF_HANDLE|TVIF_PARAM;
			TreeView_GetItem(hMenuTree,&tvi);

			if (tvi.lParam == 0)
				break;

			bd = ( ButtonData* )tvi.lParam;
			if (bd) {
				TCHAR szValue[256];
				GetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE), szValue, sizeof(szValue));
				if(_tcslen(szValue))
					{
					if(bd->pszOpValue&&(bd->pszOpValue!=bd->pszValue))
						mir_free(bd->pszOpValue);
					bd->pszOpValue=mir_tstrdup(szValue);
					}
				bd->bOpInQMenu=IsDlgButtonChecked(hdlg,IDC_INQMENU);
				bd->bIsOpServName=IsDlgButtonChecked(hdlg,IDC_ISSERVNAME);
				}
			}break;
		case TVN_SELCHANGEDA:
		case TVN_SELCHANGEDW:
			{
			TVITEM tvi;
			HTREEITEM hti;
			ButtonData* bd=NULL;

			hti=TreeView_GetSelection(hMenuTree);

			if (hti==NULL)
				break;

			tvi.mask=TVIF_HANDLE|TVIF_PARAM;

			tvi.hItem=hti;
			TreeView_GetItem(hMenuTree,&tvi);


			bd = ( ButtonData* )tvi.lParam;
			if (bd) {
				if(!TreeView_GetChild(hMenuTree, tvi.hItem)&&!(bd->fEntryOpType&QMF_EX_SEPARATOR))
					{
					EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),TRUE);
					EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),TRUE);
					EnableWindow(GetDlgItem(hdlg,IDC_INQMENU),TRUE);
					SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),bd->pszOpValue/*?bd->pszOpValue:bd->pszValue*/);
					}
				else
					{
					EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),FALSE);
					EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),FALSE);
					if(!(bd->fEntryOpType&QMF_EX_SEPARATOR))
						EnableWindow(GetDlgItem(hdlg,IDC_INQMENU),FALSE);
					SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),_T(""));
					}
				CheckDlgButton(hdlg,IDC_INQMENU,bd->bOpInQMenu);
				CheckDlgButton(hdlg,IDC_ISSERVNAME,bd->bIsOpServName);
				}
			}
		}break;

		case IDC_BUTTONSLIST:
			switch (((LPNMHDR)lparam)->code) {

		case TVN_KEYDOWN:{
			TV_KEYDOWN* pTVKeyDown = (TV_KEYDOWN*) ((LPNMHDR)lparam);
			if ( pTVKeyDown->wVKey == VK_F2 )
				TreeView_EditLabel(hButtonsList,TreeView_GetSelection(hButtonsList));
			else if ( pTVKeyDown->wVKey == VK_DELETE )
				SendMessage(hdlg,WM_COMMAND,IDC_BLISTREMOVE,0);
			}break;

		case TVN_BEGINLABELEDITA:
		case TVN_BEGINLABELEDITW:
			hwndEdit=TreeView_GetEditControl(hButtonsList);
			oldEditProc = (WNDPROC) SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG) LabelEditSubclassProc);
			break;

		case TVN_ENDLABELEDITA:
		case TVN_ENDLABELEDITW:{
			TVITEM tvi;
			TCHAR strbuf[128];
			TCHAR szLabel[128];

			SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG) oldEditProc);

			tvi.pszText = strbuf;
			tvi.cchTextMax = sizeof(strbuf);
			tvi.mask=TVIF_TEXT |TVIF_HANDLE|TVIF_PARAM;
			tvi.hItem=TreeView_GetSelection(hButtonsList);
			TreeView_GetItem(hButtonsList,&tvi);

			GetWindowText(hwndEdit, szLabel, sizeof(szLabel));
			hwndEdit=NULL;
			if(!_tcslen(szLabel)) break;

			tvi.pszText=szLabel;
			((ListData*)tvi.lParam)->dwOPFlags|=QMF_RENAMED;	

			TreeView_SetItem(hButtonsList, &tvi);
			SendMessage(GetParent(hdlg),PSM_CHANGED,0,0);
			}break;

		case TVN_SELCHANGINGA:
		case TVN_SELCHANGINGW:
			SetMenuEntryProperties(hdlg);
			break;

		case TVN_SELCHANGEDA:
		case TVN_SELCHANGEDW:{
			TVITEM tvi;
			HTREEITEM hti;

			hti=TreeView_GetSelection(hButtonsList);

			if(hti==NULL||!TreeView_GetCount(hButtonsList)){
				EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_INQMENU),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME2),FALSE);
				SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),_T(""));
				break;
				}
			
			tvi.mask=TVIF_HANDLE|TVIF_PARAM;
			tvi.hItem=hti;
			TreeView_GetItem(hButtonsList,&tvi);

			if(tvi.lParam==0) break;

			BuildMenuTree(hMenuTree,(SortedList *)((ListData*)tvi.lParam)->sl);

			SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),_T(""));
			EnableWindow(GetDlgItem(hdlg,IDC_RCLICKVALUE),TRUE);
			EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME2),TRUE);
			CheckDlgButton(hdlg,IDC_ISSERVNAME2,((ListData*)tvi.lParam)->bIsOpServName);

			if(((ListData*)tvi.lParam)->ptszOPQValue) 
				SetWindowText(GetDlgItem(hdlg,IDC_RCLICKVALUE),((ListData*)tvi.lParam)->ptszOPQValue);
			else
				SetWindowText(GetDlgItem(hdlg,IDC_RCLICKVALUE),_T(""));

			}break;
				}break;
				}
			}break;

		case WM_COMMAND:{
		switch(LOWORD(wparam)){
		case IDC_VARHELP:{
			if(!g_varhelpDlg)
				g_varhelpDlg=CreateDialog(hinstance,MAKEINTRESOURCE(IDD_HELPDIALOG), 0, HelpDlgProc);
			else
				//ShowWindow(g_varhelpDlg,SW_SHOWDEFAULT);
				SetWindowPos(g_varhelpDlg,0,0,0,0,0,SWP_SHOWWINDOW|SWP_NOMOVE|SWP_NOSIZE);
			}break;
		case IDC_BLISTADD:{
			TVINSERTSTRUCT tvis;
			ListData* ld=NULL;
			TCHAR namebuff[MAX_PATH]={'\0'};
			int count=TreeView_GetCount(hButtonsList);
			if (count>10) break;
			if(g_iOPButtonsCount==99){
				MessageBox(NULL,_T("Congratulation!\n\
								   You have clicked this button 100 times!\n\
								   There was access violation at this point...\n\
								   And now function for freeing resources must be called...\n\
								   But no! there's only break :D"),_T("You win!"),MB_OK);
				break;
				}

			ld=mir_alloc(sizeof(ListData));
			ButtonsList[g_iOPButtonsCount++]=ld;

			ld->sl=li.List_Create(0,1);
			ld->dwOPFlags=QMF_NEW;
			ld->bIsOpServName=0;
			ld->ptszButtonName=NULL;
			ld->ptszOPQValue=NULL;
			ld->ptszQValue=NULL;
			tvis.hParent = NULL;
			tvis.hInsertAfter = TVI_LAST;
			
			GetWindowText(GetDlgItem(hdlg,IDC_BUTTONNAME),namebuff,MAX_PATH);

			tvis.item.mask=TVIF_PARAM|TVIF_TEXT;
			tvis.item.pszText=(_tcslen(namebuff))?namebuff:TranslateT("New Button");
			tvis.item.lParam=(LPARAM)ld;
			TreeView_SelectItem(hButtonsList,TreeView_InsertItem(hButtonsList,&tvis));

			}break;

		case IDC_BLISTREMOVE:{ 
			TVITEM tvi;
			ListData* ld;

			if(!(tvi.hItem=TreeView_GetSelection(hButtonsList)))
				break;

			tvi.mask=TVIF_HANDLE|TVIF_PARAM;
			TreeView_GetItem(hButtonsList,&tvi);

			ld= (ListData*)tvi.lParam;

			ld->dwOPFlags|=QMF_DELETNEEDED;	

			TreeView_DeleteItem(hButtonsList,tvi.hItem);
			if(!TreeView_GetCount(hButtonsList))
				{
				TreeView_DeleteAllItems(hMenuTree);
				EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_RCLICKVALUE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_INQMENU),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME2),FALSE);
				SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),_T(""));
				SetWindowText(GetDlgItem(hdlg,IDC_RCLICKVALUE),_T(""));
				}
			}break;

		case IDC_MTREEADD:{ 
			TVINSERTSTRUCT tvis;
			TVITEM tvi;
			ButtonData *bd=NULL;
			SortedList *sl=NULL;
			TCHAR namebuff[MAX_PATH]={'\0'};
			
			if(!TreeView_GetCount(hButtonsList)) break;
			if(!(tvi.hItem=TreeView_GetSelection(hButtonsList))) break;
			
			bd=mir_alloc(sizeof(ButtonData));
			memset(bd,0,sizeof(ButtonData));

			GetWindowText(GetDlgItem(hdlg,IDC_MENUNAME),namebuff,MAX_PATH);

			bd->dwOPPos=TreeView_GetCount(hMenuTree)-1;
			bd->pszOpName=_tcslen(namebuff)?mir_tstrdup(namebuff):mir_tstrdup(TranslateT("New Menu Entry"));
			bd->pszOpValue=mir_tstrdup(bd->pszOpName);
			bd->fEntryOpType=!_tcscmp(namebuff,_T("---"))?QMF_EX_SEPARATOR:0;
			bd->dwOPFlags=QMF_NEW;
			bd->pszName=NULL;
			bd->pszValue=NULL;


			tvi.mask=TVIF_HANDLE|TVIF_PARAM;
			
			TreeView_GetItem(hButtonsList,&tvi);

			sl=((ListData*)tvi.lParam)->sl;

			li.List_InsertPtr(sl,bd);

			tvis.hParent = NULL;
			tvis.hInsertAfter = TVI_LAST;
			tvis.item.mask=TVIF_PARAM|TVIF_TEXT;
			tvis.item.pszText=bd->pszOpName;
			tvis.item.lParam=(LPARAM)bd;
			TreeView_SelectItem(hMenuTree,TreeView_InsertItem(hMenuTree,&tvis));
			}break;

		case IDC_MTREEREMOVE:{
			TVITEM tvi;
			TVINSERTSTRUCT tvis;
			HTREEITEM hti=NULL;
			ButtonData *bd=NULL;
			tvi.mask=TVIF_HANDLE|TVIF_PARAM;
			if(!(tvi.hItem=TreeView_GetSelection(hMenuTree)))
				break;
			TreeView_GetItem(hMenuTree,&tvi);
			hti=tvi.hItem;

			bd= (ButtonData*)tvi.lParam;
			bd->dwOPFlags|=QMF_DELETNEEDED;			

			if(tvi.hItem=TreeView_GetChild(hMenuTree,tvi.hItem)){
				TCHAR strbuf[128];
				while(tvi.hItem){
					tvis.hInsertAfter=hti;
					tvi.pszText = strbuf;
					tvi.cchTextMax = sizeof(strbuf);
					tvi.mask=TVIF_HANDLE|TVIF_PARAM|TVIF_TEXT;

					TreeView_GetItem(hMenuTree,&tvi); 
					tvis.hParent=NULL;
					tvis.item=tvi;
					TreeView_InsertItem(hMenuTree,&tvis);
					tvi.hItem=TreeView_GetNextSibling(hMenuTree,tvi.hItem);
					}
				}

			TreeView_DeleteItem(hMenuTree,hti);
			if(!TreeView_GetCount(hMenuTree)){
				EnableWindow(GetDlgItem(hdlg,IDC_MENUVALUE),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_ISSERVNAME),FALSE);
				EnableWindow(GetDlgItem(hdlg,IDC_INQMENU),FALSE);
				SetWindowText(GetDlgItem(hdlg,IDC_MENUVALUE),_T(""));
				}

			}break;

				}
			}break;

		case WM_NCDESTROY: 
			if(oldBNameProc) SetWindowLong(GetDlgItem(hdlg,IDC_BUTTONNAME), GWL_WNDPROC, (LONG) oldBNameProc);
			if(oldMNameProc) SetWindowLong(GetDlgItem(hdlg,IDC_MENUNAME)  , GWL_WNDPROC, (LONG) oldMNameProc);
			break; 

		case WM_CLOSE:
			EndDialog(hdlg,0);
			return 0;
		}
Beispiel #29
0
BOOL CALLBACK DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	OPENFILENAME ofn;
	POINT pt;
	RECT rect;
	switch(uMsg){
	case WM_INITDIALOG:
		InitCommonControls();
		hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_MAIN));
		SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
		CheckDlgButton(hDlg, IDC_BACKUP, BST_CHECKED);
		SendMessage(GetDlgItem(hDlg, IDC_FILE), EM_SETREADONLY, (WPARAM)TRUE, (LPARAM)0);
		hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_EXE));
		SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0);
		EnableWindow(GetDlgItem(hDlg, IDC_BUILD), FALSE);
		SetWindowPos(hDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
		break;
	case WM_CLOSE:
		EndDialog(hDlg, 0);
		break;
	case WM_PAINT:
		SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0);
		break;
	case WM_DROPFILES:
		HDROP hDrop;
		hDrop = HDROP(wParam);
		DragQueryFile(hDrop, 0, szEFileName, sizeof(szEFileName));
		DragFinish(hDrop);
		if(LoadPE(szEFileName) == FALSE)
		{
			MessageBox(hDlg, "Could not load file!", "Cryptic", MB_ICONERROR);
			return TRUE;
		}
		SetDlgItemText(hDlg, IDC_FILE, szEFileName);
		EnableWindow(GetDlgItem(hDlg, IDC_BUILD), TRUE);
		break;
	case WM_MOUSEMOVE:
		GetCursorPos(&pt);
		GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect);
		if(PtInRect(&rect, pt))
		{
			SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649)));
		}
		else
		{
			SetCursor(LoadCursor(NULL, IDC_ARROW));
		}
		break;
	case WM_LBUTTONDOWN:
		GetCursorPos(&pt);
		GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect);
		if(PtInRect(&rect, pt))
		{
			SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649)));
			memset(&ofn, 0, sizeof(ofn));
			szIFileName[0] = '\0';
			ofn.lStructSize = sizeof(OPENFILENAME);
			ofn.hwndOwner = hDlg;
			ofn.lpstrFilter = "Icon Files (*.ico)\0*.ico\0\0";
			ofn.lpstrFile = szIFileName;
			ofn.nMaxFile = MAX_PATH;
			ofn.Flags = OFN_PATHMUSTEXIST;
			if(GetOpenFileName(&ofn))
			{
				hIcon = ExtractIcon(hInst, szIFileName, 0);
				SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0);
			}
		}
		break;
	case WM_RBUTTONDOWN:
		GetCursorPos(&pt);
		GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect);
		if(PtInRect(&rect, pt))
		{
			SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649)));
		}
		break;
	case WM_COMMAND:
		switch LOWORD(wParam){
		case IDC_BROWSE:
			memset(&ofn, 0, sizeof(ofn));
			szEFileName[0] = '\0';
			ofn.lStructSize = sizeof(OPENFILENAME);
			ofn.hwndOwner = hDlg;
			ofn.lpstrFilter = "Executable Files (*.exe)\0*.exe\0\0";
			ofn.lpstrFile = szEFileName;
			ofn.nMaxFile = MAX_PATH;
			ofn.Flags = OFN_PATHMUSTEXIST;
			if(GetOpenFileName(&ofn))
			{
				if(LoadPE(szEFileName) == FALSE)
				{
					MessageBox(hDlg, "Could not load file!", "Cryptic", MB_ICONERROR);
					return TRUE;
				}
				SetDlgItemText(hDlg, IDC_FILE, szEFileName);
				EnableWindow(GetDlgItem(hDlg, IDC_BUILD), TRUE);
			}
			break;
		case IDC_BUILD:
			EnableControls(hDlg, FALSE);
			HRSRC hRsrc;
			hRsrc = FindResource(NULL, MAKEINTRESOURCE(IDR_STUB), "STUB");
			if(hRsrc == NULL)
			{
				MessageBox(hDlg, "Could not find resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			DWORD dwRsrcSize;
			dwRsrcSize = SizeofResource(NULL, hRsrc);
			HGLOBAL hGlob;
			hGlob = LoadResource(NULL, hRsrc);
			if(hGlob == NULL)
			{
				MessageBox(hDlg, "Could not load resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			LPBYTE lpBuffer;
			lpBuffer = (LPBYTE)LockResource(hGlob);
			if(lpBuffer == NULL)
			{
				MessageBox(hDlg, "Could not lock resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			GetDlgItemText(hDlg, IDC_FILE, szEFileName, MAX_PATH);
			if(IsDlgButtonChecked(hDlg, IDC_BACKUP) == BST_CHECKED)
			{
				CHAR szBFileName[MAX_PATH];
				GetDlgItemText(hDlg, IDC_FILE, szBFileName, MAX_PATH);
				strcat(szBFileName, ".bak");
				if(CopyFile(szEFileName, szBFileName, FALSE) == 0)
				{
					free(lpBuffer);
					MessageBox(hDlg, "Could not copy file!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
			}
			BYTE lpKey[14];
			srand(time(NULL));
			int i;
			for(i = 0; i < 15; i++)
			{
				lpKey[i] = BYTE(rand() % 255 + 1);
			}
			HANDLE hFile;
			hFile = CreateFile(szEFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
			if(hFile == INVALID_HANDLE_VALUE)
			{
				free(lpBuffer);
				MessageBox(hDlg, "Could not create file!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			DWORD dwBytesWritten;
			if(WriteFile(hFile, lpBuffer, dwRsrcSize, &dwBytesWritten, NULL) == 0)
			{
				CloseHandle(hFile);
				free(lpBuffer);
				MessageBox(hDlg, "Could not write to file!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			CloseHandle(hFile);
			free(lpBuffer);
			if(IsDlgButtonChecked(hDlg, IDC_ADDICON) == BST_CHECKED)
			{
				if(AddIcon(szIFileName, szEFileName) == FALSE)
				{
					MessageBox(hDlg, "Could add icon!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
			}
			HANDLE hUpdate;
			hUpdate = BeginUpdateResource(szEFileName, FALSE);
			if(hUpdate == NULL)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			if(UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(150), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), RC4(lpFileBuffer, lpKey, dwFileSize, 15), dwFileSize) == FALSE)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			if(UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(151), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), &lpKey[0], 15) == FALSE)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			if(EndUpdateResource(hUpdate, FALSE) == FALSE)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			RC4(lpFileBuffer, lpKey, dwFileSize, 15);
			pish = (PIMAGE_SECTION_HEADER)&lpFileBuffer[pidh->e_lfanew + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER) * (pinh->FileHeader.NumberOfSections - 1)];
			if(dwFileSize > (pish->PointerToRawData + pish->SizeOfRawData))
			{
				MessageBox(hDlg, "EOF data found!", "Cryptic", MB_OK);
				hFile = CreateFile(szEFileName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
				if(hFile == INVALID_HANDLE_VALUE)
				{
					MessageBox(hDlg, "Could not open file!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
				SetFilePointer(hFile, 0, NULL, FILE_END);
				if(WriteFile(hFile, &lpFileBuffer[pish->PointerToRawData + pish->SizeOfRawData + 1], dwFileSize - (pish->PointerToRawData + pish->SizeOfRawData), &dwBytesWritten, NULL) == 0)
				{
					CloseHandle(hFile);
					MessageBox(hDlg, "Could not write to file!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
				CloseHandle(hFile);
			}
			MessageBox(hDlg, "File successfully crypted!", "Cryptic", MB_ICONINFORMATION);
			EnableControls(hDlg, TRUE);
			break;
		case IDC_ABOUT:
			MessageBox(hDlg, "Cryptic v3.0\nCoded by Tughack", "About", MB_ICONINFORMATION);
			break;
		case IDC_EXIT:
			EndDialog(hDlg, 0);
			break;
		}
	}
	return FALSE;
}
wyBool
BlobMgmt::OpenFromFile()
{
	OPENFILENAME	open;
	wyWChar			filename[MAX_PATH+1] = {0};
	HANDLE			hfile = NULL;
	wyChar			*buffer = {0};
	DWORD			dwbytesread, filesize;
	wyString		bufferstr;

	memset(&open, 0, sizeof(open));

	open.lStructSize       = OPENFILENAME_SIZE_VERSION_400;
	open.hwndOwner         = m_hwnddlg;
	open.hInstance         = pGlobals->m_pcmainwin->GetHinstance();
	open.lpstrFilter       = L"All Files(*.*)\0*.*\0";
	open.lpstrCustomFilter =(LPWSTR)NULL;
	open.nFilterIndex      = 1L;
	open.lpstrFile         = filename;
	open.nMaxFile          = MAX_PATH;
	open.lpstrTitle        = L"Open File";
	
	if(! GetOpenFileName(&open))
	   return wyFalse;

	// else successfull.
	hfile = CreateFile((LPCWSTR)filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
						 NULL);	

	if(hfile == INVALID_HANDLE_VALUE)
	{
		DisplayErrorText(GetLastError(), _("Could not open file !"));
		return wyFalse;
	}

	VERIFY((filesize = GetFileSize(hfile, NULL))!= INVALID_FILE_SIZE);
	VERIFY (buffer =(wyChar*)malloc(filesize + 1));
	SetCursor(LoadCursor(NULL, IDC_WAIT));

	if(!ReadFile(hfile, buffer, filesize, &dwbytesread, NULL))
	{
		DisplayErrorText(GetLastError(), _("Could not open file. The data is not changed"));
		free(buffer);
		SetCursor(LoadCursor(NULL, IDC_ARROW));
		CloseHandle(hfile);
		return wyFalse;
	}

	*(buffer + dwbytesread)= NULL;

	SetCursor(LoadCursor(NULL, IDC_ARROW));

	// now we add the new buffer.
	if(m_newdata && m_newdata != m_olddata)
		free(m_newdata);
	
	m_newdata       = (wyChar *)buffer;
	m_newdatasize   = dwbytesread;
	
	/* store the old data too */
	m_piub->m_olddata		= m_piub->m_data;
	m_piub->m_olddatasize	= m_piub->m_datasize;
	m_piub->m_data			= m_newdata;
	m_piub->m_datasize		= dwbytesread;
	m_piub->m_isnull		= wyFalse;

	VERIFY(CloseHandle(hfile));

	// upddate with the new.
	ShowData(wyFalse);

	/* we need to do this after showdata coz showdata changes the modify flag to 0 */
	/* now if its text data then we set the text control modification flag */
	if(!memchr(buffer, 0, dwbytesread))
		SendMessage(m_hwndedit, EM_SETMODIFY, TRUE, 0);

	return wyTrue;
}