/** Global Function to translate dialog messages.*/
VBOOL VTranslateDialogMessage(MSG const& msg)
{
	HWND hWndTop = msg.hwnd;

	/* Obtain the top level window. All dialogs are typically defined
	as top level popups.*/
	while ( hWndTop )
	{
		if ( GetWindowLong(hWndTop, GWL_STYLE) & WS_CHILD )
			hWndTop = GetParent(hWndTop);
		else
			break;
	}

	/* Obtain the associated window pointer (if a VWCL window).*/
	VWindow* pWindow = VWindow::GetVWindowFromHandle(hWndTop);

	if ( !pWindow )
		return VFALSE;

	VBOOL bResult = VFALSE;

	/* Is it a dialog box?*/
	if ( pWindow->IsVDialogType() )
	{
		bResult = IsDialogMessage(hWndTop, (MSG*)&msg);

		/* Is it a modeless property sheet?*/
		if (	!bResult &&
				pWindow->GetRTTI() == VWindow::VWCL_RTTI_PROPERTY_SHEET &&
				!((VDialog*)pWindow)->IsModal() )
			bResult = PropSheet_IsDialogMessage(hWndTop, &msg);
	}

	/* Return result.*/
	return bResult;
}
Esempio n. 2
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	// создание главного окна
	HWND hwnd;
	MSG msg;
	WNDCLASS w;

	memset(&w, 0, sizeof(WNDCLASS));
	w.style = CS_HREDRAW | CS_VREDRAW;
	w.lpfnWndProc = WndProc;
	w.hInstance = hInstance;
	w.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	w.lpszClassName = L"Основное окно";

	//регистрируем класс окна
	RegisterClass(&w);

	hwnd = CreateWindow(w.lpszClassName, w.lpszClassName, WS_OVERLAPPEDWINDOW, 10, 10, 290, 100, NULL, NULL, hInstance, NULL);

	ShowWindow(hwnd, nCmdShow);
	UpdateWindow(hwnd);

	// добавление кнопки на главное окно
	CreateWindow(L"Button", L"Создать модальный диалог!", WS_CHILD | WS_VISIBLE, 10, 10, 250, 30, hwnd, (HMENU)ID_BUTTON, hInstance, NULL);

	//запускаем цикл обработки сообщений
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (hDlgModal == 0 || !IsDialogMessage(hDlgModal, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	return msg.wParam;
}
Esempio n. 3
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                     LPSTR lpszCmdParam, int nCmdShow)
{
  MSG msg;
  bstr *str;

  product = GetProduct();

  str = bstr_new();
  bstr_assign(str, "Are you sure you want to uninstall ");
  bstr_append(str, product);
  bstr_append(str, " ?");
  if (MessageBox(NULL, str->text, "Uninstall", MB_YESNO) == IDNO)
    return (1);
  bstr_free(str, TRUE);

  hInst = hInstance;
  if (!hPrevInstance)
    RegisterSepClass(hInstance);

  mainDlg = CreateDialog(hInstance, MAKEINTRESOURCE(1), NULL, MainDlgProc);
  SetGuiFont(mainDlg);

  EnableWindow(GetDlgItem(mainDlg, BT_DELOK), FALSE);
  ShowWindow(mainDlg, SW_SHOW);
  ShowWindow(GetDlgItem(mainDlg, ST_DELDONE), SW_HIDE);

  while (GetMessage(&msg, NULL, 0, 0)) {
    if (!IsDialogMessage(mainDlg, &msg)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  return 0;
}
Esempio n. 4
0
bool GWMain::processMessage()
{
	while (PeekMessage(&currentMsg, NULL, 0, 0, PM_REMOVE)) {
		// Check for exit.
		if (currentMsg.message == WM_QUIT) {
			exitCode = currentMsg.wParam;
       	return false;
		}
		// Dialog boxes need to have their messages
		// translated differently.
		GWWindow* win = GWMap::getWindow(currentMsg.hwnd);
		if (win && dynamic_cast<GWDialog*>(win))
			if (IsDialogMessage(currentMsg.hwnd,&currentMsg))
				return true;

      if (hAccel && TranslateAccelerator(currentMsg.hwnd,hAccel,&currentMsg))
         return true;

		// Normal translate/dispatch
		TranslateMessage(&currentMsg);
		DispatchMessage(&currentMsg);
   }
	return true;
}
Esempio n. 5
0
File: swas.cpp Progetto: Kerogi/swas
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{

	HWND hDlg = CreateDialogParam(hInstance, MAKEINTRESOURCE(IDD_DLG_MAIN), NULL , DlgProc, reinterpret_cast<LPARAM>(hInstance));
	ShowWindow(hDlg, SW_SHOW);


	// Main message loop:
	BOOL ret;
	MSG msg;

	while (GetMessage(&msg, NULL, 0, 0))
	{
		if(!IsDialogMessage(hDlg, &msg)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}
Esempio n. 6
0
static LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
   LPMSG lpMsg = (LPMSG) lParam;

   if ( (nCode >= 0) && (wParam == PM_REMOVE) )
   {
      // Don't translate non-input events.
      if ( (lpMsg->message >= WM_KEYFIRST) && (lpMsg->message <= WM_KEYLAST) )
      {
         if ( IsDialogMessage(s_hDlg, lpMsg) )
         {
            // The value returned from this hookproc is ignored, 
            // and it cannot be used to tell Windows the message has been handled.
            // To avoid further processing, convert the message to WM_NULL 
            // before returning.
            lpMsg->message = WM_NULL;
            lpMsg->lParam  = 0;
            lpMsg->wParam  = 0;
         }
      }
   }

   return CallNextHookEx(s_hMsgHook, nCode, wParam, lParam);
}
Esempio n. 7
0
/*
================
rvGETransformer::GetMsgProc

Ensures normal dialog functions work in the transformer dialog
================
*/
LRESULT FAR PASCAL rvGETransformer::GetMsgProc ( int nCode, WPARAM wParam, LPARAM lParam )
{
   LPMSG lpMsg = (LPMSG) lParam;

   if ( nCode >= 0 && PM_REMOVE == wParam )
   {
	  // Don't translate non-input events.
	  if ( lpMsg->message != WM_SYSCHAR && (lpMsg->message >= WM_KEYFIRST && lpMsg->message <= WM_KEYLAST) )
	  {
		 if ( IsDialogMessage( gTransDlg, lpMsg) )
		 {
			// The value returned from this hookproc is ignored,
			// and it cannot be used to tell Windows the message has been handled.
			// To avoid further processing, convert the message to WM_NULL
			// before returning.
			lpMsg->message = WM_NULL;
			lpMsg->lParam  = 0;
			lpMsg->wParam  = 0;
		 }
	  }
   }

   return CallNextHookEx(gTransHook, nCode, wParam, lParam);
}
Esempio n. 8
0
//============================================================================================
//   MAIN
//============================================================================================
extern "C" int WINAPI WinMain(  HINSTANCE hInstance,      // handle to current instance
                                HINSTANCE hPrevInstance,  // handle to previous instance
                                LPSTR lpCmdLine,          // command line
                                int nCmdShow   ){         // show state

  HANDLE hMutex;
  TCHAR szTokens[] = "-/";
  LPCTSTR lpszToken;
  int iRes;
  HWND hDlgWnd;
  UINT uiTimerID; 
  HRESULT hr;


  // Check for another instance
  hMutex = OpenMutex( SYNCHRONIZE,  // requested access (lowest possible)
                      FALSE,  // allow inheritance (does not matter)
                      x_szMutexName);  // unique name

  if(hMutex){
    MessageBox( NULL, "Cannot start the application because another instance is already running.\n", 
                x_szTitle, MB_OK | MB_ICONERROR );
    return 1;
  }

  hMutex = CreateMutex( NULL,  // default security
                        TRUE,  // obtain ownership
                        x_szMutexName);  // unique name
  if(!hMutex){
    MessageBox( NULL, "Cannot create application mutex.\n", 
                x_szTitle, MB_OK | MB_ICONERROR );
    return 1;
  }



  // Parse the command line for options
  lpszToken = FindOneOf(lpCmdLine, szTokens);
  while (lpszToken != NULL) {
    if (lstrcmpi(lpszToken, "UnregServer")==0) {
      iRes = g_UnregisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't unregister server. g_UnregisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is unregistered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    if (lstrcmpi(lpszToken, "RegServer")==0) {
      iRes = g_RegisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't register server. g_RegisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is registered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    lpszToken = FindOneOf(lpszToken, szTokens);
  } // while there are tokens


  
//-------  Windows staff starts here
  CP_printfCreate(x_szTitle); // create console window

  hDlgWnd=CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN_DIALOG),
                      NULL, x_DialogProc); 
  g_hWnd = hDlgWnd;

  SetWindowText(hDlgWnd, x_szTitle);
  SendMessage(hDlgWnd, WM_SETICON, ICON_BIG, 
              (LPARAM)LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON_APPL)));
  SendMessage(hDlgWnd, WM_SETICON, ICON_SMALL, 
             (LPARAM)LoadImage(hInstance, MAKEINTRESOURCE(IDI_ICON_APPL), IMAGE_ICON, 16, 16, 0));
  ShowWindow(hDlgWnd, SW_SHOW); 
  CP_printf(g_szVersion);
  CP_printf("\n\n");
  
  uiTimerID = SetTimer( hDlgWnd,  TIMER_ID,  TIMER_PERIOD_MS,  NULL ); 
 
  if ( uiTimerID == 0){ 
    CP_printf("Error: could not create timer!"); // don't exit we are still functional
  } 

  CP_printfHide();  // default is no log window

  // Init COM using single-thread apartment model
  hr = CoInitialize(NULL); 
  if( hr != S_OK) { 
    MessageBox( NULL, "Error in CoInitializeEx()", x_szTitle, MB_OK);
    return 1;
  }

  iRes = g_Init_LibertyTrack( );
  if( iRes != 0 ) { 
    MessageBox( NULL, "Error: g_Init_LibertyTrack() failed.", x_szTitle, MB_OK);
    return 1;
  }
  // Message loop
  MSG msg;
  while (GetMessage(&msg, 0, 0, 0)) {
    // IsDialogMessage() processes keyboard events for the dialog and
    // passes others to translate/dispatch
    if(!IsDialogMessage(hDlgWnd,&msg)){
      TranslateMessage(&msg);
      DispatchMessage(&msg); 
    }
  }  // end of uMsg loop

  KillTimer( hDlgWnd, TIMER_ID);
	CoUninitialize();
  ReleaseMutex(hMutex); 

  return 0;
}
Esempio n. 9
0
BOOL CSelectUserDlg::PreTranslateMessage(MSG* pMsg)
{
	return IsDialogMessage(pMsg);
}
Esempio n. 10
0
static NTSTATUS ShowUpdateDialogThreadStart(
    __in PVOID Parameter
    )
{
    BOOL result;
    MSG message;
    PH_AUTO_POOL autoPool;

    PhInitializeAutoPool(&autoPool);

    UpdateDialogHandle = CreateDialog(
        (HINSTANCE)PluginInstance->DllBase,
        MAKEINTRESOURCE(IDD_UPDATE),
        PhMainWndHandle,
        UpdaterWndProc
        );

    PhSetEvent(&InitializedEvent);

    while (result = GetMessage(&message, NULL, 0, 0))
    {
        if (result == -1)
            break;

        if (!IsDialogMessage(UpdateDialogHandle, &message))
        {
            TranslateMessage(&message);
            DispatchMessage(&message);
        }

        PhDrainAutoPool(&autoPool);
    }

    PhDeleteAutoPool(&autoPool);
    PhResetEvent(&InitializedEvent);

    // Ensure global objects are disposed and reset when window closes.

    if (SetupFilePath)
    {
        PhDereferenceObject(SetupFilePath);
        SetupFilePath = NULL;
    }

    if (UpdateCheckThreadHandle)
    {
        NtClose(UpdateCheckThreadHandle);
        UpdateCheckThreadHandle = NULL;
    }

    if (DownloadThreadHandle)
    {
        NtClose(DownloadThreadHandle);
        DownloadThreadHandle = NULL;
    }

    if (UpdaterDialogThreadHandle)
    {
        NtClose(UpdaterDialogThreadHandle);
        UpdaterDialogThreadHandle = NULL;
    }

    if (FontHandle)
    {
        DeleteObject(FontHandle);
        FontHandle = NULL;
    }

    FreeXmlData();

    if (UpdateDialogHandle)
    {
        DestroyWindow(UpdateDialogHandle);
        UpdateDialogHandle = NULL;
    }

    return STATUS_SUCCESS;
}
Esempio n. 11
0
	BOOL PreTranslateMessage(MSG* pMsg)
	{
		return IsDialogMessage(pMsg);
	}
BOOL CRepositoryFilterView::PreTranslateMessage(MSG* pMsg)
{
    BOOL retVal = IsDialogMessage(pMsg);
    return retVal;
}
Esempio n. 13
0
//============================================================================================
//   MAIN
//============================================================================================
extern "C" int WINAPI WinMain(  HINSTANCE hInstance,      // handle to current instance
                                HINSTANCE hPrevInstance,  // handle to previous instance
                                LPSTR lpCmdLine,          // command line
                                int nCmdShow   ){         // show state

  TCHAR szTokens[] = "-/";
  int iRes;
  HWND hDlgWnd;
  UINT uiTimerID; 
  HRESULT hr;

  // Parse the command line for options
  LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
  while (lpszToken != NULL) {
    if (lstrcmpi(lpszToken, "UnregServer")==0) {
      iRes = g_UnregisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't unregister server. g_UnregisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is unregistered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    if (lstrcmpi(lpszToken, "RegServer")==0) {
      iRes = g_RegisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't register server. g_RegisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is registered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    lpszToken = FindOneOf(lpszToken, szTokens);
  } // while there are tokens


  
//-------  Windows staff starts here
  CP_printfCreate(x_szTitle); // create console window

  hDlgWnd=CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN_DIALOG),
                      NULL, x_DialogProc); 
  SetWindowText(hDlgWnd, x_szTitle);
  SendMessage(hDlgWnd, WM_SETICON, ICON_BIG, 
              (LPARAM)LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON_APPL)));
  SendMessage(hDlgWnd, WM_SETICON, ICON_SMALL, 
             (LPARAM)LoadImage(hInstance, MAKEINTRESOURCE(IDI_ICON_APPL), IMAGE_ICON, 16, 16, 0));
//  SetWindowText(GetDlgItem(hDlgWnd, IDC_LBL_VERSION ) , g_szVersion);
  ShowWindow(hDlgWnd, SW_SHOW); 
  CP_printf(g_szVersion);
  CP_printf("\n\n");
  
  uiTimerID = SetTimer( hDlgWnd,  TIMER_ID,  TIMER_PERIOD_MS,  NULL ); 
 
  if ( uiTimerID == 0){ 
    CP_printf("Error: could not create timer!"); // don't exit we are still functional
  } 


  // Init COM using multi-threaded model

  hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);    //COINIT_APARTMENTTHREADED
  if( hr != S_OK) { 
    MessageBox( NULL, "Error in CoInitializeEx()", x_szTitle, MB_OK);
    return 1;
  }

  iRes = g_Init_EyeTrack( );
  if( iRes != 0 ) { 
    MessageBox( NULL, "Error: g_Init_EyeTrack() failed.", x_szTitle, MB_OK);
    return 1;
  }
  // Message loop
  MSG msg;
  while (GetMessage(&msg, 0, 0, 0)) {
    // Process dialog messages in IsDialogMessage() pass others to translate/dispatch
    if(!IsDialogMessage(hDlgWnd,&msg)){
      TranslateMessage(&msg);
      DispatchMessage(&msg); 
    }
  }  // end of message loop
  KillTimer( hDlgWnd, TIMER_ID);
	CoUninitialize();

  return 0;
}
Esempio n. 14
0
//================================================================================================
//--------------------------------------------------==-+++--> Entry Point of Program Using WinMain:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	WNDCLASS wndclass;
	HWND hwndMain;
	MSG msg;
	int updated;
	
	(void)hPrevInstance;
	(void)nCmdShow;
	
	#if defined(__GNUC__) && defined(_DEBUG)
	#	ifdef _WIN64
	#		define LoadExcHndl() LoadLibraryExA("dbg\\64\\exchndl", NULL, LOAD_WITH_ALTERED_SEARCH_PATH)
	#	else
	#		define LoadExcHndl() LoadLibraryExA("dbg\\exchndl", NULL, LOAD_WITH_ALTERED_SEARCH_PATH)
	#	endif
	#else
	#	define LoadExcHndl()
	#endif
	LoadExcHndl(); // LOAD_WITH_ALTERED_SEARCH_PATH works :P At least since Win2k
	
	g_instance = hInstance;
	if(LoadClockAPI("misc/T-Clock" ARCH_SUFFIX, &api)){
		MessageBox(NULL, "Error loading: T-Clock" ARCH_SUFFIX ".dll", "API error", MB_OK|MB_ICONERROR);
		return 2;
	}
	chdir(api.root); // make sure we've got the right working directory
	
	// Make sure we're running Windows 2000 and above
	if(!api.OS) {
		MessageBox(NULL,"T-Clock requires Windows 2000 or newer","old OS",MB_OK|MB_ICONERROR);
		return 1;
	}
	
	// make sure ObjectBar isn't running -> From Original Code/Unclear if This is Still a Conflict. (test suggested not really.. no crash but no clock either :P)
	if(FindWindow("ObjectBar Main","ObjectBar")) {
		MessageBox(NULL,"ObjectBar and T-Clock can't be run together","ObjectBar detected!",MB_OK|MB_ICONERROR);
		return 1;
	}
	
	// Load ALL of the Global Resources
	g_hIconTClock = LoadIcon(api.hInstance, MAKEINTRESOURCE(IDI_MAIN));
	g_hIconPlay = LoadImage(g_instance, MAKEINTRESOURCE(IDI_PLAY), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	g_hIconStop = LoadImage(g_instance, MAKEINTRESOURCE(IDI_STOP), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	g_hIconDel  = LoadImage(g_instance, MAKEINTRESOURCE(IDI_DEL), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	
//	FindTrayServer(hwndMain);
	
	// Make sure we're not running 32bit on 64bit OS / start the other one
	#ifndef _WIN64
	if(IsWow64()){
		hwndMain = FindWindow(g_szClassName, NULL);
		if(hwndMain) { // send commands to existing instance
			ProcessCommandLine(hwndMain,lpCmdLine);
		}else{ // start new instance
			char clock64[MAX_PATH];
			memcpy(clock64, api.root, api.root_len+1);
			add_title(clock64,"Clock" ARCH_SUFFIX_64 ".exe");
			api.Exec(clock64,lpCmdLine,NULL);
		}
		return 0;
	}
	#endif // _WIN64
	
	// Do Not Allow the Program to Execute Twice!
	updated = 25; /**< wait up to 5 sec in 1/5th seconds for other instance */
	do{
		HANDLE processlock=CreateMutex(NULL,FALSE,g_szClassName); // we leak handle here, but Windows closes on process exit anyway (so why do it manually?)
		if(processlock && GetLastError()==ERROR_ALREADY_EXISTS){
			CloseHandle(processlock);
			hwndMain = FindWindow(g_szClassName, NULL);
			if(hwndMain) { // This One Sends Commands to the Instance
				ProcessCommandLine(hwndMain,lpCmdLine); // That is Currently Running.
				return 0;
			}
			Sleep(200);
			continue;
		}
		break;
	}while(updated--);
	
	// Update settings if required and setup defaults
	if((updated=CheckSettings())<0){
		return 1;
	}
	CancelAllTimersOnStartUp();
	
	// Message of the taskbar recreating - Special thanks to Mr.Inuya
	g_WM_TaskbarCreated = RegisterWindowMessage("TaskbarCreated");
	
	// register a window class
	wndclass.style         = 0;
	wndclass.lpfnWndProc   = WndProc;
	wndclass.cbClsExtra    = 0;
	wndclass.cbWndExtra    = 0;
	wndclass.hInstance     = g_instance;
	wndclass.hIcon         = g_hIconTClock;
	wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH)(intptr_t)(COLOR_WINDOW+1);
	wndclass.lpszMenuName  = NULL;
	wndclass.lpszClassName = g_szClassName;
	g_atomTClock = RegisterClass(&wndclass);
	
	if(api.OS >= TOS_VISTA) { // allow non elevated processes to send control messages (eg, App with admin rights, explorer without)
		#define MSGFLT_ADD 1
		#define MSGFLT_REMOVE 2
		typedef BOOL (WINAPI* ChangeWindowMessageFilter_t)(UINT message,DWORD dwFlag);
		ChangeWindowMessageFilter_t ChangeWindowMessageFilter=(ChangeWindowMessageFilter_t)GetProcAddress(GetModuleHandle("user32"), "ChangeWindowMessageFilter");
		if(ChangeWindowMessageFilter){
			int msgid;
			ChangeWindowMessageFilter(g_WM_TaskbarCreated,MSGFLT_ADD);
			ChangeWindowMessageFilter(WM_COMMAND,MSGFLT_ADD);
			for(msgid=WM_MOUSEFIRST; msgid<=WM_MOUSELAST; ++msgid)
				ChangeWindowMessageFilter(msgid,MSGFLT_ADD);
			for(msgid=MAINMFIRST; msgid<=MAINMLAST; ++msgid)
				ChangeWindowMessageFilter(msgid,MSGFLT_ADD);
		}
	}
	
	// create a hidden window
	g_hwndTClockMain = hwndMain = CreateWindowEx(WS_EX_NOACTIVATE, MAKEINTATOM(g_atomTClock),NULL, 0, 0,0,0,0, NULL,NULL,g_instance,NULL);
	// This Checks for First Instance Startup Options
	ProcessCommandLine(hwndMain,lpCmdLine);
	
	GetHotKeyInfo(hwndMain);
	
	if(api.OS > TOS_2000) {
		if(api.GetInt("Desktop", "MonOffOnLock", 0))
			RegisterSession(hwndMain);
	}
	if(updated==1){
		PostMessage(hwndMain,WM_COMMAND,IDM_SHOWPROP,0);
	}
	while(GetMessage(&msg, NULL, 0, 0)) {
		if(!(g_hwndSheet && IsWindow(g_hwndSheet) && PropSheet_IsDialogMessage(g_hwndSheet,&msg))
		&& !(g_hDlgTimer && IsWindow(g_hDlgTimer) && IsDialogMessage(g_hDlgTimer,&msg))
		&& !(g_hDlgTimerWatch && IsWindow(g_hDlgTimerWatch) && IsDialogMessage(g_hDlgTimerWatch,&msg))
		&& !(g_hDlgStopWatch && IsWindow(g_hDlgStopWatch) && IsDialogStopWatchMessage(g_hDlgStopWatch,&msg))){
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	
	UnregisterHotKey(hwndMain, HOT_TIMER);
	UnregisterHotKey(hwndMain, HOT_WATCH);
	UnregisterHotKey(hwndMain, HOT_STOPW);
	UnregisterHotKey(hwndMain, HOT_PROPR);
	UnregisterHotKey(hwndMain, HOT_CALEN);
	UnregisterHotKey(hwndMain, HOT_TSYNC);
	
	UnregisterSession(hwndMain);
	
	EndNewAPI(NULL);
	
	return (int)msg.wParam;
}
Esempio n. 15
0
WPARAM CFidgetApp::Run(void)
{
    HACCEL hAccelTable = LoadAccelerators(m_hInstance, (LPCTSTR)IDC_FIDGET);

    // Main message loop:
    //
    WPARAM iReturn = 0;
    bool bFinished = false;
    while (!bFinished)
    {
        CLinearTimeAbsolute ltaCurrent;
        ltaCurrent.GetUTC();

        // Execute background tasks at specifically scheduled times.
        //
        scheduler.RunTasks(ltaCurrent);
        CLinearTimeAbsolute ltaWakeUp;
        if (!scheduler.WhenNext(&ltaWakeUp))
        {
            ltaWakeUp = ltaCurrent + time_30m;
        }
        else if (ltaWakeUp < ltaCurrent)
        {
            // This is necessary to deal with computer time jumping backwards
            // which can happen when someone sets or resets the computer clock.
            //
            ltaWakeUp = ltaCurrent;
        }

        CLinearTimeDelta ltdTimeOut = ltaWakeUp - ltaCurrent;
        DWORD dwTimeout = ltdTimeOut.ReturnMilliseconds();

        DWORD nHandles = 0;
        DWORD dwObject = MsgWaitForMultipleObjectsEx(nHandles, NULL, dwTimeout, QS_ALLINPUT, 0);
        if (WAIT_OBJECT_0 + nHandles == dwObject)
        {
            for (; !bFinished;)
            {
                // There is at least one new message waiting to be processed.
                //
                MSG msg;
                BOOL bGM = GetMessage(&msg, NULL, 0, 0);
                if (0 == bGM)
                {
                    // WM_QUIT message was received. It is time to terminate
                    // ourselves.
                    //
                    iReturn = msg.wParam;
                    bFinished = true;
                }
                else if (-1 == bGM)
                {
                    // An unexpected problem occured.
                    //
                    bFinished = true;
                }
                else
                {
                    // Translate and dispatch message to Windows Procedure.
                    //
                    if (  (  NULL == m_hwndNewSession
                          || !IsDialogMessage(m_hwndNewSession, &msg))
                       && (  NULL == m_hwndAbout
                          || !IsDialogMessage(m_hwndAbout, &msg))
                       && !TranslateMDISysAccel(g_theApp.m_pMainFrame->m_pMDIControl->m_hwnd, &msg)
                       && !TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
                    {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                    }
                }

                // We must process all messages in the queue before making
                // another MsgWaitForMultipleObjectsEx() call.
                //
                if (!PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE|PM_NOYIELD))
                {
                    break;
                }
            }
        }
        else if (WAIT_TIMEOUT != dwObject)
        {
            // An unexpected event occured.
            //
            bFinished = true;
        }

        // It's time to perform some background task.
        //
    }
    DestroyAcceleratorTable(hAccelTable);
    return iReturn;
}
Esempio n. 16
0
LONG PhMainMessageLoop(
    VOID
)
{
    BOOL result;
    MSG message;
    HACCEL acceleratorTable;

    acceleratorTable = LoadAccelerators(PhInstanceHandle, MAKEINTRESOURCE(IDR_MAINWND_ACCEL));

    while (result = GetMessage(&message, NULL, 0, 0))
    {
        BOOLEAN processed = FALSE;
        ULONG i;

        if (result == -1)
            return 1;

        if (FilterList)
        {
            for (i = 0; i < FilterList->Count; i++)
            {
                PPH_MESSAGE_LOOP_FILTER_ENTRY entry = FilterList->Items[i];

                if (entry->Filter(&message, entry->Context))
                {
                    processed = TRUE;
                    break;
                }
            }
        }

        if (!processed)
        {
            if (
                message.hwnd == PhMainWndHandle ||
                IsChild(PhMainWndHandle, message.hwnd)
            )
            {
                if (TranslateAccelerator(PhMainWndHandle, acceleratorTable, &message))
                    processed = TRUE;
            }

            if (DialogList)
            {
                for (i = 0; i < DialogList->Count; i++)
                {
                    if (IsDialogMessage((HWND)DialogList->Items[i], &message))
                    {
                        processed = TRUE;
                        break;
                    }
                }
            }
        }

        if (!processed)
        {
            TranslateMessage(&message);
            DispatchMessage(&message);
        }

        PhDrainAutoPool(&BaseAutoPool);
    }

    return (LONG)message.wParam;
}
Esempio n. 17
0
int32_t startwin_idle(void *v)
{
    if (!startupdlg || !IsWindow(startupdlg)) return 0;
    if (IsDialogMessage(startupdlg, (MSG*)v)) return 1;
    return 0;
}
Esempio n. 18
0
int WINAPI _tWinMain(HINSTANCE hinstExe, HINSTANCE, PTSTR pszCmdLine, int) {

   // Counter fiber execution context
   PVOID pFiberCounter = NULL;   

   // Convert this thread to a fiber.

   /* Converts the current thread into a fiber. 
    * You must convert a thread into a fiber 
	* before you can schedule other fibers. */
   g_FiberInfo.pFiberUI = ConvertThreadToFiber(NULL);

   /* Allocates a fiber local storage (FLS) index. 
    * Any fiber in the process can subsequently use this index 
	* to store and retrieve values that are local to the fiber. */
   g_dwSlot = FlsAlloc(LogMessage);
   FlsSetValue(g_dwSlot, TEXT("UI fiber"));


   // Create the application's UI window.
   g_FiberInfo.hwnd = CreateDialog(hinstExe, MAKEINTRESOURCE(IDD_COUNTER), 
      NULL, Dlg_Proc);

   // Update the window showing which fiber is executing.
   SetDlgItemText(g_FiberInfo.hwnd, IDC_FIBER, TEXT("User interface"));

   // Initially, there is no background processing to be done.
   g_FiberInfo.bps = BPS_DONE;

   // While the UI window still exists...
   BOOL fQuit = FALSE;
   while (!fQuit) {

      // UI messages are higher priority than background processing.
      MSG msg;
	  /* Dispatches incoming sent messages, checks 
	   * the thread message queue for a posted message, 
	   * and retrieves the message (if any exist). 
	   * PM_REMOVE 0x0001 
	   * Messages are removed from the queue after processing by PeekMessage.
	   */
      if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {

         // If a message exists in the queue, process it.
	     /* Determines whether a message is intended 
		  * for the specified dialog box and, 
		  * if it is, processes the message. 
		  * hDlg [in] Type: HWND A handle to the dialog box.
          * lpMsg [in] Type: LPMSG A pointer to an MSG structure 
		  * that contains the message to be checked.
		  */
         if (!IsDialogMessage(g_FiberInfo.hwnd, &msg)) 
		 {
			 /* Translates virtual-key messages into character messages. 
			  * The character messages are posted to the calling thread's message queue, 
			  * to be read the next time the thread calls the GetMessage or PeekMessage function */
             TranslateMessage(&msg);
			 /* Dispatches a message to a window procedure. 
			  * It is typically used to dispatch a message retrieved by the GetMessage function. */
             DispatchMessage(&msg);
         }

         fQuit = (msg.message == WM_QUIT);
         
         if (fQuit)
         {
            // Release FLS slot
            FlsFree(g_dwSlot);

            // The background processing must be stopped. 
            if (pFiberCounter != NULL) { 
               // A recalculation fiber exists; delete it
               DeleteFiber(pFiberCounter); 
               pFiberCounter = NULL; 
            }
         
            // Quit the fiber mode and return to simple thread mode
            ConvertFiberToThread();
            g_FiberInfo.pFiberUI = NULL;
         }
         
      } else {

         // No UI msgs exist; check the state of the background processing.
         switch (g_FiberInfo.bps) {
            case BPS_DONE:
               // No background processing to do; wait for a UI event.
               /* Yields control to other threads when a thread has no other messages 
			    * in its message queue. 
				* The WaitMessage function suspends the thread 
				* and does not return until a new message 
				* is placed in the thread's message queue. */
               WaitMessage();
               break;

            case BPS_STARTOVER:
               // User changed the count; 
               // cancel the current background processing.
               if (pFiberCounter != NULL) { 
                  // A recalculation fiber exists; delete it so that
                  // background processing starts over from the beginning.
                  DeleteFiber(pFiberCounter); 
                  pFiberCounter = NULL; 
               }

               // Convert this thread to a fiber if needed.
               if (g_FiberInfo.pFiberUI == NULL)
                  g_FiberInfo.pFiberUI = ConvertThreadToFiber(NULL);

               LogMessage(TEXT("convert UI thread to fiber..."));

               // Create a new recalc fiber that starts from the beginning.
               pFiberCounter = CreateFiber(0, FiberFunc, &g_FiberInfo);

               // The background processing started; it should continue.
               g_FiberInfo.bps = BPS_CONTINUE;

               // Fall through to BPS_CONTINUE case...

            case BPS_CONTINUE:
               // Allow the background processing to execute...
               SwitchToFiber(pFiberCounter);

               // The background processing has been paused 
               // (because a UI message showed up) or has been 
               // stopped (because the counting has completed).

               // Update the window showing which fiber is executing.
               SetDlgItemText(g_FiberInfo.hwnd, IDC_FIBER, 
                  TEXT("User interface"));

               if (g_FiberInfo.bps == BPS_DONE) { 
                  // The background processing ran to completion. Delete the
                  // fiber so that processing will restart next time.
                  DeleteFiber(pFiberCounter); 
                  pFiberCounter = NULL; 
               
                  // Quit the fiber mode and return to simple thread mode
                  ConvertFiberToThread();
                  g_FiberInfo.pFiberUI = NULL;
               }
               break;
         }  // switch on background processing state

      }  // No UI messages exist
   }  // while the window still exists

   DestroyWindow(g_FiberInfo.hwnd); 

   return(0);  // End the application.
}
Esempio n. 19
0
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nShowCmd)
{
    MSG		msg;
    HACCEL	hAccel;
    TCHAR	arg[MAX_PATH];
    TCHAR *	pszCmdline;

    EnableCrashingOnCrashes();

    //INITCOMMONCONTROLSEX icx = { sizeof(icx), ICC_
    g_hInstance = hInst;

    // This program requires COM
    OleInitialize(0);

    //
    //	Commandline processing
    //

    pszCmdline = GetArg(GetCommandLineW(), arg, MAX_PATH);

    if(pszCmdline && *pszCmdline == '-')
    {
        pszCmdline = GetArg(pszCmdline, arg, MAX_PATH);

        // 'touch' the specified file!
        if(lstrcmpi(arg, TEXT("-touch")) == 0)
        {
            // check to see if it's a quoted filename
            if(*pszCmdline == '\"')
            {
                GetArg(pszCmdline, arg, MAX_PATH);
                pszCmdline = arg;
            }

            if(!TouchFile(pszCmdline))
            {
                HexWinErrorBox(GetLastError(), 0);
                return 1;
            }
            return 0;
        }
        else
        {
            pszCmdline = GetArg(pszCmdline, arg, MAX_PATH);
        }
    }


    {
        INITCOMMONCONTROLSEX icex = { sizeof(icex), -1 };
        InitCommonControlsEx(&icex);
    }

    /*g_Config = OpenConfig(TEXT("mapsize.exe.129082349834.bookmarks"));
    smeg(g_Config, TEXT("bookmarks.bookmark."), TEXT("mapsize.exe"));
    SaveConfig(TEXT("oof.config"), g_Config);*/
    LoadSettings();

    RegisterTabView();
    InitMainWnd();
    CreateMainWnd();


    // open file specified on commmand line?
    if(pszCmdline && *pszCmdline)
    {
        // check to see if it's a quoted filename
        if(*pszCmdline == '\"')
        {
            GetArg(pszCmdline, arg, MAX_PATH);
            pszCmdline = arg;
        }

        if(!HexeditOpenFile(g_hwndMain, pszCmdline, DefaultFileMode()))//HVOF_DEFAULT))
        {
            SendMessage(g_hwndMain, WM_COMMAND, IDM_FILE_NEW, 0);
        }
    }
    // automatically create new document if none specified
    else
    {
        SendMessage(g_hwndMain, WM_COMMAND, IDM_FILE_NEW, 0);
    }

    InitDockingBars(g_hwndMain);

    if(g_fRestoreWinPos)
        nShowCmd = SW_SHOW;

    ShowWindow(g_hwndMain, nShowCmd);

    // force any floating popups (i.e. the DOCKWNDs) to
    // become visible at the same time
    //ShowOwnedPopups(g_hwndMain, TRUE);
    DockWnd_ShowDeferredPopups(g_hwndMain);

    //
    // load keyboard accelerator table
    //
    hAccel = LoadAccelerators(GetModuleHandle(0)/*g_hResourceModule*/, MAKEINTRESOURCE(IDR_ACCELERATOR1));

    //
    // message-pump
    //
    while(GetMessage(&msg, 0, 0, 0) > 0)
    {
        if(!TranslateAccelerator(g_hwndMain, hAccel, &msg))
        {
            if( !IsDialogMessage(g_hwndSearch, &msg) &&
                    !IsDialogMessage(g_hwndGoto, &msg)   &&
                    !DockWnd_IsDialogMessage(g_hwndMain, DWID_TYPEVIEW, &msg) &&
                    !DockWnd_IsDialogMessage(g_hwndMain, DWID_SEARCHBAR, &msg) &&
                    !DockWnd_IsDialogMessage(g_hwndMain, DWID_HIGHLIGHT, &msg)
              )
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }

    SaveSettings();

    // Shutdown COM
    OleUninitialize();

    return 0;
}
Esempio n. 20
0
//----------------------------------------------------------------------
//  
// WinMain
//
// Registers a class. The reason I did this is because the application
// doesn't get cleaned up properly upon exit if winmain just calls
// dialogbox. This was manifested by all the system icons disappearing
// after the program exited. See Petzold's hexcalc example for the base
// of this.
//
//----------------------------------------------------------------------
int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
        				LPSTR lpCmdLine, int nCmdShow )
{	  
	static TCHAR	szAppName [] = TEXT("CACHESET") ;
	MSG				msg ;
	WNDCLASSEX		wndclass ;
	HWND			hDummyWnd;
	int				NTVersion;
	int				len = 256;
	HANDLE			hToken;
	SYSTEM_CACHE_INFORMATION	newCacheSize;
	ULONG			minSize, maxSize;

	// save instance
	hInst = hInstance;

	// init common controls
	InitCommonControls();

	// get NT version
	NTVersion = GetVersion();
	if( NTVersion >= 0x80000000 ) {
		Abort( NULL, TEXT("Not running on Windows NT"));
		return TRUE;
	}

	// Enable increase quota privilege
    if(!OpenProcessToken( GetCurrentProcess(),
				TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
				&hToken )) {
	
		printf("You do not have the necessary privilege to run this program\n");
		return -1;
	}

    // Enable SeDebugPrivilege
    if(!SetPrivilege(hToken, SE_INCREASE_QUOTA_NAME, TRUE))
    {

 		Abort(NULL, TEXT("You must have the INCREASE_QUOTA privilege to run CacheSet"));
        CloseHandle(hToken);
        return -1;
    }
	CloseHandle( hToken );

	// locate the calls we need in NTDLL
	LocateNTDLLCalls();

	// If there are command line arguments, set the cache size
	if( lpCmdLine && (sscanf( lpCmdLine," %d %d", &minSize, &maxSize ) == 2) ) {

		// set the cache size 
		newCacheSize.MinimumWorkingSet = minSize * 1024;
		newCacheSize.MaximumWorkingSet = maxSize * 1024;
		NtSetSystemInformation( SYSTEMCACHEINFORMATION,
									   &newCacheSize, sizeof(newCacheSize) );
		return 0;
	}

	// create a dummy class and window that will hide the task tray icon for us
	wndclass.cbSize			= sizeof( WNDCLASSEX );
	wndclass.style          = 0 ;
 	wndclass.lpfnWndProc    = (WNDPROC) DummyProc ;
	wndclass.cbClsExtra     = 0 ;
	wndclass.cbWndExtra     = 0 ;
	wndclass.hInstance      = hInstance ;
	wndclass.hIcon          = LoadIcon (hInstance, "APPICON") ;
	wndclass.hIconSm		= LoadIcon (hInstance, "APPICON");
	wndclass.hCursor        = LoadCursor (NULL, IDC_ARROW) ;
	wndclass.hbrBackground  = (HBRUSH) (COLOR_BTNFACE+1);
	wndclass.lpszMenuName   = NULL ;
	wndclass.lpszClassName  = "Dummy" ;
	RegisterClassEx (&wndclass) ;

	hDummyWnd = CreateWindowEx( WS_EX_TOOLWINDOW, "Dummy", "",
								0, -1, -1, 0, 0, 0, 0, hInstance, 0 );

	// create the main window class
	wndclass.cbSize			= sizeof( WNDCLASSEX );
	wndclass.style          = CS_HREDRAW | CS_VREDRAW ;
 	wndclass.lpfnWndProc    = (WNDPROC) MainDialog ;
	wndclass.cbClsExtra     = 0 ;
	wndclass.cbWndExtra     = DLGWINDOWEXTRA ;
	wndclass.hInstance      = hInstance ;
	wndclass.hIcon          = LoadIcon (hInstance, "APPICON") ;
	wndclass.hIconSm		= LoadIcon (hInstance, "APPICON");
	wndclass.hCursor        = LoadCursor (NULL, IDC_ARROW) ;
	wndclass.hbrBackground  = (HBRUSH) (COLOR_BTNFACE+1);
	wndclass.lpszMenuName   = NULL ;
	wndclass.lpszClassName  = szAppName ;
	RegisterClassEx (&wndclass) ;
 
 	// create the dialog
	hMainDlg = CreateDialog( hInstance, "CACHESET", hDummyWnd, (DLGPROC)MainDialog) ;
	ShowWindow( hMainDlg, nCmdShow) ;
 
	while (GetMessage (&msg, NULL, 0, 0)) {
		if( !IsDialogMessage( hMainDlg, &msg )) {
          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
		}
	}
	return msg.wParam ;
}
Esempio n. 21
0
//========================================================================================
//	/exit		exit T-Clock 2010
//	/prop		show T-Clock 2010 properties
//	/SyncOpt	SNTP options
//	/Sync		synchronize the system clock with an NTP server
//	/start		start the Stopwatch (open as needed)
//	/stop		stop (pause really) the Stopwatch
//	/reset		reset Stopwatch to 0 (stop as needed)
//	/lap		record a (the current) lap time
//================================================================================================
//---------------------------------------------//---------------+++--> T-Clock Command Line Option:
void ProcessCommandLine(HWND hwndMain,const char* cmdline)   //-----------------------------+++-->
{
	int justElevated = 0;
	const char* p = cmdline;
	if(g_hwndTClockMain != hwndMain){
		g_hwndTClockMain = CreateWindow("STATIC",NULL,0,0,0,0,0,HWND_MESSAGE_nowarn,0,0,0);
		SubclassWindow(g_hwndTClockMain, MsgOnlyProc);
	}
	
	while(*p != '\0') {
		if(*p == '/') {
			++p;
			if(strncasecmp(p, "prop", 4) == 0) {
				SendMessage(hwndMain, WM_COMMAND, IDM_SHOWPROP, 0);
				p += 4;
			} else if(strncasecmp(p, "exit", 4) == 0) {
				SendMessage(hwndMain, MAINM_EXIT, 0, 0);
				p += 4;
			} else if(strncasecmp(p, "start", 5) == 0) {
				SendMessage(hwndMain, WM_COMMAND, IDM_STOPWATCH_START, 0);
				p += 5;
			} else if(strncasecmp(p, "stop", 4) == 0) {
				SendMessage(hwndMain, WM_COMMAND, IDM_STOPWATCH_STOP, 0);
				p += 4;
			} else if(strncasecmp(p, "reset", 5) == 0) {
				SendMessage(hwndMain, WM_COMMAND, IDM_STOPWATCH_RESET, 0);
				p += 5;
			} else if(strncasecmp(p, "pause", 5) == 0) {
				SendMessage(hwndMain, WM_COMMAND, IDM_STOPWATCH_PAUSE, 0);
				p += 5;
			} else if(strncasecmp(p, "resume", 6) == 0) {
				SendMessage(hwndMain, WM_COMMAND, IDM_STOPWATCH_RESUME, 0);
				p += 6;
			} else if(strncasecmp(p, "lap", 3) == 0) {
				SendMessage(hwndMain, WM_COMMAND, IDM_STOPWATCH_LAP, 0);
				p += 3;
			} else if(strncasecmp(p, "SyncOpt", 7) == 0) {
				if(HaveSetTimePermissions()){
					if(!SendMessage(hwndMain, WM_COMMAND, MAKEWPARAM(IDM_SNTP,1), 0)){
						NetTimeConfigDialog(justElevated);
					}
				}else{
					SendMessage(hwndMain, WM_COMMAND, IDM_SNTP, 0);
				}
				p += 7;
			} else if(strncasecmp(p, "Sync", 4) == 0) {
				p += 4;
				SendMessage(hwndMain, WM_COMMAND, MAKEWPARAM(IDM_SNTP_SYNC,justElevated), 0);
				if(g_hwndTClockMain == hwndMain)
					SendMessage(hwndMain, MAINM_EXIT, 0, 0);
			} else if(strncmp(p, "Wc", 2) == 0) { // Win10 calendar "restore"
				if(p[2] == '1') // restore to previous
					api.SetSystemInt(HKEY_LOCAL_MACHINE, kSectionImmersiveShell, kKeyWin32Tray, 1);
				else // use the slow (new) one
					api.DelSystemValue(HKEY_LOCAL_MACHINE, kSectionImmersiveShell, kKeyWin32Tray);
				p += 2;
			} else if(strncmp(p, "UAC", 3) == 0) {
				justElevated = 1;
				p += 3;
			}
			continue;
		}
		++p;
	}
	
	if(g_hwndTClockMain != hwndMain){
		const DWORD kTimeout = 10000;
		const DWORD kStartTicks = GetTickCount();
		DWORD timeout;
		MSG msg;
		msg.message = 0;
		for(;;){
			int have_ui = IsWindow(g_hwndSheet) || IsWindow(g_hDlgTimer) || IsWindow(g_hDlgTimerWatch) || IsWindow(g_hDlgSNTP) || IsWindow(g_hDlgStopWatch);
			if(have_ui)
				timeout = INFINITE;
			else if(IsPlaying())
				timeout = 200;
			else
				break;
			MsgWaitForMultipleObjectsEx(0, NULL, timeout, QS_ALLEVENTS, MWMO_INPUTAVAILABLE);
			while(PeekMessage(&msg,NULL,0,0,PM_REMOVE)){
				if(msg.message == WM_QUIT)
					break;
				if(!(g_hwndSheet && IsWindow(g_hwndSheet) && PropSheet_IsDialogMessage(g_hwndSheet,&msg))
				&& !(g_hDlgTimer && IsWindow(g_hDlgTimer) && IsDialogMessage(g_hDlgTimer,&msg))
				&& !(g_hDlgTimerWatch && IsWindow(g_hDlgTimerWatch) && IsDialogMessage(g_hDlgTimerWatch,&msg))
				&& !(g_hDlgSNTP && IsWindow(g_hDlgSNTP) && IsDialogMessage(g_hDlgSNTP,&msg))
				&& !(g_hDlgStopWatch && IsWindow(g_hDlgStopWatch) && IsDialogStopWatchMessage(g_hDlgStopWatch,&msg))){
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
			}
			if(msg.message == WM_QUIT)
				break;
			if(!have_ui) {
				DWORD elapsed = GetTickCount() - kStartTicks;
				if(elapsed >= kTimeout)
					break;
			}
		}
		DestroyWindow(g_hwndTClockMain);
		g_hwndTClockMain = NULL;
	}
}
Esempio n. 22
0
void
mswin_display_splash_window(BOOL show_ver)
{
    MSG msg;
    int left, top;
    RECT splashrt;
    RECT clientrt;
    RECT controlrt;
    HWND hWnd;
    int buttop;
    int strsize = 0;
    int bufsize = BUFSZ;
    char *buf = malloc(bufsize);

    if (buf == NULL)
        panic("out of memory");
    buf[0] = '\0';

    hWnd = CreateDialog(GetNHApp()->hApp, MAKEINTRESOURCE(IDD_SPLASH),
                        GetNHApp()->hMainWnd, NHSplashWndProc);
    if (!hWnd)
        panic("Cannot create Splash window");
    mswin_init_splashfonts(hWnd);
    GetNHApp()->hPopupWnd = hWnd;
    /* Get control size */
    GetWindowRect(GetDlgItem(hWnd, IDOK), &controlrt);
    controlrt.right -= controlrt.left;
    controlrt.bottom -= controlrt.top;
    /* Get current client area */
    GetClientRect(hWnd, &clientrt);
    /* Get window size */
    GetWindowRect(hWnd, &splashrt);
    splashrt.right -= splashrt.left;
    splashrt.bottom -= splashrt.top;
    /* Get difference between requested client area and current value */
    splashrt.right += SPLASH_WIDTH + SPLASH_OFFSET_X * 2 - clientrt.right;
    splashrt.bottom += SPLASH_HEIGHT + controlrt.bottom + SPLASH_OFFSET_Y * 3
                       - clientrt.bottom;
    /* Place the window centered */
    /* On the screen, not on the parent window */
    left = (GetSystemMetrics(SM_CXSCREEN) - splashrt.right) / 2;
    top = (GetSystemMetrics(SM_CYSCREEN) - splashrt.bottom) / 2;
    MoveWindow(hWnd, left, top, splashrt.right, splashrt.bottom, TRUE);
    /* Place the OK control */
    GetClientRect(hWnd, &clientrt);
    MoveWindow(GetDlgItem(hWnd, IDOK),
               (clientrt.right - clientrt.left - controlrt.right) / 2,
               clientrt.bottom - controlrt.bottom - SPLASH_OFFSET_Y,
               controlrt.right, controlrt.bottom, TRUE);
    buttop = clientrt.bottom - controlrt.bottom - SPLASH_OFFSET_Y;
    /* Place the text control */
    GetWindowRect(GetDlgItem(hWnd, IDC_EXTRAINFO), &controlrt);
    controlrt.right -= controlrt.left;
    controlrt.bottom -= controlrt.top;
    GetClientRect(hWnd, &clientrt);
    MoveWindow(GetDlgItem(hWnd, IDC_EXTRAINFO),
               clientrt.left + SPLASH_OFFSET_X,
               buttop - controlrt.bottom - SPLASH_OFFSET_Y,
               clientrt.right - 2 * SPLASH_OFFSET_X, controlrt.bottom, TRUE);

    /* Fill the text control */
    Sprintf(buf, "%s\r\n%s\r\n%s\r\n%s\r\n\r\n", COPYRIGHT_BANNER_A,
            COPYRIGHT_BANNER_B, COPYRIGHT_BANNER_C, COPYRIGHT_BANNER_D);
    strsize = strlen(buf);

    if (show_ver) {
        /* Show complete version information */
        dlb *f;
        char verbuf[BUFSZ];
        int verstrsize = 0;
 
        getversionstring(verbuf);
        verstrsize = strlen(verbuf);
        if (verstrsize + strlen("\r\n\r\n") + 1  <  BUFSZ - 1)
            strcat(verbuf, "\r\n\r\n");
        verstrsize = strlen(verbuf);

        if (strsize + verstrsize + 1 > bufsize) {
            bufsize += BUFSZ;
            buf = realloc(buf, bufsize);
            if (buf == NULL)
                panic("out of memory");
        }
        strcat(buf, verbuf);
        strsize = strlen(buf);
            
        /* Add compile options */
        f = dlb_fopen(OPTIONS_USED, RDTMODE);
        if (f) {
            char line[LLEN + 1];

            while (dlb_fgets(line, LLEN, f)) {
                size_t len;
                len = strlen(line);
                if (len > 0 && line[len - 1] == '\n') {
                    line[len - 1] = '\r';
                    line[len] = '\n';
                    line[len + 1] = '\0';
                    len++;
                }
                if (strsize + (int) len + 1 > bufsize) {
                    bufsize += BUFSZ;
                    buf = realloc(buf, bufsize);
                    if (buf == NULL)
                        panic("out of memory");
                }
                strcat(buf, line);
                strsize += len;
            }
            (void) dlb_fclose(f);
        }
    } else {
        /* Show news, if any */
        if (iflags.news) {
            FILE *nf;

            iflags.news = 0; /* prevent newgame() from re-displaying news */
            nf = fopen(NEWS, "r");
            if (nf != NULL) {
                char line[LLEN + 1];

                while (fgets(line, LLEN, nf)) {
                    size_t len;
                    len = strlen(line);
                    if (len > 0 && line[len - 1] == '\n') {
                        line[len - 1] = '\r';
                        line[len] = '\n';
                        line[len + 1] = '\0';
                        len++;
                    }
                    if (strsize + (int) len + 1 > bufsize) {
                        bufsize += BUFSZ;
                        buf = realloc(buf, bufsize);
                        if (buf == NULL)
                            panic("out of memory");
                    }
                    strcat(buf, line);
                    strsize += len;
                }
                (void) fclose(nf);
            } else {
                strcat(buf, "No news.");
            }
        }
    }
    SetWindowText(GetDlgItem(hWnd, IDC_EXTRAINFO), buf);
    free(buf);
    ShowWindow(hWnd, SW_SHOW);

    while (IsWindow(hWnd) && GetMessage(&msg, NULL, 0, 0) != 0) {
        if (!IsDialogMessage(hWnd, &msg)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    GetNHApp()->hPopupWnd = NULL;
    mswin_destroy_splashfonts();
}
Esempio n. 23
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	MSG msg; int retval;

 	if(InitApp(hInstance, lpCmdLine) == false)
		return 0;

	hWnd = BuildWindow(nCmdShow);
	if(hWnd == NULL)
		return 0;

	// build GUI
	if (!BuildControls(hWnd))
		return 0;

	// Initialize all controls
	ApplySettings();

	// show credits
	char buf[BUFLEN];
	ZeroMemory(buf, BUFLEN);
	strncpy(buf, CREDITS, BUFLEN-1);
	SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)buf);

	while((retval = GetMessage(&msg,NULL,0,0)) != 0)
	{
		// capture key-def events
		if ((msg.hwnd == g_keySwitchLeftControl 
                    || msg.hwnd == g_keySwitchRightControl 
                    || msg.hwnd == g_keyResetControl 
                    || msg.hwnd == g_keyRandomControl 
                    || msg.hwnd == g_keyPrevControl 
                    || msg.hwnd == g_keyNextControl 
                    || msg.hwnd == g_keyPrevValControl 
                    || msg.hwnd == g_keyNextValControl 
                    || msg.hwnd == g_keyInfoPagePrevControl 
                    || msg.hwnd == g_keyInfoPageNextControl 
                    || msg.hwnd == g_keyAction1Control 
                    || msg.hwnd == g_keyAction2Control 
                    || msg.hwnd == g_keySwitch1Control 
                    || msg.hwnd == g_keySwitch2Control 
            ) && (
                msg.message == WM_KEYDOWN 
                    || msg.message == WM_SYSKEYDOWN
            ))
		{
			PostMessage(hWnd, WM_APP_KEYDEF, msg.wParam, (LPARAM)msg.hwnd);
			continue;
		}

		if(retval == -1)
			return 0;	// an error occured while getting a message

		if (!IsDialogMessage(hWnd, &msg)) // need to call this to make WS_TABSTOP work
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return 0;
}
Esempio n. 24
0
BOOL CMapDlg::PreTranslateMessage(MSG* pMsg)
{
	return IsDialogMessage(pMsg);
}
Esempio n. 25
0
/***********************************************************************
 *
 *           WinMain
 */
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE prev, LPTSTR cmdline, int show)
{
    MSG         msg;
    HACCEL      hAccel;
    WNDCLASSEX  wndclass;
    HMONITOR    monitor;
    MONITORINFO info;
    INT         x, y;

    static const TCHAR className[] = _T("NPClass");
    static const TCHAR winName[]   = _T("Notepad");

    UNREFERENCED_PARAMETER(prev);

    aFINDMSGSTRING = (ATOM) RegisterWindowMessage(FINDMSGSTRING);

    ZeroMemory(&Globals, sizeof(Globals));
    Globals.hInstance       = hInstance;
    LoadSettings();

    ZeroMemory(&wndclass, sizeof(wndclass));
    wndclass.cbSize        = sizeof(wndclass);
    wndclass.lpfnWndProc   = NOTEPAD_WndProc;
    wndclass.hInstance     = Globals.hInstance;
    wndclass.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_NPICON));
    wndclass.hCursor       = LoadCursor(0, IDC_ARROW);
    wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wndclass.lpszMenuName  = MAKEINTRESOURCE(MAIN_MENU);
    wndclass.lpszClassName = className;
    wndclass.hIconSm       = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_NPICON),
                            IMAGE_ICON, 16, 16, 0);

    if (!RegisterClassEx(&wndclass)) return FALSE;

    /* Setup windows */

    monitor = MonitorFromRect( &Globals.main_rect, MONITOR_DEFAULTTOPRIMARY );
    info.cbSize = sizeof(info);
    GetMonitorInfoW( monitor, &info );

    x = Globals.main_rect.left;
    y = Globals.main_rect.top;
    if (Globals.main_rect.left >= info.rcWork.right ||
        Globals.main_rect.top >= info.rcWork.bottom ||
        Globals.main_rect.right < info.rcWork.left ||
        Globals.main_rect.bottom < info.rcWork.top)
        x = y = CW_USEDEFAULT;

    Globals.hMainWnd =
        CreateWindow(className, winName, WS_OVERLAPPEDWINDOW,
                     x, y, Globals.main_rect.right - Globals.main_rect.left,
                     Globals.main_rect.bottom - Globals.main_rect.top,
                     NULL, NULL, Globals.hInstance, NULL);
    if (!Globals.hMainWnd)
    {
        ShowLastError();
        ExitProcess(1);
    }

    DoCreateEditWindow();

    NOTEPAD_InitData();
    DIALOG_FileNew();

    ShowWindow(Globals.hMainWnd, show);
    UpdateWindow(Globals.hMainWnd);
    DragAcceptFiles(Globals.hMainWnd, TRUE);

    DIALOG_ViewStatusBar();

    HandleCommandLine(cmdline);

    hAccel = LoadAccelerators( hInstance, MAKEINTRESOURCE(ID_ACCEL) );

    while (GetMessage(&msg, 0, 0, 0))
    {
        if (!IsDialogMessage(Globals.hFindReplaceDlg, &msg) &&
            !TranslateAccelerator(Globals.hMainWnd, hAccel, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    return (int) msg.wParam;
}
Esempio n. 26
0
//
//	Application entry point
//
int WINAPI WinMain(
	HINSTANCE	hInstance,
	HINSTANCE	hPrevInst,
	LPSTR		lpCmdLine,
	int			nCmdShow)
{
	HACCEL		hAccel;
	MSG			msg = { 0 };
	DWORD		err;

	UNREFERENCED_PARAMETER(hPrevInst);
	UNREFERENCED_PARAMETER(nCmdShow);

	//
	//	Reports memory leaks at process termination
	//
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	//
	//	Check the Operating System version
	//
	/*if (!VfdIsValidPlatform()) {
		ShowErrorMessage(0, MSG_ERR_WRONG_PLATFORM);
		return -1;
	}*/

	//
	//	Save the application instance handle
	//
	hAppInst = hInstance;

	//
	//	Process command line parameters
	//
	if (lpCmdLine && *lpCmdLine) {
		CommandLine();
		return 0;
	}

	//
	//	register the custom dialog window class
	//
	{
		WNDCLASS	wc;
		
		GetClassInfo(hInstance, WC_DIALOG, &wc);

		wc.lpszClassName = VFDWIN_APP_BASENAME;

		RegisterClass(&wc);
	}

	//
	//	Find if another instance of VfdWin is running
	//
	{
		HWND	hWnd;

		hWnd = FindWindow(VFDWIN_APP_BASENAME, NULL);

		if (hWnd) {

			//	bring to the foreground

			ShowWindow(hWnd, SW_RESTORE);
			SetForegroundWindow(hWnd);

			return 0;
		}
	}

	//
	//	Store application executable file path
	//
	err = GetModuleFileName(NULL, sAppPath, sizeof(sAppPath));

	if (err == 0) {
		err = GetLastError();

		VFDTRACE(0,("WinMain : GetModuleFileName() - %s",
			GetSystemMessage(err)));

		ShowErrorMessage(err, MSG_ERR_APP_INTERNAL);

		goto cleanup;
	}

	pAppBase = sAppPath + err;

	while (pAppBase > sAppPath && *(pAppBase - 1) != '\\') {
		pAppBase--;
	}

	//
	//	initialize ole and common controls
	//
	if (!SUCCEEDED(CoInitialize(NULL))) {
		err = GetLastError();

		VFDTRACE(0,("WinMain : CoInitialize() - %s",
			GetSystemMessage(err)));

		ShowErrorMessage(err, MSG_ERR_APP_INTERNAL);

		goto cleanup;
	}

	InitCommonControls();

	//
	//	Create the main dialog window
	//
	hMainWnd = CreateDialog(
		hInstance,
		MAKEINTRESOURCE(IDD_MAIN),
		NULL,
		MainProc);

	if (hMainWnd == NULL) {
		err = GetLastError();

		VFDTRACE(0,("WinMain : CreateDialog - %s",
			GetSystemMessage(err)));

		ShowErrorMessage(err, MSG_ERR_APP_INTERNAL);

		goto cleanup;
	}

	hAccel = LoadAccelerators(hInstance,
		MAKEINTRESOURCE(IDR_ACCELERATOR));

	if (hAccel == NULL) {
		VFDTRACE(0,("WinMain : LoadAccelerators - %s",
			GetSystemMessage(GetLastError())));
	}

	//
	//	Message loop
	//
	for (;;) {
		BOOL ret = GetMessage(&msg, NULL, 0, 0);

		if (ret == 0) {
			break;
		}
		else if (ret == -1) {
			err = GetLastError();

			VFDTRACE(0,("WinMain: GetMessage - %s",
				GetSystemMessage(err)));

			ShowErrorMessage(err, MSG_ERR_APP_INTERNAL);

			break;
		}

		if (!TranslateAccelerator(hMainWnd, hAccel, &msg) &&
			!IsDialogMessage(hMainWnd, &msg)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

cleanup:
	CoUninitialize();

	return msg.wParam;
}
Esempio n. 27
0
BOOL CStreamEditorView::PreTranslateMessage(MSG* pMsg)
{
	return IsDialogMessage(pMsg);
}
Esempio n. 28
0
//----------------------------------------------------------------------
//
// WinMain
//
// Initialize a dialog window class and pop the autologon dialog.
//
//----------------------------------------------------------------------
int WINAPI WinMain(	HINSTANCE hInstance, 
				   HINSTANCE hPrevInstance,	
				   LPSTR lpCmdLine,
				   int nCmdShow )
{
	static TCHAR	szAppName [] = TEXT("NOTMYFAULT") ;
	MSG				msg ;	   
	HWND			hMainDlg;
	WNDCLASSEX		wndclass ;
	PWSTR			*cmdLine;
	int				numArgs, i;
	DWORD			nb;

	cmdLine = CommandLineToArgvW( GetCommandLineW(), &numArgs );
	for( i = 0; i < numArgs; i++ ) {

		if( cmdLine[i][0] == '/' ||
			cmdLine[i][0] == '-' ) {

			if( !_wcsicmp( &cmdLine[i][1], L"crash" )) {

				if( StartMyFaultDriver( NULL )) {

					DeviceIoControl(SysHandle, IOCTL_IRQL, NULL, 0, NULL, 0, &nb, NULL );
				}
			} else {

				MessageBox( NULL, "Usage: notmyfault [/crash]\n"
						"/crash    Crashes the system.", "NotMyFault", MB_ICONERROR );
				return -1;
			}
		}
	}

	//
	// Create the main window class
	//
	wndclass.cbSize			= sizeof( WNDCLASSEX );
	wndclass.style          = CS_HREDRAW | CS_VREDRAW ;
 	wndclass.lpfnWndProc    = (WNDPROC) MainDialog ;
	wndclass.cbClsExtra     = 0 ;
	wndclass.cbWndExtra     = DLGWINDOWEXTRA ;
	wndclass.hInstance      = hInstance ;
	wndclass.hIcon          = LoadIcon (hInstance, "APPICON") ;
	wndclass.hIconSm		= LoadIcon (hInstance, "APPICON");
	wndclass.hCursor        = LoadCursor (NULL, IDC_ARROW) ;
	wndclass.hbrBackground  = (HBRUSH) (COLOR_BTNFACE+1);
	wndclass.lpszMenuName   = NULL ;
	wndclass.lpszClassName  = szAppName ;
	RegisterClassEx (&wndclass) ;
 
	//
 	// Create the dialog
	//
	hMainDlg = CreateDialog( hInstance, "NOTMYFAULT", NULL, (DLGPROC)MainDialog) ;
	ShowWindow( hMainDlg, nCmdShow) ;
 
	while (GetMessage (&msg, NULL, 0, 0)) {
		if( !IsDialogMessage( hMainDlg, &msg )) {
          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
		}
	}
	return (int) msg.wParam ;
}
Esempio n. 29
0
void ShowErrorPane(const char *text)
{
	if (Window == NULL || ConWindow == NULL)
	{
		if (text != NULL)
		{
			MessageBox (Window, text,
				GAMESIG " Fatal Error", MB_OK|MB_ICONSTOP|MB_TASKMODAL);
		}
		return;
	}

	if (StartScreen != NULL)	// Ensure that the network pane is hidden.
	{
		StartScreen->NetDone();
	}
	if (text != NULL)
	{
		char caption[100];
		mysnprintf(caption, countof(caption), "Fatal Error - " GAMESIG " %s " X64 " (%s)", GetVersionString(), GetGitTime());
		SetWindowText (Window, caption);
		ErrorIcon = CreateWindowEx (WS_EX_NOPARENTNOTIFY, "STATIC", NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_OWNERDRAW, 0, 0, 0, 0, Window, NULL, g_hInst, NULL);
		if (ErrorIcon != NULL)
		{
			SetWindowLong (ErrorIcon, GWL_ID, IDC_ICONPIC);
		}
	}
	ErrorPane = CreateDialogParam (g_hInst, MAKEINTRESOURCE(IDD_ERRORPANE), Window, ErrorPaneProc, (LONG_PTR)NULL);

	if (text != NULL)
	{
		CHARRANGE end;
		CHARFORMAT2 oldformat, newformat;
		PARAFORMAT2 paraformat;

		// Append the error message to the log.
		end.cpMax = end.cpMin = GetWindowTextLength (ConWindow);
		SendMessage (ConWindow, EM_EXSETSEL, 0, (LPARAM)&end);

		// Remember current charformat.
		oldformat.cbSize = sizeof(oldformat);
		SendMessage (ConWindow, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&oldformat);

		// Use bigger font and standout colors.
		newformat.cbSize = sizeof(newformat);
		newformat.dwMask = CFM_BOLD | CFM_COLOR | CFM_SIZE;
		newformat.dwEffects = CFE_BOLD;
		newformat.yHeight = oldformat.yHeight * 5 / 4;
		newformat.crTextColor = RGB(255,170,170);
		SendMessage (ConWindow, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&newformat);

		// Indent the rest of the text to make the error message stand out a little more.
		paraformat.cbSize = sizeof(paraformat);
		paraformat.dwMask = PFM_STARTINDENT | PFM_OFFSETINDENT | PFM_RIGHTINDENT;
		paraformat.dxStartIndent = paraformat.dxOffset = paraformat.dxRightIndent = 120;
		SendMessage (ConWindow, EM_SETPARAFORMAT, 0, (LPARAM)&paraformat);
		SendMessage (ConWindow, EM_REPLACESEL, FALSE, (LPARAM)"\n");

		// Find out where the error lines start for the error icon display control.
		SendMessage (ConWindow, EM_EXGETSEL, 0, (LPARAM)&end);
		ErrorIconChar = end.cpMax;

		// Now start adding the actual error message.
		SendMessage (ConWindow, EM_REPLACESEL, FALSE, (LPARAM)"Execution could not continue.\n\n");

		// Restore old charformat but with light yellow text.
		oldformat.crTextColor = RGB(255,255,170);
		SendMessage (ConWindow, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&oldformat);

		// Add the error text.
		SendMessage (ConWindow, EM_REPLACESEL, FALSE, (LPARAM)text);

		// Make sure the error text is not scrolled below the window.
		SendMessage (ConWindow, EM_LINESCROLL, 0, SendMessage (ConWindow, EM_GETLINECOUNT, 0, 0));
		// The above line scrolled everything off the screen, so pretend to move the scroll
		// bar thumb, which clamps to not show any extra lines if it doesn't need to.
		SendMessage (ConWindow, EM_SCROLL, SB_PAGEDOWN, 0);
	}

	BOOL bRet;
	MSG msg;

	while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
	{
		if (bRet == -1)
		{
			MessageBox (Window, text,
				GAMESIG " Fatal Error", MB_OK|MB_ICONSTOP|MB_TASKMODAL);
			return;
		}
		else if (!IsDialogMessage (ErrorPane, &msg))
		{
			TranslateMessage (&msg);
			DispatchMessage (&msg);
		}
	}
}
Esempio n. 30
0
void ShowIoDialog(int item)
{
    if(!Prog.mcu) {
        MessageBox(MainWindow,
            _("No microcontroller has been selected. You must select a "
            "microcontroller before you can assign I/O pins.\r\n\r\n"
            "Select a microcontroller under the Settings menu and try "
            "again."), _("I/O Pin Assignment"), MB_OK | MB_ICONWARNING);
        return;
    }

    if(Prog.mcu->whichIsa == ISA_ANSIC) {
        Error(_("Can't specify I/O assignment for ANSI C target; compile and "
            "see comments in generated source code."));
        return;
    }

    if(Prog.mcu->whichIsa == ISA_INTERPRETED) {
        Error(_("Can't specify I/O assignment for interpretable target; see "
            "comments in reference implementation of interpreter."));
        return;
    }

    if(Prog.io.assignment[item].name[0] != 'X' && 
       Prog.io.assignment[item].name[0] != 'Y' &&
       Prog.io.assignment[item].name[0] != 'A')
    {
        Error(_("Can only assign pin number to input/output pins (Xname or "
            "Yname or Aname)."));
        return;
    }

    if(Prog.io.assignment[item].name[0] == 'A' && Prog.mcu->adcCount == 0) {
        Error(_("No ADC or ADC not supported for this micro."));
        return;
    }

    if(strcmp(Prog.io.assignment[item].name+1, "new")==0) {
        Error(_("Rename I/O from default name ('%s') before assigning "
            "MCU pin."), Prog.io.assignment[item].name);
        return;
    }

    MakeWindowClass();

    // We need the TOOLWINDOW style, or else the window will be forced to
    // a minimum width greater than our current width. And without the
    // APPWINDOW style, it becomes impossible to get the window back (by
    // Alt+Tab or taskbar).
    IoDialog = CreateWindowClient(WS_EX_TOOLWINDOW | WS_EX_APPWINDOW,
        "LDmicroIo", _("I/O Pin"),
        WS_OVERLAPPED | WS_SYSMENU,
        100, 100, 107, 387, NULL, NULL, Instance, NULL);

    MakeControls();

    SendMessage(PinList, LB_ADDSTRING, 0, (LPARAM)_("(no pin)"));
    int i;
    for(i = 0; i < Prog.mcu->pinCount; i++) {
        int j;
        for(j = 0; j < Prog.io.count; j++) {
            if(j == item) continue;
            if(Prog.io.assignment[j].pin == Prog.mcu->pinInfo[i].pin) {
                goto cant_use_this_io;
            }
        }

        if(UartFunctionUsed() && Prog.mcu &&
                ((Prog.mcu->pinInfo[i].pin == Prog.mcu->uartNeeds.rxPin) ||
                 (Prog.mcu->pinInfo[i].pin == Prog.mcu->uartNeeds.txPin)))
        {
            goto cant_use_this_io;
        }

        if(PwmFunctionUsed() && 
            Prog.mcu->pinInfo[i].pin == Prog.mcu->pwmNeedsPin)
        {
            goto cant_use_this_io;
        }

        if(Prog.io.assignment[item].name[0] == 'A') {
            for(j = 0; j < Prog.mcu->adcCount; j++) {
                if(Prog.mcu->adcInfo[j].pin == Prog.mcu->pinInfo[i].pin) {
                    // okay; we know how to connect it up to the ADC
                    break;
                }
            }
            if(j == Prog.mcu->adcCount) {
                goto cant_use_this_io;
            }
        }

        char buf[40];
        if(Prog.mcu->pinCount <= 21) {
            sprintf(buf, "%3d   %c%c%d", Prog.mcu->pinInfo[i].pin,
                Prog.mcu->portPrefix, Prog.mcu->pinInfo[i].port,
                Prog.mcu->pinInfo[i].bit);
        } else {
            sprintf(buf, "%3d  %c%c%d", Prog.mcu->pinInfo[i].pin,
                Prog.mcu->portPrefix, Prog.mcu->pinInfo[i].port,
                Prog.mcu->pinInfo[i].bit);
        }
        SendMessage(PinList, LB_ADDSTRING, 0, (LPARAM)buf);
cant_use_this_io:;
    }

    EnableWindow(MainWindow, FALSE);
    ShowWindow(IoDialog, TRUE);
    SetFocus(PinList);

    MSG msg;
    DWORD ret;
    DialogDone = FALSE;
    DialogCancel = FALSE;
    while((ret = GetMessage(&msg, NULL, 0, 0)) && !DialogDone) {
        if(msg.message == WM_KEYDOWN) {
            if(msg.wParam == VK_RETURN) {
                DialogDone = TRUE;
                break;
            } else if(msg.wParam == VK_ESCAPE) {
                DialogDone = TRUE;
                DialogCancel = TRUE;
                break;
            }
        }

        if(IsDialogMessage(IoDialog, &msg)) continue;
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    if(!DialogCancel) {
        int sel = SendMessage(PinList, LB_GETCURSEL, 0, 0);
        char pin[16];
        SendMessage(PinList, LB_GETTEXT, (WPARAM)sel, (LPARAM)pin);
        if(strcmp(pin, _("(no pin)"))==0) {
            int i;
            for(i = 0; i < IoSeenPreviouslyCount; i++) {
                if(strcmp(IoSeenPreviously[i].name,
                    Prog.io.assignment[item].name)==0)
                {
                    IoSeenPreviously[i].pin = NO_PIN_ASSIGNED;
                }
            }
            Prog.io.assignment[item].pin = NO_PIN_ASSIGNED;
        } else {
            Prog.io.assignment[item].pin = atoi(pin);
            // Only one name can be bound to each pin; make sure that there's
            // not another entry for this pin in the IoSeenPreviously list,
            // that might get used if the user creates a new pin with that
            // name.
            int i;
            for(i = 0; i < IoSeenPreviouslyCount; i++) {
                if(IoSeenPreviously[i].pin == atoi(pin)) {
                    IoSeenPreviously[i].pin = NO_PIN_ASSIGNED;
                }
            }
        }
    }

    EnableWindow(MainWindow, TRUE);
    DestroyWindow(IoDialog);
    return;
}