Example #1
0
static BOOL _CmdWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    HTREEITEM hSelection;
    HKEY hRootKey;
    LPCWSTR keyPath, s;
    WORD wID = LOWORD(wParam);

    UNREFERENCED_PARAMETER(message);

    switch (wID)
    {
        /* Parse the menu selections: */
    case ID_REGISTRY_EXIT:
        DestroyWindow(hWnd);
        break;
    case ID_VIEW_REFRESH:
        /* TODO */
        break;
    case ID_TREE_EXPANDBRANCH:
        (void)TreeView_Expand(g_pChildWnd->hTreeWnd, TreeView_GetSelection(g_pChildWnd->hTreeWnd), TVE_EXPAND);
        break;
    case ID_TREE_COLLAPSEBRANCH:
        (void)TreeView_Expand(g_pChildWnd->hTreeWnd, TreeView_GetSelection(g_pChildWnd->hTreeWnd), TVE_COLLAPSE);
        break;
    case ID_TREE_RENAME:
        SetFocus(g_pChildWnd->hTreeWnd);
        (void)TreeView_EditLabel(g_pChildWnd->hTreeWnd, TreeView_GetSelection(g_pChildWnd->hTreeWnd));
        break;
    case ID_TREE_DELETE:
        hSelection = TreeView_GetSelection(g_pChildWnd->hTreeWnd);
        keyPath = GetItemPath(g_pChildWnd->hTreeWnd, hSelection, &hRootKey);

        if (keyPath == 0 || *keyPath == 0)
        {
            MessageBeep(MB_ICONHAND);
        }
        else if (DeleteKey(hWnd, hRootKey, keyPath))
            DeleteNode(g_pChildWnd->hTreeWnd, 0);
        break;
    case ID_TREE_EXPORT:
        ExportRegistryFile(g_pChildWnd->hTreeWnd);
        break;
    case ID_EDIT_FIND:
        FindDialog(hWnd);
        break;
    case ID_EDIT_COPYKEYNAME:
        hSelection = TreeView_GetSelection(g_pChildWnd->hTreeWnd);
        keyPath = GetItemPath(g_pChildWnd->hTreeWnd, hSelection, &hRootKey);
        CopyKeyName(hWnd, hRootKey, keyPath);
        break;
    case ID_EDIT_NEW_KEY:
        CreateNewKey(g_pChildWnd->hTreeWnd, TreeView_GetSelection(g_pChildWnd->hTreeWnd));
        break;
    case ID_EDIT_NEW_STRINGVALUE:
    case ID_EDIT_NEW_BINARYVALUE:
    case ID_EDIT_NEW_DWORDVALUE:
        SendMessageW(hFrameWnd, WM_COMMAND, wParam, lParam);
        break;
    case ID_SWITCH_PANELS:
        g_pChildWnd->nFocusPanel = !g_pChildWnd->nFocusPanel;
        SetFocus(g_pChildWnd->nFocusPanel? g_pChildWnd->hListWnd: g_pChildWnd->hTreeWnd);
        break;
    default:
        if ((wID >= ID_TREE_SUGGESTION_MIN) && (wID <= ID_TREE_SUGGESTION_MAX))
        {
            s = Suggestions;
            while(wID > ID_TREE_SUGGESTION_MIN)
            {
                if (*s)
                    s += wcslen(s) + 1;
                wID--;
            }
            SelectNode(g_pChildWnd->hTreeWnd, s);
            break;
        }
        return FALSE;
    }
    return TRUE;
}
Example #2
0
static int CALLBACK LogProc(HWND hwnd, UINT msg,
			    WPARAM wParam, LPARAM lParam)
{
    int i;

    switch (msg) {
      case WM_INITDIALOG:
	{
	    char *str = dupprintf("%s Event Log", appname);
	    SetWindowText(hwnd, str);
	    sfree(str);
	}
	{
	    static int tabs[4] = { 78, 108 };
	    SendDlgItemMessage(hwnd, IDN_LIST, LB_SETTABSTOPS, 2,
			       (LPARAM) tabs);
	}
	for (i = 0; i < nevents; i++)
	    SendDlgItemMessage(hwnd, IDN_LIST, LB_ADDSTRING,
			       0, (LPARAM) events[i]);
	return 1;
      case WM_COMMAND:
	switch (LOWORD(wParam)) {
	  case IDOK:
	  case IDCANCEL:
	    logbox = NULL;
	    SetActiveWindow(GetParent(hwnd));
	    DestroyWindow(hwnd);
	    return 0;
	  case IDN_COPY:
	    if (HIWORD(wParam) == BN_CLICKED ||
		HIWORD(wParam) == BN_DOUBLECLICKED) {
		int selcount;
		int *selitems;
		selcount = SendDlgItemMessage(hwnd, IDN_LIST,
					      LB_GETSELCOUNT, 0, 0);
		if (selcount == 0) {   /* don't even try to copy zero items */
		    MessageBeep(0);
		    break;
		}

		selitems = snewn(selcount, int);
		if (selitems) {
		    int count = SendDlgItemMessage(hwnd, IDN_LIST,
						   LB_GETSELITEMS,
						   selcount,
						   (LPARAM) selitems);
		    int i;
		    int size;
		    char *clipdata;
		    static unsigned char sel_nl[] = SEL_NL;

		    if (count == 0) {  /* can't copy zero stuff */
			MessageBeep(0);
			break;
		    }

		    size = 0;
		    for (i = 0; i < count; i++)
			size +=
			    strlen(events[selitems[i]]) + sizeof(sel_nl);

		    clipdata = snewn(size, char);
		    if (clipdata) {
			char *p = clipdata;
			for (i = 0; i < count; i++) {
			    char *q = events[selitems[i]];
			    int qlen = strlen(q);
			    memcpy(p, q, qlen);
			    p += qlen;
			    memcpy(p, sel_nl, sizeof(sel_nl));
			    p += sizeof(sel_nl);
			}
			write_aclip(NULL, clipdata, size, TRUE);
			sfree(clipdata);
		    }
		    sfree(selitems);

		    for (i = 0; i < nevents; i++)
			SendDlgItemMessage(hwnd, IDN_LIST, LB_SETSEL,
					   FALSE, i);
		}
	    }
	    return 0;
	}
	return 0;
      case WM_CLOSE:
	logbox = NULL;
	SetActiveWindow(GetParent(hwnd));
	DestroyWindow(hwnd);
	return 0;
    }
void CADQIDlg::OnDblClkInterfaces()
{
    CString s;
    int xx=0;
    int idx;
    IUnknown *pNewUnk = NULL;


    idx = m_cListIf.GetCurSel();
    if ( idx == LB_ERR )
    {
        MessageBeep(0);
        return;
    }


    CWaitCursor wait;
    m_cListIf.GetText( idx, s );


    //////////////////////////////////////////////////////////////
    //
    // Find the appropriate dialog box to display
    //
    /////////////////////////////////////////////////////////////////
    while( !IsEqualIID( *adsiIfs[xx].pIID, IID_NULL ) && s != adsiIfs[xx].szIf  )
    {
        xx++;
    }

    ASSERT( !IsEqualIID( *adsiIfs[xx].pIID, IID_NULL ) );
    if ( adsiIfs[xx].pFn )
    {
        m_pUnk->AddRef();
        (*adsiIfs[xx].pFn)( m_pUnk, &pNewUnk );
    }
    else
    {
        wait.Restore();
        AfxMessageBox(_T("No UI implemented yet"));
    }



    ////////////////////////////////////////////////////
    // if IADsOpenObject is selected, special care
    ///////////////////////////////////////////////////
    if ( pNewUnk )
    {

        HRESULT hr;
        BSTR  bstr;
        IADs  *pADs;

        hr = pNewUnk->QueryInterface( IID_IADs, (void**) &pADs );
        if ( SUCCEEDED(hr) )
        {
            pADs->get_ADsPath( &bstr );
        }
        pADs->Release();

        m_sADsPath = bstr;
        SysFreeString( bstr );


        m_pUnk->Release(); // old ads iunknown path;
        m_pUnk = pNewUnk;

        UpdateData(FALSE);
        EnumerateInterface();

    }


}
Example #4
0
BOOL CMyDateEdit::CheckTime(char nchar,int StartPos,int EndPos)
{
	CString strText;
	if(m_isTime)
	{
		if(StartPos==2||StartPos==3||StartPos==5||StartPos==6)
		{
			if (nchar>'5')
			{
				MessageBeep((UINT)-1);
				return FALSE;
			}
		}	
		if(StartPos==0)
		{
			if (nchar>'2')
			{
				MessageBeep((UINT)-1);
				return FALSE;
			}
			if(nchar=='2')
			{
				if(GetText().GetAt(1)>'3')
				{
					strText=GetText();
					strText.SetAt(1,'3');
					SetWindowText(strText);
					SetSel(StartPos,EndPos);
					return TRUE;
				}
			}
		}	
		if(StartPos==1)
		{
			if(GetText().GetAt(0)=='2')
			{
				if(nchar>'3')
				{
					MessageBeep((UINT)-1);
					return FALSE;			
				}

			}
		}
	}
	if(m_isDateTime)
	{
		if(StartPos==13||StartPos==14||StartPos==16||StartPos==17)
		{
			if (nchar>'5')
			{
				MessageBeep((UINT)-1);
				return FALSE;
			}
		}
		if(StartPos==10||StartPos==11)
		{
			if (nchar>'2')
			{
				MessageBeep((UINT)-1);
				return FALSE;
			}
			if(nchar=='2')
			{
				if(GetText().GetAt(12)>'3')
				{
					strText=GetText();
					strText.SetAt(12,'3');
					SetWindowText(strText);
					SetSel(StartPos,EndPos);
					return TRUE;
				}
			}
		}	
		if(StartPos==12)
		{
			if(GetText().GetAt(11)=='2')
			{
				if(nchar>'3')
				{
					MessageBeep((UINT)-1);
					return FALSE;			
				}

			}
		}
	}	
	return TRUE;
}
Example #5
0
// This function tries to prevent the user from entering invalid
// amounts in the CArborEditCurrency text control.  This is difficult
// to do here because you really need the amount string after the edit,
// not before.  This function attempts to construct the new amount string,
// but it's risky business trying to predict what Windows will REALLY do...
//
// A better approach might be to construct a DDV_Currency function that
// checks for valid amounts after the user selects "OK" from the dialog box.
void CArborEditCurrency::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
	// If the control is read only, beep and exit
	if (GetStyle() & ES_READONLY)
	{
		MessageBeep(MB_ICONEXCLAMATION);
		return;
	}

	// Get the decimal delimiter for this currency.  Beep and exit if problem
	// getting currency info (invalid currency or init_currency_formats
	// not called)
	char cDelimiter = get_currency_decimal_delimiter(m_iCurrencyCode);
	if (cDelimiter == -1)
	{
		MessageBeep(MB_ICONEXCLAMATION);
		return;
	}

	// If the input character is not a control character,
	// digit, or decimal delimiter, then beep and exit
	if (!(nChar < 0x20) &&
		!isdigit(nChar) &&
		!(nChar == (UINT)cDelimiter))
	{
		MessageBeep(MB_ICONEXCLAMATION);
		return;
	}

	// Now attempt to construct what the new text string will look like.
	// Only try this for "normal" edits; i.e., edits that don't involve
	// control characters other than paste (0x16).
	if (nChar == 0x16 || nChar > 0x19)
	{
		// Get the old string
		CString oldString;
		GetWindowText(oldString);

		// Get the inserted string.  This is a single character unless
		// text is being pasted from the clipboard.
		CString insertedString;
		if (nChar != 0x16)
		{
			insertedString = (char)nChar;
		}
		else
		{
			// Get pasted text from the clipboard
			if (OpenClipboard())
			{
				HGLOBAL hData = ::GetClipboardData(CF_TEXT);
				if (hData)
				{
					insertedString = (LPCTSTR) GlobalLock(hData);
					GlobalUnlock(hData);
				}
			}
			CloseClipboard();
		}

		// Construct the new string.
		// Replace any text that is currently selected.
		int iStartSel, iEndSel;
		GetSel(iStartSel, iEndSel);
		CString newString = oldString.Left(iStartSel) + insertedString
			+ oldString.Right(oldString.GetLength() - iEndSel);

		// Count the number of minus signs, decimal delimiters,
		// integer digits, and decimal digits
		int nMinusSigns = 0;
		int nDelimiters = 0;
		int nIntegerDigits = 0;
		int nDecimalDigits = 0;

		for (int i = 0; i < newString.GetLength(); i++)
		{
			if (newString[i] == '-')
				nMinusSigns++;
			if (newString[i] == cDelimiter)
				nDelimiters++;
			if (isdigit(newString[i]) && nDelimiters == 0)
				nIntegerDigits++;
			if (isdigit(newString[i]) && nDelimiters > 0)
				nDecimalDigits++;
		}

		// Determine the maximum number of integer and decimal digits
		// based on Arb_numeric and the currency.  If problem getting
		// currency info (perhaps invalid currency or init_currency_formats
		// not called), beep and exit.
		int maxDecimalDigits = get_currency_implied_decimal(m_iCurrencyCode);
		if (maxDecimalDigits == -1)
		{
			MessageBeep(MB_ICONEXCLAMATION);
			return;
		}
		int maxIntegerDigits = ARB_NUMERIC_LEN - 3 - maxDecimalDigits;

		// Beep and exit if this is not a valid amount string
		// - Minus sign (not allowed during user input)
		// - More than one decimal delimiter
		// - More than the maximum number of integer digits
		// - More than the maximum number of decimal digits
		if ((nMinusSigns > 0) ||
			(nDelimiters > 1) ||
			(nIntegerDigits > maxIntegerDigits) ||
			(nDecimalDigits > maxDecimalDigits))
		{
			MessageBeep(MB_ICONEXCLAMATION);
			return;
		}
	}

	// Pass the character onto CEdit for processing
	CEdit::OnChar(nChar, nRepCnt, nFlags);
}
Example #6
0
void WinSonicSimpleAlert::Beep() const
{
	MessageBeep(MB_ICONASTERISK);
}
LRESULT CSwissKnifePaneModify::OnGridNotify( WPARAM wParam, LPARAM lParam )
{
	if (wParam == XTP_PGN_INPLACEBUTTONDOWN)
	{
		CXTPPropertyGridInplaceButton* pButton = (CXTPPropertyGridInplaceButton*)lParam;
		if (pButton->GetItem()->GetID() == 510 && pButton->GetID() == XTP_ID_PROPERTYGRID_EXPANDBUTTON) // 2 Buttons
		{
			AfxMessageBox(_T("Expand button"));
			return TRUE;
		}
	}

	if (wParam == XTP_PGN_SORTORDER_CHANGED)
	{
		UpdateData(FALSE);
		TRACE(_T("SortOrder Changed.\n"));
	}
	if (wParam == XTP_PGN_ITEMVALUE_CHANGED)
	{
		CXTPPropertyGridItem* pItem = (CXTPPropertyGridItem*)lParam;
		TRACE(_T("Value Changed. Caption = %s, ID = %i, Value = %s\n"), pItem->GetCaption(), pItem->GetID(), pItem->GetValue());

		if (DYNAMIC_DOWNCAST(CXTPPropertyGridItemEnum, pItem))
		{
			if (pItem->GetMetrics(TRUE, FALSE))
			{
				pItem->GetMetrics(TRUE, FALSE)->m_nImage = ((CXTPPropertyGridItemEnum*)pItem)->GetEnum();
			}
		}


		if( pItem->GetID() == ID_CREATE_PHYSIC_LAYER)
		{
			CXTPPropertyGridItemBool* itembool = (CXTPPropertyGridItemBool*)pItem;
			if (m_currTarget && itembool->GetBool())
			{
				if (!m_currTarget->getPhysicLayer())
				{
#ifdef OS_WIN32

						IGameObjectPhysicLayer* pPhysicLayer = gEnv->pPhysics->CreatePhysicLayer();
						m_currTarget->setGameObjectLayer(pPhysicLayer);
						pPhysicLayer->createStatic();

						
#endif

				}
			}
		}
	}
	if (wParam == XTP_PGN_SELECTION_CHANGED)
	{
		CXTPPropertyGridItem* pItem = (CXTPPropertyGridItem*)lParam;
		if (pItem)
		{
			if (pItem->IsKindOf(RUNTIME_CLASS(CXTPPropertyGridItemColor)))
			{
				TRACE(_T("Color Item. Selection Changed. Item = %s\n"), pItem->GetCaption());
			}
		}
	}
	if (wParam == XTP_PGN_EDIT_CHANGED)
	{
		CXTPPropertyGridInplaceEdit* pEdit = DYNAMIC_DOWNCAST(CXTPPropertyGridInplaceEdit, (CWnd*)lParam);
		if (pEdit && pEdit->GetItem())
		{
			// Custom Validation
			// Custom Validation
			if (pEdit->GetItem()->GetCaption() == _T("ItemsInMRUList"))
			{
				CString str;
				pEdit->CEdit::GetWindowText(str);

				int i = _ttoi(str);
				if (i > 20)
				{
					MessageBeep((UINT)-1);
					pEdit->SetSel(0, -1);
					pEdit->ReplaceSel(_T("20"));
				}
			}
		}
	}
	return 0;
}
void CChEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
#if 1

	// flomar, 03/28/2013: after hours of debugging I finally located the source of 
	// the problem; obviously the user's key strokes weren't correctly processed, in 
	// other words a character inserted at a specific location would get assigned to an 
	// incorrect matrix cell-- before digging in any deeper I completely re-wrote this 
	// function; it *should* work as intended now; I left the old code in here on purpose 
	// (see the '#if' blocks above and below) in case someone has to deal with this in 
	// another 10 or so years, and I'm not 100% sure I didn't introduce some bugs myself

	// the character the user tried to insert-- in case the character is invalid with regards 
	// to the analysis alphabet, it gets replaced implicitly; if the replacement fails (i.e. 
	// the character is still invalid), we return right away and notify the user with a beep
	const char newCharacter = MyToUpper(m_Alg->getAlphabet()->replaceInvalidLetter(true, nChar));
	if(!m_Alg->myisalpha2(newCharacter)) {
		MessageBeep(MB_OK);
	}
	// the character that was replaced by the new character; the way this is handled 
	// is pretty ugly with all that SetSel/GetLine stuff, but I'm certainly not gonna 
	// touch any other parts of this dialog for the meantime (note: a better solution 
	// would be to have member variables for each and every cell of the GUI matrix);
	// in case the character is not part of the analysis alphabet, we're trying to 
	// convert it just like we did with the new character above
	char tempCharacter[2];
	memset(tempCharacter, 0, sizeof(char) * 2);
	SetSel(0, 1);
	GetLine(0, tempCharacter, 1);
	ReplaceSel(CString(newCharacter));
	SetSel(0, 1);
	// try to replace the temp character with something valid, if necessary
	tempCharacter[0] = MyToUpper(m_Alg->getAlphabet()->replaceInvalidLetter(true, tempCharacter[0]));
	// if the character is still invalid after the conversion, we proceed with a 
	// null element which, as of today, is denoted by the '*' character
	if(!tempCharacter[0]) {
		tempCharacter[0] = m_Alg->getAlphabet()->getNullElement()->getValue();
	}
	// at this point all conversion work is done, we can now assign the old character
	const char oldCharacter = tempCharacter[0];
	// if old a new character are identical, return without doing anything else
	if(newCharacter == oldCharacter) {
		return;
	}
	// if the new character is invalid (not part of the alphabet), return as well
	if(!m_Alg->myisalpha2(newCharacter)) {
		return;
	}
	// we're gonna need those in a minute...
	int newCharacterIndexColumn = -1;
	int newCharacterIndexRow = -1;
	// get the size of the current maxtrix (either 5x5 or 6x6)
	const int matrixSize = m_Alg->getSize();
	// go through all cells of the matrix and find the newly inserted character
	for(int indexRow=0; indexRow<matrixSize; indexRow++) {
		for(int indexColumn=0; indexColumn<matrixSize; indexColumn++) {
			// get the current character
			char currentCharacter = m_Alg->getCharOfMatrix(indexColumn, indexRow);
			// ignore null elements
			if(currentCharacter != m_Alg->getAlphabet()->getNullElement()->getValue()) {
				// assign indices for new character
				if(newCharacter == currentCharacter) {
					newCharacterIndexColumn = indexColumn;
					newCharacterIndexRow = indexRow;
				}
			}
		}
	}
	// this variable tells us if the new character did already exist in the matrix
	const bool newCharacterAlreadyExisted = newCharacterIndexColumn != -1 && newCharacterIndexRow != -1;
	// if the new character did NOT exist in the matrix, determine its indices (column/row)
	if(!newCharacterAlreadyExisted) {
		for(int indexRow=0; indexRow<matrixSize && newCharacterIndexRow<0; indexRow++) {
			for(int indexColumn=0; indexColumn<matrixSize && newCharacterIndexColumn<0; indexColumn++) {
				// get the content of the current matrix cell
				CString stringCurrentMatrixCell;
				m_Dia->getEinfeld(indexColumn, indexRow)->GetWindowText(stringCurrentMatrixCell);
				// check if we've arrived at the new character
				if(newCharacter == stringCurrentMatrixCell[0]) {
					// update indices for the new character
					newCharacterIndexColumn = indexColumn;
					newCharacterIndexRow = indexRow;
					// now update the matrix (actually insert the new character at its appropriate position)
					m_Alg->setElMatrix(newCharacter, newCharacterIndexColumn, newCharacterIndexRow);
				}
			}
		}
	}
	// in case the new character was already inserted, switch back to the old character
	if(newCharacterAlreadyExisted) {
		// update the dialog
		m_Dia->getEinfeld(newCharacterIndexColumn, newCharacterIndexRow)->SetWindowText(CString(oldCharacter));
		// update the analysis
		m_Alg->setElMatrix(oldCharacter, newCharacterIndexColumn, newCharacterIndexRow);
	}
	// some clean-up work
	m_Alg->UpdateDigrams(m_Dia->getDec());
	m_Alg->DoCipher(false, m_Dia->getDec(),MAXSHOWLETTER);
	m_Dia->UpdateListBox();
	m_Dia->UpdatePassword();
	
#else
	char b1[2],b2[2];

	if(!m_Alg->myisalpha2(nChar))  // TG, Umlaute oder französische Zeichen zu etwas ähnlichem ersetzen.
		nChar = m_Alg->getAlphabet()->replaceInvalidLetter(true, MyToUpper(nChar));
	if (m_Alg->myisalpha2(nChar))
	{
		int i,j,s,a,b,c,d;

		a=-1; c =-1;
		b2[1]=0;
		b2[0]=MyToUpper(nChar);
		SetSel(0, 1);
		GetLine(0,b1,2);
		ReplaceSel(b2);
		SetSel(0, 1);
		if(!m_Alg->myisalpha2(b1[0])){  // TG, Umlaute oder französische Zeichen zu etwas ähnlichem ersetzen.
			b1[0] = m_Alg->getAlphabet()->replaceInvalidLetter(true, b1[0]);
			if (b1[0] == '\0')
				b1[0] = m_Alg->getAlphabet()->getNullElement()->getValue();
		}
		if (b1[0]==b2[0]||!m_Alg->myisalpha2(b2[0]))
			return;
		s=m_Alg->getSize();
		for (i=0;i<s;i++)
		{
			for (j=0;j<s;j++)
			{
				if (b1[0] == m_Alg->getCharOfMatrix (i,j))
				{ // hole Indices vom alten Buchstaben
					a=i;
					b=j;
				}
				if (b2[0] == m_Alg->getCharOfMatrix (i,j))
				{ // hole Indices vom eingetippten Buchstaben
					c=i;
					d=j;
				}
			}
		}
		if (a>=0) { // zu ersetzender Buchstabe gefunden
			i=i;
		} else { // wie erfahre ich meine Koordinaten?
			for (i=0;(i<s)&&(a<0);i++)
				for (j=0;(j<s)&&(a<0);j++) {
					CString tmpstr;
					m_Dia->getEinfeld(i,j)->GetWindowText(tmpstr);
					if (b2[0] == tmpstr[0]) {
						a=i; b=j;
					}
				}
			i=i;
		}
		m_Alg->setElMatrix (b2[0], a, b);
		if (c>=0) { // eingetippter Buchstabe war schon vorhanden
			m_Dia->getEinfeld(c,d)->SetWindowText(b1);
			m_Alg->setElMatrix (b1[0], c, d);
		} else {
			i=i;
		}
		m_Alg->UpdateDigrams(m_Dia->getDec());
		m_Alg->DoCipher(false, m_Dia->getDec(),MAXSHOWLETTER);
		m_Dia->UpdateListBox();
		m_Dia->UpdatePassword();
	} else  // invalid character
		MessageBeep(MB_OK);
#endif
} // void CChEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
Example #9
0
wchar_t* Xlat(wchar_t *Line,
                     int StartPos,
                     int EndPos,
                     unsigned __int64 Flags)
{
	int PreLang=2,CurLang=2; // unknown
	size_t LangCount[2]={};

	if (!Line || !*Line)
		return nullptr;

	int Length=StrLength(Line);
	EndPos=std::min(EndPos,Length);
	StartPos=std::max(StartPos,0);

	if (StartPos > EndPos || StartPos >= Length)
		return Line;

	if (Global->Opt->XLat.Table[0].empty() || Global->Opt->XLat.Table[1].empty())
		return Line;

	size_t MinLenTable=std::min(Global->Opt->XLat.Table[0].size(),Global->Opt->XLat.Table[1].size());
	string strLayoutName;
	bool ProcessLayoutName=false;
	StringOption RulesNamed;

	if ((Flags & XLAT_USEKEYBLAYOUTNAME) && Global->Console->GetKeyboardLayoutName(strLayoutName))
	{
		/*
			Уточнение по поводу этого куска, чтобы потом не вспоминать ;-)
			Было сделано в 1.7 build 1585

		    Делаем именно то, что заказывали!

		    Т.е. если сейчас раскладка стоит английская, а мы шпарим по русски, то
		    если раньше 'б' и 'ю' (в результате малой статистики) конвертировались
		    как бог на душу положит... то теперь так, как должно быть.

		    Для проверки нужно у HKEY_CURRENT_USER\Software\Far2\XLat\Flags выставить
		    второй бит (считаем от нуля; 0x4) и дописать две переменных:

		    ; набирали по русски в английской раскладке
		    ; `ё~Ё[х{Х]ъ}Ъ;Ж:Ж'э"Э,б<Б.ю>Ю/.?,
		    XLat::"00000409"="`ё~Ё[х{Х]ъ}Ъ;Ж:Ж'э\"Э,б<Б.ю>Ю/.?,"

		    ; набирали по английски в русской раскладке
		    ; ё`Ё~х[Х{ъ]Ъ}Ж;Ж:э'Э"б,Б<ю.Ю>./,?
		    XLat::"00000419"="ё`Ё~х[Х{ъ]Ъ}Ж;Ж:э'Э\"б,Б<ю.Ю>./,?"

		    Здесь есть бага (хотя, багой и не назовешь...) -
		      конвертнули,
		      переключилась раскладка,
		      руками переключили раскладку,
		      снова конвертим и...
		*/
		string XlatRules;
		Global->Db->GeneralCfg()->GetValue(L"XLat", strLayoutName, XlatRules, L"");
		RulesNamed = XlatRules;
		if (!RulesNamed.empty())
			ProcessLayoutName=true;
	}

	// цикл по всей строке
	for (int j=StartPos; j < EndPos; j++)
	{
		wchar_t Chr = Line[j];
		wchar_t ChrOld = Line[j];
		// ChrOld - пред символ
		int IsChange=0;

		// цикл по просмотру Chr в таблицах
		// <=MinLenTable так как длина настоящая а начальный индекс 1
		for (size_t i=0; i <= MinLenTable; i++)
		{
			// символ из латиницы?
			if (Chr == Global->Opt->XLat.Table[1][i])
			{
				Chr=Global->Opt->XLat.Table[0][i];
				IsChange=1;
				CurLang=1; // pred - english
				LangCount[1]++;
				break;
			}
			// символ из русской?
			else if (Chr == Global->Opt->XLat.Table[0][i])
			{
				Chr=Global->Opt->XLat.Table[1][i];
				CurLang=0; // pred - russian
				LangCount[0]++;
				IsChange=1;
				break;
			}
		}

		if (!IsChange) // особые случаи...
		{
			if (ProcessLayoutName)
			{
				for (size_t i=0; i < RulesNamed.size(); i+=2)
				{
					if (Chr == RulesNamed[i])
					{
						Chr=RulesNamed[i+1];
						break;
					}
				}
			}
			else
			{
				PreLang=CurLang;

				if (LangCount[0] > LangCount[1])
					CurLang=0;
				else if (LangCount[0] < LangCount[1])
					CurLang=1;
				else
					CurLang=2;

				if (PreLang != CurLang)
					CurLang=PreLang;

				for (size_t i=0; i < Global->Opt->XLat.Rules[CurLang].size(); i+=2)
				{
					if (ChrOld == Global->Opt->XLat.Rules[CurLang][i])
					{
						Chr=Global->Opt->XLat.Rules[CurLang][i+1];
						break;
					}
				}

#if 0

				// Если в таблице не найдено и таблица была Unknown...
				if (I >= Global->Opt->XLat.Rules[CurLang][0] && CurLang == 2)
				{
					// ...смотрим сначала в первой таблице...
					for (I=1; I < Global->Opt->XLat.Rules[0][0]; I+=2)
						if (ChrOld == (BYTE)Global->Opt->XLat.Rules[0][I])
							break;

					for (J=1; J < Global->Opt->XLat.Rules[1][0]; J+=2)
						if (ChrOld == (BYTE)Global->Opt->XLat.Rules[1][J])
							break;

					if (I >= Global->Opt->XLat.Rules[0][0])
						CurLang=1;

					if (J >= Global->Opt->XLat.Rules[1][0])
						CurLang=0;

					if ()//???
					{
						Chr=(BYTE)Global->Opt->XLat.Rules[CurLang][J+1];
					}
				}

#endif
			}
		}

		Line[j]=Chr;
	}

	// переключаем раскладку клавиатуры?
	if (Flags & XLAT_SWITCHKEYBLAYOUT)
	{
		HWND hWnd = Global->Console->GetWindow();

		if (hWnd)
		{
			HKL Next = nullptr;

			if (Global->Opt->XLat.Layouts[0])
			{
				if (++Global->Opt->XLat.CurrentLayout >= (int)ARRAYSIZE(Global->Opt->XLat.Layouts) || !Global->Opt->XLat.Layouts[Global->Opt->XLat.CurrentLayout])
					Global->Opt->XLat.CurrentLayout=0;

				if (Global->Opt->XLat.Layouts[Global->Opt->XLat.CurrentLayout])
					Next=Global->Opt->XLat.Layouts[Global->Opt->XLat.CurrentLayout];
			}

			PostMessage(hWnd,WM_INPUTLANGCHANGEREQUEST, Next?0:INPUTLANGCHANGE_FORWARD, (LPARAM)Next);

			if (Flags & XLAT_SWITCHKEYBBEEP)
				MessageBeep(0);
		}
	}

	return Line;
}
/////////////////////////////////////////////////////////////////////////////
//	OnEditVerifyPercentCell
//		This is a handy utility to keep user entry in percent cells valid as they type.
//    The caller should determine that the cell is for percent entry, and if so
//    can pass verification of the input key to this function.
//	Params:
//		col, row	- location of the edit cell
//		edit		-	pointer to the edit control
//		vcKey		- virtual key code of the pressed key
//	Return:
//		TRUE - to accept pressed key
//		FALSE - to do not accept the key
int CDDBaseGrid::OnEditVerifyPercentCell(int col, long row,CWnd *edit,UINT *vcKey)
{
   // Cursor movement keys are okay
   // But these symbols don't work ... ?
   //if (*vcKey == VK_BACK || *vcKey == VK_LEFT || *vcKey == VK_RIGHT || *vcKey == VK_DELETE)
   //   return TRUE;
   if (*vcKey == VK_BACK || *vcKey == 0x7F /*Delete*/ 
      || *vcKey == VK_CANCEL/*Ctrl+C*/ || *vcKey == 0x16/*Ctrl+V*/)
      return TRUE;

   // Current selection will be replaced, so chars in there don't matter, remove them from
   // consideration during validation tests.
   CString curTxt;
   CEdit *cedit = (CEdit*)edit;
   edit->GetWindowText(curTxt);
   int startIndx = -1, endIndx = -1;
   cedit->GetSel(startIndx, endIndx);
   if (startIndx > -1 && endIndx > startIndx)
      curTxt.Delete(startIndx, endIndx - startIndx);

   int curPercentIndx = curTxt.Find("%");

   // Alpha chars '.' and '%' accepted, but only one per customer
   if (*vcKey == '%' || *vcKey == '.')
   {
      // Possibly okay, make sure no duplicate of percent or decimal pt.

      int curDecimalIndx = curTxt.Find(".");

      // Can only have one of these
      if (*vcKey == '%' && curPercentIndx > -1)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }
      if (*vcKey == '.' && curDecimalIndx > -1)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Can't put decimal after percent
      // startIndx is where new char will go
      if (*vcKey == '.' && curPercentIndx > -1 && startIndx > curPercentIndx)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Percent can only go at end
      if (*vcKey == '%' && startIndx < curTxt.GetLength())
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Okay, we'll accept the char
      return TRUE;
   }

   // We're accepting digits, but can't be after percent
   if (isdigit(*vcKey))
   {
      // Can't put digits after percent
      // startIndx is where new char will go
      if (curPercentIndx > -1 && startIndx > curPercentIndx)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Okay
      return TRUE;
   }

   // All else
   MessageBeep((UINT)-1);
   return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
//	OnEditVerifyFloatCell
//		This is a handy utility to keep user entry in floating point number cells valid as they type.
//    The caller should determine that the cell is for percent entry, and if so
//    can pass verification of the input key to this function.
//	Params:
//		col, row	- location of the edit cell
//		edit		-	pointer to the edit control
//		vcKey		- virtual key code of the pressed key
//	Return:
//		TRUE - to accept pressed key
//		FALSE - to do not accept the key
int CDDBaseGrid::OnEditVerifyFloatCell(int col, long row,CWnd *edit,UINT *vcKey)
{
   // Cursor movement keys are okay
   // But these symbols don't work ... ?
   //if (*vcKey == VK_BACK || *vcKey == VK_LEFT || *vcKey == VK_RIGHT || *vcKey == VK_DELETE)
   //   return TRUE;
   if (*vcKey == VK_BACK || *vcKey == 0x7F /*Delete*/)
      return TRUE;

   // Current selection will be replaced, so chars in there don't matter, remove them from
   // consideration during validation tests.
   CString curTxt;
   CEdit *cedit = (CEdit*)edit;
   edit->GetWindowText(curTxt);
   int startIndx = -1, endIndx = -1;
   cedit->GetSel(startIndx, endIndx);
   if (startIndx > -1 && endIndx > startIndx)
      curTxt.Delete(startIndx, endIndx - startIndx);

   int curMinusIndx = curTxt.Find("-");

   // Alpha chars '.' and '-' accepted, but only one per customer
   if (*vcKey == '.' || *vcKey == '-')
   {
      // Possibly okay, make sure no duplicate of percent or decimal pt.

      int curDecimalIndx = curTxt.Find(".");

      // Can only have one of these
      if (*vcKey == '-' && curMinusIndx > -1)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }
      if (*vcKey == '.' && curDecimalIndx > -1)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Can't put decimal before minus
      if (*vcKey == '.' && curMinusIndx > -1 && startIndx <= curMinusIndx)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Minus can only go at beginning
      if (*vcKey == '-' && startIndx != 0)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Okay, we'll accept the char
      return TRUE;
   }

   // We're accepting digits, but not in front of minus sign
   if (isdigit(*vcKey))
   {
      // Can't put digits in front of minus
      if (curMinusIndx > -1 && startIndx <= curMinusIndx)
      {
         MessageBeep((UINT)-1);
         return FALSE;
      }

      // Okay
      return TRUE;
   }

   // All else
   MessageBeep((UINT)-1);
   return FALSE;
}
Example #12
0
int HSExport2::DoExport(const TCHAR *name,ExpInterface *ei,Interface *gi, BOOL suppressPrompts, DWORD options)
{
    BOOL backupEnabled = gi->AutoBackupEnabled();
    gi->EnableAutoBackup(FALSE);

    BOOL bmmSilentMode = TheManager->SilentMode();
    TheManager->SetSilentMode(TRUE);

    bool mbSuppressPrompts = hsMessageBox_SuppressPrompts;
    hsMessageBox_SuppressPrompts = (suppressPrompts)?true:false;

    // Disable save so we don't crash in export or
    // otherwise screw database.
    SimpleExportExitCallback exitCB;
    gi->RegisterExitMAXCallback(&exitCB);

    gUserPropMgr.OpenQuickTable();
    hsConverterUtils::Instance().CreateNodeSearchCache();

    BroadcastNotification(NOTIFY_PRE_EXPORT);

    // get just the path (not the file) of where we are going to export to
    char out_path[256];
    IGetPath(name, out_path);
    // Apparently this was implied by the open dialog, but not if you call Max's ExportToFile() func
    SetCurrentDirectory(out_path);

    // 
    // Setup ErrorMsg
    //
    // Needs to be outside try/catch so it doesn't stack unwind...
    plExportErrorMsg hituser_errorMessage;  // This is the errorMessage that slaps user

    TSTR filename = gi->GetCurFileName();
    hsStrncpy(fName, filename, 128);
    char *dot = strrchr(fName, '.');
    if (dot)
        *dot = 0;
    char ErrorLogName[512];
    sprintf(ErrorLogName, "%s%s.err", out_path, fName);
    plExportLogErrorMsg logonly_errorMessage(ErrorLogName);     // This errorMessage just writes it all to a file

    // now decide which errorMessage object to use
    plErrorMsg* errorMessage;
    if (suppressPrompts)
        errorMessage = &logonly_errorMessage;
    else
        errorMessage = &hituser_errorMessage;

    // For export time stats
    DWORD exportTime = timeGetTime();
    _SYSTEMTIME tm;
    GetSystemTime(&tm);

    //
    // Let's get cracking!  Convert the scene...
    //
    plConvertSettings settings;
    
    if (plExportDlg::Instance().IsExporting())
    {
        settings.fDoPreshade = plExportDlg::Instance().GetDoPreshade();
        settings.fPhysicalsOnly = plExportDlg::Instance().GetPhysicalsOnly();
        settings.fDoLightMap = plExportDlg::Instance().GetDoLightMap();
        settings.fExportPage = plExportDlg::Instance().GetExportPage();
    }

    plConvert::Instance().Init(gi, errorMessage, &settings);

    // We want to incorporate any SDL changes since the last export, so we DeInit()
    // and re-initialize.
    char buf[MAX_PATH];
    strcpy(buf, plMaxConfig::GetClientPath());
    strcat(buf, "sdl");
    plSDLMgr::GetInstance()->SetSDLDir(buf);
    plSDLMgr::GetInstance()->DeInit();
    plSDLMgr::GetInstance()->Init();

    // Add disk source for writing
    char datPath[MAX_PATH];
    strcpy(datPath, out_path);
    plFileUtils::AddSlash(datPath);
    strcat(datPath, "dat\\");
    CreateDirectory(datPath, NULL);
    plPluginResManager::ResMgr()->SetDataPath(datPath);

    if (hsgResMgr::Reset())
    {
        plSimulationMgr::Init();
        plAvatarMgr::GetInstance();

        // Verify the pages here manually, since it's a separate step now
        plPluginResManager::ResMgr()->VerifyPages();

        plPythonFileMod::SetAtConvertTime();

        // Convert!!!
        bool convertOK = plConvert::Instance().Convert();

        // Free the material cache.  This will delete unused materials.
        hsMaterialConverter::Instance().FreeMaterialCache(out_path);

        if (convertOK)
        {
            // Optimize the drawables
            plOptimizeIterator  optIterator;
            plPluginResManager::ResMgr()->IterateKeys( &optIterator );

            // And save.
            plPluginResManager::ResMgr()->WriteAllPages();

            // Write out a texture log file
            char textureLog[MAX_PATH];
            sprintf(textureLog, "log\\exportedTextures_%s.log", fName);
            plTextureExportLog      textureExportLog( textureLog );
            plTextureLoggerCBack    loggerCallback( &textureExportLog );
            
            plPluginResManager::ResMgr()->IterateKeys( &loggerCallback );
            
            textureExportLog.Write();

            // Moving this to the end of writing the files out. Yes, this means that any unused mipmaps still get
            // written to disk, including ones loaded on preload, but it's the only way to get shared texture pages
            // to work without loading in the entire age worth of reffing objects. - 5.30.2002 mcn
            plBitmapCreator::Instance().DeInit();
        }

        // Have the resMgr clean up after export. This includes paging out any converted pages
        plPluginResManager::ResMgr()->EndExport();

        plSimulationMgr::Shutdown();
        plAvatarMgr::ShutDown();

        // Reset the resmgr so we free all the memory it allocated
        hsgResMgr::Reset();
    }


    //----------------------------------------------
    // Write a log entry to the Db file name for now
    //----------------------------------------------
    hsUNIXStream dbLog;
    dbLog.Open(name,"at");
    char str[256];
    exportTime = (timeGetTime() - exportTime) / 1000;
    sprintf(str,"Export from Max File \"%s\" on %02d/%02d/%4d took %d:%02d\n",filename,tm.wMonth,tm.wDay,tm.wYear, exportTime/60, exportTime%60);
    dbLog.WriteString(str);
    dbLog.Close();

    // Allow plugins to clean up after export
    BroadcastNotification(NOTIFY_POST_EXPORT);

    hsConverterUtils::Instance().DestroyNodeSearchCache();
    gUserPropMgr.CloseQuickTable();
    gi->UnRegisterExitMAXCallback(&exitCB);
    hsMessageBox_SuppressPrompts = mbSuppressPrompts;
    TheManager->SetSilentMode(bmmSilentMode);
    gi->EnableAutoBackup(backupEnabled);

    MessageBeep(MB_ICONASTERISK);

    return 1;
}
Example #13
0
/*******************************************************************************
 *
 *  FUNCTION: _CmdWndProc(HWND, unsigned, WORD, LONG)
 *
 *  PURPOSE:  Processes WM_COMMAND messages for the main frame window.
 *
 */
static BOOL _CmdWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    HKEY hKeyRoot = 0, hKey = 0;
    LPCTSTR keyPath;
    LPCTSTR valueName;
    BOOL result = TRUE;
    REGSAM regsam = KEY_READ;
    LONG lRet;
    int item;

    UNREFERENCED_PARAMETER(lParam);
    UNREFERENCED_PARAMETER(message);

    switch (LOWORD(wParam))
    {
    case ID_REGISTRY_LOADHIVE:
        LoadHive(hWnd);
        return TRUE;
    case ID_REGISTRY_UNLOADHIVE:
        UnloadHive(hWnd);
        return TRUE;
    case ID_REGISTRY_IMPORTREGISTRYFILE:
        ImportRegistryFile(hWnd);
        return TRUE;
    case ID_REGISTRY_EXPORTREGISTRYFILE:
        ExportRegistryFile(hWnd);
        return TRUE;
    case ID_REGISTRY_CONNECTNETWORKREGISTRY:
    {
        IDsObjectPicker *ObjectPicker;
        TCHAR szComputerName[MAX_COMPUTERNAME_LENGTH + 1];
        HRESULT hRet;

        hRet = CoInitialize(NULL);
        if (SUCCEEDED(hRet))
        {
            hRet = InitializeRemoteRegistryPicker(&ObjectPicker);
            if (SUCCEEDED(hRet))
            {
                hRet = InvokeRemoteRegistryPickerDialog(ObjectPicker,
                                                        hWnd,
                                                        szComputerName,
                                                        sizeof(szComputerName) / sizeof(szComputerName[0]));
                if (hRet == S_OK)
                {
                    /* FIXME - connect to the registry */
                }

                FreeObjectPicker(ObjectPicker);
            }

            CoUninitialize();
        }

        return TRUE;
    }
    case ID_REGISTRY_DISCONNECTNETWORKREGISTRY:
        return TRUE;
    case ID_REGISTRY_PRINT:
        PrintRegistryHive(hWnd, _T(""));
        return TRUE;
    case ID_REGISTRY_EXIT:
        DestroyWindow(hWnd);
        return TRUE;
    case ID_VIEW_STATUSBAR:
        toggle_child(hWnd, LOWORD(wParam), hStatusBar);
        return TRUE;
    case ID_HELP_HELPTOPICS:
        WinHelp(hWnd, _T("regedit"), HELP_FINDER, 0);
        return TRUE;
    case ID_HELP_ABOUT:
        ShowAboutBox(hWnd);
        return TRUE;
    case ID_VIEW_SPLIT:
    {
        RECT rt;
        POINT pt, pts;
        GetClientRect(g_pChildWnd->hWnd, &rt);
        pt.x = rt.left + g_pChildWnd->nSplitPos;
        pt.y = (rt.bottom / 2);
        pts = pt;
        if(ClientToScreen(g_pChildWnd->hWnd, &pts))
        {
            SetCursorPos(pts.x, pts.y);
            SetCursor(LoadCursor(0, IDC_SIZEWE));
            SendMessage(g_pChildWnd->hWnd, WM_LBUTTONDOWN, 0, MAKELPARAM(pt.x, pt.y));
        }
        return TRUE;
    }
    case ID_EDIT_RENAME:
    case ID_EDIT_MODIFY:
    case ID_EDIT_MODIFY_BIN:
    case ID_EDIT_DELETE:
        regsam |= KEY_WRITE;
        break;
    }

    keyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot);
    valueName = GetValueName(g_pChildWnd->hListWnd, -1);
    if (keyPath)
    {
        lRet = RegOpenKeyEx(hKeyRoot, keyPath, 0, regsam, &hKey);
        if (lRet != ERROR_SUCCESS) hKey = 0;
    }

    switch (LOWORD(wParam))
    {
    case ID_EDIT_MODIFY:
        if (valueName && ModifyValue(hWnd, hKey, valueName, FALSE))
            RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath);
        break;
    case ID_EDIT_MODIFY_BIN:
        if (valueName && ModifyValue(hWnd, hKey, valueName, TRUE))
            RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath);
        break;
    case ID_EDIT_RENAME:
        if (GetFocus() == g_pChildWnd->hListWnd)
        {
            if(ListView_GetSelectedCount(g_pChildWnd->hListWnd) == 1)
            {
                item = ListView_GetNextItem(g_pChildWnd->hListWnd, -1, LVNI_SELECTED);
                if(item > -1)
                {
                    (void)ListView_EditLabel(g_pChildWnd->hListWnd, item);
                }
            }
        }
        else if (GetFocus() == g_pChildWnd->hTreeWnd)
        {
            /* Get focused entry of treeview (if any) */
            HTREEITEM hItem = TreeView_GetSelection(g_pChildWnd->hTreeWnd);
            if (hItem != NULL)
                (void)TreeView_EditLabel(g_pChildWnd->hTreeWnd, hItem);
        }
        break;
    case ID_EDIT_DELETE:
    {
        if (GetFocus() == g_pChildWnd->hListWnd)
        {
            UINT nSelected = ListView_GetSelectedCount(g_pChildWnd->hListWnd);
            if(nSelected >= 1)
            {
                TCHAR msg[128], caption[128];
                LoadString(hInst, IDS_QUERY_DELETE_CONFIRM, caption, sizeof(caption)/sizeof(TCHAR));
                LoadString(hInst, (nSelected == 1 ? IDS_QUERY_DELETE_ONE : IDS_QUERY_DELETE_MORE), msg, sizeof(msg)/sizeof(TCHAR));
                if(MessageBox(g_pChildWnd->hWnd, msg, caption, MB_ICONQUESTION | MB_YESNO) == IDYES)
                {
                    int ni, errs;

                    item = -1;
                    errs = 0;
                    while((ni = ListView_GetNextItem(g_pChildWnd->hListWnd, item, LVNI_SELECTED)) > -1)
                    {
                        valueName = GetValueName(g_pChildWnd->hListWnd, item);
                        if(RegDeleteValue(hKey, valueName) != ERROR_SUCCESS)
                        {
                            errs++;
                        }
                        item = ni;
                    }

                    RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath);
                    if(errs > 0)
                    {
                        LoadString(hInst, IDS_ERR_DELVAL_CAPTION, caption, sizeof(caption)/sizeof(TCHAR));
                        LoadString(hInst, IDS_ERR_DELETEVALUE, msg, sizeof(msg)/sizeof(TCHAR));
                        MessageBox(g_pChildWnd->hWnd, msg, caption, MB_ICONSTOP);
                    }
                }
            }
        }
        else if (GetFocus() == g_pChildWnd->hTreeWnd)
        {
            if (keyPath == 0 || *keyPath == 0)
            {
                MessageBeep(MB_ICONHAND);
            }
            else if (DeleteKey(hWnd, hKeyRoot, keyPath))
            {
                DeleteNode(g_pChildWnd->hTreeWnd, 0);
                RefreshTreeView(g_pChildWnd->hTreeWnd);
            }
        }
        break;
    }
    case ID_EDIT_NEW_STRINGVALUE:
        CreateNewValue(hKeyRoot, keyPath, REG_SZ);
        break;
    case ID_EDIT_NEW_BINARYVALUE:
        CreateNewValue(hKeyRoot, keyPath, REG_BINARY);
        break;
    case ID_EDIT_NEW_DWORDVALUE:
        CreateNewValue(hKeyRoot, keyPath, REG_DWORD);
        break;
    case ID_EDIT_NEW_MULTISTRINGVALUE:
        CreateNewValue(hKeyRoot, keyPath, REG_MULTI_SZ);
        break;
    case ID_EDIT_NEW_EXPANDABLESTRINGVALUE:
        CreateNewValue(hKeyRoot, keyPath, REG_EXPAND_SZ);
        break;
    case ID_EDIT_FIND:
        FindDialog(hWnd);
        break;
    case ID_EDIT_FINDNEXT:
        FindNext(hWnd);
        break;
    case ID_EDIT_COPYKEYNAME:
        CopyKeyName(hWnd, hKeyRoot, keyPath);
        break;
    case ID_EDIT_PERMISSIONS:
        RegKeyEditPermissions(hWnd, hKeyRoot, NULL, keyPath);
        break;
    case ID_REGISTRY_PRINTERSETUP:
        /*PRINTDLG pd;*/
        /*PrintDlg(&pd);*/
        /*PAGESETUPDLG psd;*/
        /*PageSetupDlg(&psd);*/
        break;
    case ID_REGISTRY_OPENLOCAL:
        break;

    case ID_VIEW_REFRESH:
        RefreshTreeView(g_pChildWnd->hTreeWnd);
        /*RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath, NULL); */
        break;
        /*case ID_OPTIONS_TOOLBAR:*/
        /*	toggle_child(hWnd, LOWORD(wParam), hToolBar);*/
        /*    break;*/
    case ID_EDIT_NEW_KEY:
        CreateNewKey(g_pChildWnd->hTreeWnd, TreeView_GetSelection(g_pChildWnd->hTreeWnd));
        break;
    default:
        if ((LOWORD(wParam) >= ID_FAVORITES_MIN) && (LOWORD(wParam) <= ID_FAVORITES_MAX))
        {
            HMENU hMenu;
            MENUITEMINFO mii;
            TCHAR szFavorite[512];

            hMenu = GetSubMenu(GetMenu(hWnd), FAVORITES_MENU_POSITION);

            memset(&mii, 0, sizeof(mii));
            mii.cbSize = sizeof(mii);
            mii.fMask = MIIM_TYPE;
            mii.fType = MFT_STRING;
            mii.dwTypeData = szFavorite;
            mii.cch = sizeof(szFavorite) / sizeof(szFavorite[0]);

            if (GetMenuItemInfo(hMenu, LOWORD(wParam) - ID_FAVORITES_MIN, TRUE, &mii))
            {
                ChooseFavorite(szFavorite);
            }
        }
        else
        {
            result = FALSE;
        }
        break;
    }

    if(hKey)
        RegCloseKey(hKey);
    return result;
}
Example #14
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	static int		idColor[5] = {WHITE_BRUSH, LTGRAY_BRUSH, GRAY_BRUSH, DKGRAY_BRUSH, BLACK_BRUSH};
	static int		iSelection = IDM_BKGND_WHITE;
	static HMENU	hMenu, hSubMenu;
	POINT			point;
	int				cnt;
	HDC				hdc;
	TCHAR			szBuffer[10];

	switch (message) {
	//case WM_CREATE:
	//	hMenu = LoadMenu(hInst, szAppName);
	//	hMenu = GetSubMenu(hMenu, 0);
	//	return 0;

	case WM_RBUTTONUP:
		hMenu = LoadMenu(hInst, szAppName);
		hMenu = GetSubMenu(hMenu, 1);
		
		point.x = LOWORD(lParam);
		point.y = HIWORD(lParam);
		ClientToScreen(hwnd, &point);
		TrackPopupMenu(hMenu, TPM_RIGHTBUTTON, point.x, point.y, 0, hwnd, NULL);


		//Show count
		hSubMenu = GetSubMenu(hMenu, 0);
		hdc = GetDC(hwnd);
		TextOut(hdc,0 ,0, szBuffer, wsprintf(szBuffer, TEXT("File: %i"), GetMenuItemCount(hSubMenu))); 
		ReleaseDC(hwnd, hdc);
		DestroyMenu(hSubMenu);

		hSubMenu = GetSubMenu(hMenu, 3);
		hdc = GetDC(hwnd);
		TextOut(hdc,0 ,20, szBuffer, wsprintf(szBuffer, TEXT("Timer: %i"), GetMenuItemCount(hSubMenu))); 
		ReleaseDC(hwnd, hdc);
		DestroyMenu(hSubMenu);

		DestroyMenu(hMenu);

		return 0;

	case WM_COMMAND:
		hMenu = GetMenu(hwnd);
		switch (LOWORD (wParam)) {
		case IDM_FILE_NEW:
		case IDM_FILE_OPEN:
		case IDM_FILE_SAVE:
		case IDM_FILE_SAVE_AS:
			MessageBeep(0);
			return 0;

		case IDM_APP_EXIT:
			SendMessage(hwnd, WM_CLOSE, 0, 0);
			return 0;

		case IDM_EDIT_UNDO:
		case IDM_EDIT_CUT:
		case IDM_EDIT_COPY:
		case IDM_EDIT_PASTE:
		case IDM_EDIT_CLEAR:
			MessageBeep(0);
			return 0;

		case IDM_BKGND_WHITE:
		case IDM_BKGND_LTGRAY:
		case IDM_BKGND_GRAY:
		case IDM_BKGND_DKGRAY:
		case IDM_BKGND_BLACK:
			CheckMenuItem(hMenu, iSelection, MF_UNCHECKED);
			iSelection = LOWORD(wParam);
			CheckMenuItem(hMenu, iSelection, MF_CHECKED);

			SetClassLong(hwnd, GCL_HBRBACKGROUND, (LONG) GetStockObject(idColor[LOWORD(wParam) - IDM_BKGND_WHITE]));
			InvalidateRect(hwnd, NULL, TRUE);
			return 0;

		case IDM_TIMER_START:
			if (SetTimer(hwnd, ID_TIMER, 1000, NULL)) {
				EnableMenuItem(hMenu, IDM_TIMER_START, MF_GRAYED);
				EnableMenuItem(hMenu, IDM_TIMER_STOP, MF_ENABLED);
			}
			return 0;

		case IDM_TIMER_STOP:
			KillTimer(hwnd, ID_TIMER);
			EnableMenuItem(hMenu, IDM_TIMER_START, MF_ENABLED);
			EnableMenuItem(hMenu, IDM_TIMER_STOP, MF_GRAYED);
			return 0;

		case IDM_APP_HELP:
			MessageBox(hwnd, TEXT("Help not yet implemented!"), szAppName, MB_ICONEXCLAMATION | MB_OK);
			return 0;

		case IDM_APP_ABOUT:
			MessageBox(hwnd, TEXT("Menu Demonstration Program\n") TEXT("(c) hogehoge, 2013"), szAppName, MB_ICONINFORMATION | MB_OK);
			return 0;
		}
		//break;
		return 0;

	case WM_TIMER:
		MessageBeep(0);
		return 0;

	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}

	return DefWindowProc(hwnd, message, wParam, lParam);
}
Example #15
0
/*
 * Dialog-box function for the main PuTTYgen dialog box.
 */
static int CALLBACK MainDlgProc(HWND hwnd, UINT msg,
				WPARAM wParam, LPARAM lParam)
{
    static const char generating_msg[] =
	"Please wait while a key is generated...";
    static const char entropy_msg[] =
	"Please generate some randomness by moving the mouse over the blank area.";
    struct MainDlgState *state;

    switch (msg) {
      case WM_INITDIALOG:
        if (help_path)
            SetWindowLong(hwnd, GWL_EXSTYLE,
                          GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_CONTEXTHELP);
        else {
            /*
             * If we add a Help button, this is where we destroy it
             * if the help file isn't present.
             */
        }
        requested_help = FALSE;

	state = smalloc(sizeof(*state));
	state->generation_thread_exists = FALSE;
	state->collecting_entropy = FALSE;
	state->entropy = NULL;
	state->key_exists = FALSE;
	SetWindowLong(hwnd, GWL_USERDATA, (LONG) state);
	{
	    HMENU menu, menu1;

	    menu = CreateMenu();

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_LOAD, "&Load private key");
	    AppendMenu(menu1, MF_ENABLED, IDC_SAVEPUB, "Save p&ublic key");
	    AppendMenu(menu1, MF_ENABLED, IDC_SAVE, "&Save private key");
	    AppendMenu(menu1, MF_SEPARATOR, 0, 0);
	    AppendMenu(menu1, MF_ENABLED, IDC_QUIT, "E&xit");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&File");
	    state->filemenu = menu1;

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_GENERATE, "&Generate key pair");
	    AppendMenu(menu1, MF_SEPARATOR, 0, 0);
	    AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH1, "SSH&1 key (RSA)");
	    AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2RSA, "SSH2 &RSA key");
	    AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2DSA, "SSH2 &DSA key");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&Key");
	    state->keymenu = menu1;

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_IMPORT, "&Import key");
	    AppendMenu(menu1, MF_SEPARATOR, 0, 0);
	    AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_OPENSSH,
		       "Export &OpenSSH key");
	    AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_SSHCOM,
		       "Export &ssh.com key");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1,
		       "&Conversions");
	    state->cvtmenu = menu1;

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_ABOUT, "&About");
	    if (help_path)
		AppendMenu(menu1, MF_ENABLED, IDC_GIVEHELP, "&Help");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&Help");

	    SetMenu(hwnd, menu);
	}

	/*
	 * Centre the window.
	 */
	{			       /* centre the window */
	    RECT rs, rd;
	    HWND hw;

	    hw = GetDesktopWindow();
	    if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
		MoveWindow(hwnd,
			   (rs.right + rs.left + rd.left - rd.right) / 2,
			   (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
			   rd.right - rd.left, rd.bottom - rd.top, TRUE);
	}

	{
	    struct ctlpos cp, cp2;

	    /* Accelerators used: acglops1rbd */

	    ctlposinit(&cp, hwnd, 4, 4, 4);
	    beginbox(&cp, "Key", IDC_BOX_KEY);
	    cp2 = cp;
	    statictext(&cp2, "No key.", 1, IDC_NOKEY);
	    cp2 = cp;
	    statictext(&cp2, "", 1, IDC_GENERATING);
	    progressbar(&cp2, IDC_PROGRESS);
	    bigeditctrl(&cp,
			"&Public key for pasting into authorized_keys file:",
			IDC_PKSTATIC, IDC_KEYDISPLAY, 5);
	    SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0);
	    staticedit(&cp, "Key fingerprint:", IDC_FPSTATIC,
		       IDC_FINGERPRINT, 75);
	    SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1,
			       0);
	    staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC,
		       IDC_COMMENTEDIT, 75);
	    staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC,
			   IDC_PASSPHRASE1EDIT, 75);
	    staticpassedit(&cp, "C&onfirm passphrase:",
			   IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 75);
	    endbox(&cp);
	    beginbox(&cp, "Actions", IDC_BOX_ACTIONS);
	    staticbtn(&cp, "Generate a public/private key pair",
		      IDC_GENSTATIC, "&Generate", IDC_GENERATE);
	    staticbtn(&cp, "Load an existing private key file",
		      IDC_LOADSTATIC, "&Load", IDC_LOAD);
	    static2btn(&cp, "Save the generated key", IDC_SAVESTATIC,
		       "Save p&ublic key", IDC_SAVEPUB,
		       "&Save private key", IDC_SAVE);
	    endbox(&cp);
	    beginbox(&cp, "Parameters", IDC_BOX_PARAMS);
	    radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 3,
		      "SSH&1 (RSA)", IDC_KEYSSH1,
		      "SSH2 &RSA", IDC_KEYSSH2RSA,
		      "SSH2 &DSA", IDC_KEYSSH2DSA, NULL);
	    staticedit(&cp, "Number of &bits in a generated key:",
		       IDC_BITSSTATIC, IDC_BITS, 20);
	    endbox(&cp);
	}
	CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2DSA, IDC_KEYSSH1);
	CheckMenuRadioItem(state->keymenu, IDC_KEYSSH1, IDC_KEYSSH2DSA,
			   IDC_KEYSSH1, MF_BYCOMMAND);
	SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEYSIZE, FALSE);

	/*
	 * Initially, hide the progress bar and the key display,
	 * and show the no-key display. Also disable the Save
	 * buttons, because with no key we obviously can't save
	 * anything.
	 */
	ui_set_state(hwnd, state, 0);

	/*
	 * Load a key file if one was provided on the command line.
	 */
	if (cmdline_keyfile)
	    load_key_file(hwnd, state, cmdline_keyfile, 0);

	return 1;
      case WM_MOUSEMOVE:
	state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	if (state->collecting_entropy &&
	    state->entropy && state->entropy_got < state->entropy_required) {
	    state->entropy[state->entropy_got++] = lParam;
	    state->entropy[state->entropy_got++] = GetMessageTime();
	    SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS,
			       state->entropy_got, 0);
	    if (state->entropy_got >= state->entropy_required) {
		struct rsa_key_thread_params *params;
		DWORD threadid;

		/*
		 * Seed the entropy pool
		 */
		random_add_heavynoise(state->entropy, state->entropy_size);
		memset(state->entropy, 0, state->entropy_size);
		sfree(state->entropy);
		state->collecting_entropy = FALSE;

		SetDlgItemText(hwnd, IDC_GENERATING, generating_msg);
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
				   MAKELPARAM(0, PROGRESSRANGE));
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);

		params = smalloc(sizeof(*params));
		params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS);
		params->dialog = hwnd;
		params->keysize = state->keysize;
		params->is_dsa = state->is_dsa;
		params->key = &state->key;
		params->dsskey = &state->dsskey;

		if (!CreateThread(NULL, 0, generate_rsa_key_thread,
				  params, 0, &threadid)) {
		    MessageBox(hwnd, "Out of thread resources",
			       "Key generation error",
			       MB_OK | MB_ICONERROR);
		    sfree(params);
		} else {
		    state->generation_thread_exists = TRUE;
		}
	    }
	}
	break;
      case WM_COMMAND:
	switch (LOWORD(wParam)) {
	  case IDC_KEYSSH1:
	  case IDC_KEYSSH2RSA:
	  case IDC_KEYSSH2DSA:
	    {
		state = (struct MainDlgState *)
		    GetWindowLong(hwnd, GWL_USERDATA);
		if (!IsDlgButtonChecked(hwnd, LOWORD(wParam)))
		    CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2DSA,
				     LOWORD(wParam));
		CheckMenuRadioItem(state->keymenu, IDC_KEYSSH1, IDC_KEYSSH2DSA,
				   LOWORD(wParam), MF_BYCOMMAND);
	    }
	    break;
	  case IDC_QUIT:
	    PostMessage(hwnd, WM_CLOSE, 0, 0);
	    break;
	  case IDC_COMMENTEDIT:
	    if (HIWORD(wParam) == EN_CHANGE) {
		state = (struct MainDlgState *)
		    GetWindowLong(hwnd, GWL_USERDATA);
		if (state->key_exists) {
		    HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT);
		    int len = GetWindowTextLength(editctl);
		    if (*state->commentptr)
			sfree(*state->commentptr);
		    *state->commentptr = smalloc(len + 1);
		    GetWindowText(editctl, *state->commentptr, len + 1);
		    if (state->ssh2) {
			setupbigedit2(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC,
				      &state->ssh2key);
		    } else {
			setupbigedit1(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC,
				      &state->key);
		    }
		}
	    }
	    break;
	  case IDC_ABOUT:
	    EnableWindow(hwnd, 0);
	    DialogBox(hinst, MAKEINTRESOURCE(213), NULL, AboutProc);
	    EnableWindow(hwnd, 1);
	    SetActiveWindow(hwnd);
	    return 0;
	  case IDC_GIVEHELP:
            if (HIWORD(wParam) == BN_CLICKED ||
                HIWORD(wParam) == BN_DOUBLECLICKED) {
                if (help_path) {
                    WinHelp(hwnd, help_path, HELP_COMMAND,
                            (DWORD)"JI(`',`puttygen.general')");
                    requested_help = TRUE;
                }
            }
	    return 0;
	  case IDC_GENERATE:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (!state->generation_thread_exists) {
		BOOL ok;
		state->keysize = GetDlgItemInt(hwnd, IDC_BITS, &ok, FALSE);
		if (!ok)
		    state->keysize = DEFAULT_KEYSIZE;
		/* If we ever introduce a new key type, check it here! */
		state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1);
		state->is_dsa = IsDlgButtonChecked(hwnd, IDC_KEYSSH2DSA);
		if (state->keysize < 256) {
		    int ret = MessageBox(hwnd,
					 "PuTTYgen will not generate a key"
					 " smaller than 256 bits.\n"
					 "Key length reset to 256. Continue?",
					 "PuTTYgen Warning",
					 MB_ICONWARNING | MB_OKCANCEL);
		    if (ret != IDOK)
			break;
		    state->keysize = 256;
		    SetDlgItemInt(hwnd, IDC_BITS, 256, FALSE);
		}
		ui_set_state(hwnd, state, 1);
		SetDlgItemText(hwnd, IDC_GENERATING, entropy_msg);
		state->key_exists = FALSE;
		state->collecting_entropy = TRUE;

		/*
		 * My brief statistical tests on mouse movements
		 * suggest that there are about 2.5 bits of
		 * randomness in the x position, 2.5 in the y
		 * position, and 1.7 in the message time, making
		 * 5.7 bits of unpredictability per mouse movement.
		 * However, other people have told me it's far less
		 * than that, so I'm going to be stupidly cautious
		 * and knock that down to a nice round 2. With this
		 * method, we require two words per mouse movement,
		 * so with 2 bits per mouse movement we expect 2
		 * bits every 2 words.
		 */
		state->entropy_required = (state->keysize / 2) * 2;
		state->entropy_got = 0;
		state->entropy_size = (state->entropy_required *
				       sizeof(*state->entropy));
		state->entropy = smalloc(state->entropy_size);

		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
				   MAKELPARAM(0, state->entropy_required));
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
	    }
	    break;
	  case IDC_SAVE:
          case IDC_EXPORT_OPENSSH:
          case IDC_EXPORT_SSHCOM:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (state->key_exists) {
		char filename[FILENAME_MAX];
		char passphrase[PASSPHRASE_MAXLEN];
		char passphrase2[PASSPHRASE_MAXLEN];
                int type, realtype;

                if (state->ssh2)
                    realtype = SSH_KEYTYPE_SSH2;
                else
                    realtype = SSH_KEYTYPE_SSH1;

                if (LOWORD(wParam) == IDC_EXPORT_OPENSSH)
                    type = SSH_KEYTYPE_OPENSSH;
                else if (LOWORD(wParam) == IDC_EXPORT_SSHCOM)
                    type = SSH_KEYTYPE_SSHCOM;
                else
                    type = realtype;

                if (type != realtype &&
                    import_target_type(type) != realtype) {
                    char msg[256];
                    sprintf(msg, "Cannot export an SSH%d key in an SSH%d"
                            " format", (state->ssh2 ? 2 : 1),
                            (state->ssh2 ? 1 : 2));
		    MessageBox(hwnd, msg,
                               "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    break;
                }

		GetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
			       passphrase, sizeof(passphrase));
		GetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
			       passphrase2, sizeof(passphrase2));
		if (strcmp(passphrase, passphrase2)) {
		    MessageBox(hwnd,
			       "The two passphrases given do not match.",
			       "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    break;
		}
		if (!*passphrase) {
		    int ret;
		    ret = MessageBox(hwnd,
				     "Are you sure you want to save this key\n"
				     "without a passphrase to protect it?",
				     "PuTTYgen Warning",
				     MB_YESNO | MB_ICONWARNING);
		    if (ret != IDYES)
			break;
		}
		if (prompt_keyfile(hwnd, "Save private key as:",
				   filename, 1, (type == realtype))) {
		    int ret;
		    FILE *fp = fopen(filename, "r");
		    if (fp) {
			char buffer[FILENAME_MAX + 80];
			fclose(fp);
			sprintf(buffer, "Overwrite existing file\n%.*s?",
				FILENAME_MAX, filename);
			ret = MessageBox(hwnd, buffer, "PuTTYgen Warning",
					 MB_YESNO | MB_ICONWARNING);
			if (ret != IDYES)
			    break;
		    }

		    if (state->ssh2) {
                        if (type != realtype)
                            ret = export_ssh2(filename, type, &state->ssh2key,
                                              *passphrase ? passphrase : NULL);
                        else
                            ret = ssh2_save_userkey(filename, &state->ssh2key,
                                                    *passphrase ? passphrase :
                                                    NULL);
		    } else {
                        if (type != realtype)
                            ret = export_ssh1(filename, type, &state->key,
                                              *passphrase ? passphrase : NULL);
                        else
                            ret = saversakey(filename, &state->key,
                                             *passphrase ? passphrase : NULL);
		    }
		    if (ret <= 0) {
			MessageBox(hwnd, "Unable to save key file",
				   "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    }
		}
	    }
	    break;
	  case IDC_SAVEPUB:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (state->key_exists) {
		char filename[FILENAME_MAX];
		if (prompt_keyfile(hwnd, "Save public key as:",
				   filename, 1, 0)) {
		    int ret;
		    FILE *fp = fopen(filename, "r");
		    if (fp) {
			char buffer[FILENAME_MAX + 80];
			fclose(fp);
			sprintf(buffer, "Overwrite existing file\n%.*s?",
				FILENAME_MAX, filename);
			ret = MessageBox(hwnd, buffer, "PuTTYgen Warning",
					 MB_YESNO | MB_ICONWARNING);
			if (ret != IDYES)
			    break;
		    }
		    if (state->ssh2) {
			ret = save_ssh2_pubkey(filename, &state->ssh2key);
		    } else {
			ret = save_ssh1_pubkey(filename, &state->key);
		    }
		    if (ret <= 0) {
			MessageBox(hwnd, "Unable to save key file",
				   "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    }
		}
	    }
	    break;
	  case IDC_LOAD:
	  case IDC_IMPORT:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (!state->generation_thread_exists) {
		char filename[FILENAME_MAX];
		if (prompt_keyfile(hwnd, "Load private key:",
				   filename, 0, LOWORD(wParam)==IDC_LOAD))
		    load_key_file(hwnd, state, filename,
				  LOWORD(wParam) != IDC_LOAD);
	    }
	    break;
	}
	return 0;
      case WM_DONEKEY:
	state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	state->generation_thread_exists = FALSE;
	state->key_exists = TRUE;
	SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
			   MAKELPARAM(0, PROGRESSRANGE));
	SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0);
	if (state->ssh2) {
	    if (state->is_dsa) {
		state->ssh2key.data = &state->dsskey;
		state->ssh2key.alg = &ssh_dss;
	    } else {
		state->ssh2key.data = &state->key;
		state->ssh2key.alg = &ssh_rsa;
	    }
	    state->commentptr = &state->ssh2key.comment;
	} else {
	    state->commentptr = &state->key.comment;
	}
	/*
	 * Invent a comment for the key. We'll do this by including
	 * the date in it. This will be so horrifyingly ugly that
	 * the user will immediately want to change it, which is
	 * what we want :-)
	 */
	*state->commentptr = smalloc(30);
	{
	    time_t t;
	    struct tm *tm;
	    time(&t);
	    tm = localtime(&t);
	    if (state->is_dsa)
		strftime(*state->commentptr, 30, "dsa-key-%Y%m%d", tm);
	    else
		strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", tm);
	}

	/*
	 * Now update the key controls with all the key data.
	 */
	{
	    char *savecomment;
	    /*
	     * Blank passphrase, initially. This isn't dangerous,
	     * because we will warn (Are You Sure?) before allowing
	     * the user to save an unprotected private key.
	     */
	    SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, "");
	    SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, "");
	    /*
	     * Set the comment.
	     */
	    SetDlgItemText(hwnd, IDC_COMMENTEDIT, *state->commentptr);
	    /*
	     * Set the key fingerprint.
	     */
	    savecomment = *state->commentptr;
	    *state->commentptr = NULL;
	    if (state->ssh2) {
		char *fp;
		fp = state->ssh2key.alg->fingerprint(state->ssh2key.data);
		SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
		sfree(fp);
	    } else {
		char buf[128];
		rsa_fingerprint(buf, sizeof(buf), &state->key);
		SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
	    }
	    *state->commentptr = savecomment;
	    /*
	     * Construct a decimal representation of the key, for
	     * pasting into .ssh/authorized_keys or
	     * .ssh/authorized_keys2 on a Unix box.
	     */
	    if (state->ssh2) {
		setupbigedit2(hwnd, IDC_KEYDISPLAY,
			      IDC_PKSTATIC, &state->ssh2key);
	    } else {
		setupbigedit1(hwnd, IDC_KEYDISPLAY,
			      IDC_PKSTATIC, &state->key);
	    }
	}
	/*
	 * Finally, hide the progress bar and show the key data.
	 */
	ui_set_state(hwnd, state, 2);
	break;
      case WM_HELP:
        if (help_path) {
            int id = ((LPHELPINFO)lParam)->iCtrlId;
            char *cmd = NULL;
            switch (id) {
              case IDC_GENERATING:
              case IDC_PROGRESS:
              case IDC_GENSTATIC:
              case IDC_GENERATE:
                cmd = "JI(`',`puttygen.generate')"; break;
              case IDC_PKSTATIC:
              case IDC_KEYDISPLAY:
                cmd = "JI(`',`puttygen.pastekey')"; break;
              case IDC_FPSTATIC:
              case IDC_FINGERPRINT:
                cmd = "JI(`',`puttygen.fingerprint')"; break;
              case IDC_COMMENTSTATIC:
              case IDC_COMMENTEDIT:
                cmd = "JI(`',`puttygen.comment')"; break;
              case IDC_PASSPHRASE1STATIC:
              case IDC_PASSPHRASE1EDIT:
              case IDC_PASSPHRASE2STATIC:
              case IDC_PASSPHRASE2EDIT:
                cmd = "JI(`',`puttygen.passphrase')"; break;
              case IDC_LOADSTATIC:
              case IDC_LOAD:
                cmd = "JI(`',`puttygen.load')"; break;
              case IDC_SAVESTATIC:
              case IDC_SAVE:
                cmd = "JI(`',`puttygen.savepriv')"; break;
              case IDC_SAVEPUB:
                cmd = "JI(`',`puttygen.savepub')"; break;
              case IDC_TYPESTATIC:
              case IDC_KEYSSH1:
              case IDC_KEYSSH2RSA:
              case IDC_KEYSSH2DSA:
                cmd = "JI(`',`puttygen.keytype')"; break;
              case IDC_BITSSTATIC:
              case IDC_BITS:
                cmd = "JI(`',`puttygen.bits')"; break;
              case IDC_IMPORT:
              case IDC_EXPORT_OPENSSH:
              case IDC_EXPORT_SSHCOM:
                cmd = "JI(`',`puttygen.conversions')"; break;
            }
            if (cmd) {
                WinHelp(hwnd, help_path, HELP_COMMAND, (DWORD)cmd);
                requested_help = TRUE;
            } else {
                MessageBeep(0);
            }
        }
        break;
      case WM_CLOSE:
	state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	sfree(state);
        if (requested_help) {
            WinHelp(hwnd, help_path, HELP_QUIT, 0);
            requested_help = FALSE;
        }
	EndDialog(hwnd, 1);
	return 0;
    }
    return 0;
}
Example #16
0
void Sys_Beep( void )
{
	MessageBeep( MB_ICONASTERISK );
}
Example #17
0
LRESULT CALLBACK EditCtlProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
    LPCTSTR lpTable, lpTable1;
    TCHAR   c;
#ifdef FAREAST
    TCHAR ch, chHW;
#endif // FAREAST
    HKL     hkl = GetKeyboardLayout(0);

    ASSERT(oldEditCtlProc);

    switch (message) {
    case WM_PASTE :
    {
        BOOL bPassThrough = TRUE;

        if (IsNumericOnlyEdit(hwnd))
        {
            // only going to accept pastes that have pure numeric data in them

            HANDLE hMem;

            if(OpenClipboard(hwnd))
            {
                hMem = GetClipboardData(CF_UNICODETEXT);
                if(hMem)
                {
                    TCHAR *pText = (TCHAR *)LocalLock(hMem); // can't fail on CE
                    int iLen = _tcslen(pText);
                    int iPos = 0;

                    for (iPos = 0; (iPos < iLen) && bPassThrough; iPos++)
                    {
                        if (!_istdigit(pText[iPos]))
                        {
                            // bad char
                            bPassThrough = FALSE;

                        }
                    }

                    LocalUnlock(hMem);
                }
                CloseClipboard();
            }
        }

        if (bPassThrough)
        {
            return CallWindowProc(oldEditCtlProc,hwnd, message, wParam, lParam);
        } else {
            MessageBeep(MB_OK);
            return FALSE;
        }
    }
    break;


    case WM_IME_COMPOSITION:
        if( ImmIsIME(hkl ) &&
                LOWORD(hkl ) == MAKELANGID(LANG_KOREAN, SUBLANG_DEFAULT))
        {
            HIMC himc = ImmGetContext(hwnd);
            if (himc)
            {
                TCHAR szTempStr[4];
                if (0<ImmGetCompositionString(himc,GCS_COMPSTR, szTempStr, 4))
                {
                    DWORD fdwConversion;
                    DWORD fdwSentence;

                    ImmNotifyIME(himc,NI_COMPOSITIONSTR,CPS_CANCEL,0);
                    ImmGetConversionStatus(himc, &fdwConversion, &fdwSentence);
                    fdwConversion&=(~IME_CMODE_NATIVE);
                    ImmSetConversionStatus(himc,fdwConversion, fdwSentence);
                }
                ImmReleaseContext(hwnd,himc);
                return CallWindowProc(oldEditCtlProc,hwnd, message, wParam, lParam);
            }
        }
        break;

    case WM_CHAR:
#ifdef FAREAST // Convert full-width numbers to half width
        ch = (TCHAR)wParam;
        LCMapString(LOCALE_USER_DEFAULT, LCMAP_HALFWIDTH,
                    &ch, 1, &chHW, 1);
        wParam = (WPARAM)chHW;
#endif // FAREAST
        // This character is not ASCII. If your country/region needs specific characters. You
        // have to change this. Otherwise, we abandon this character.
        if (wParam >= 0x80 )  {  // service on ilegal chars
            MessageBeep(MB_OK);
            return TRUE;
        }
        if (wParam < VK_SPACE || wParam > 0x7e )  {  // service on legal chars
            //DPF("None ascii char. ignore \r\n ");
            break;
        }

        if ((lpTable = GetTable(hwnd)) == NULL) {
            //				DPF("Can not find table, trying parent \r\n");
            if ((lpTable = GetTable(GetParent(hwnd))) == NULL) {
                //DPF("Can not find table,  \r\n");
                break;
            }
        }
        lpTable1 = lpTable;
        if (wParam >= '0' && wParam <= '9')
            goto found;
        while ((c = *lpTable++) > 0) {
            if ((TCHAR)wParam == c)
                goto found;
        }
        // now try w/ upper case
        if (iswlower((TCHAR)wParam)) {
            wParam = (LPARAM)towupper((TCHAR)wParam);
            while ((c = *lpTable1++) > 0) {
                if ((TCHAR)wParam == c)
                    goto found;
            }
        }
        //DPF1("Char '%c' not in table\r\n", wParam);
        MessageBeep(MB_OK);
        return TRUE;
found:
        //DPF1("Found char '%c' in table\r\n", wParam);
        break;
    default:
        break;
    }                                                                                   // of switch
    return CallWindowProc(oldEditCtlProc, hwnd, message, wParam, lParam);
}
Example #18
0
int
text_putch(TW *tw, int ch)
{
int pos;
int n;
#ifndef WINDOWS_NO_UNICODE
int shift = tw->utf8shift;
    tw->utf8shift=0;
#endif
    if (tw->quitnow)
        return ch;	/* don't write error message as we shut down */
    switch(ch) {
        case '\r':
                tw->CursorPos.x = 0;
                if (tw->CursorFlag)
                    text_to_cursor(tw);
                break;
        case '\n':
                text_new_line(tw);
                break;
        case 7:
                MessageBeep(-1);
                if (tw->CursorFlag)
                    text_to_cursor(tw);
                break;
        case '\t':
                {
                    for (n = 8 - (tw->CursorPos.x % 8); n>0; n-- )
                            text_putch(tw, ' ');
                }
                break;
        case 0x08:
        case 0x7f:
                tw->CursorPos.x--;
                if (tw->CursorPos.x < 0) {
                    tw->CursorPos.x = tw->ScreenSize.x - 1;
                    tw->CursorPos.y--;
                }
                if (tw->CursorPos.y < 0)
                    tw->CursorPos.y = 0;
                break;
        default:
                pos = tw->CursorPos.y*tw->ScreenSize.x + tw->CursorPos.x;
#ifndef WINDOWS_NO_UNICODE
                /* Are we continuing a unicode char? */
                if ((ch & 0xC0) == 0x80) {
                    tw->ScreenBuffer[pos] |= (ch & 0x3F)<<shift;
                    if (shift > 0)
                        tw->utf8shift = shift-6;
                    else
                        text_update_text(tw, 1); /* Only update when complete */
                } else if (ch >= 0xe0) { /* 2 more to come */
                    tw->ScreenBuffer[pos] = (ch & 0x0f)<<12;
                    tw->utf8shift = 6;
                } else if (ch >= 0xC0) { /* 1 more to come */
                    tw->ScreenBuffer[pos] = (ch & 0x01f)<<6;
                    tw->utf8shift = 0;
                }
                else
#endif
                {
                    tw->ScreenBuffer[pos] = ch;
                    text_update_text(tw, 1);
                }
    }
    return ch;
}
Example #19
0
int 
OpenDocument(
    WORD    mode,
    WORD    type,
    int     doc,
    LPSTR   FileName,
    int     dupView,
    int     Preference,
    BOOL    bUserActivated
    )

/*++

Routine Description:

    This routine is used to create a new document or to duplicate
    the view of an existing document.

Arguments:

    mode        - Supplies MODE_DUPLICATE if the document is to be duplicated
                           MODE_RELOAD if the file is to be reloaded
                           MODE_CREATE if the document is to be created
    type        - Supplies the document type
    doc         - Supplies
    FileName    - Supplies a pointer to the name of the file for the document
    dupView     - Supplies the view to be duplicated (mode == MODE_DUPLICATE)
    Preference  - Supplies the view preference (-1 if none)
    bUserActivated - Indicates whether this action was initiated by the
                user or by windbg. The value is to determine the Z order of
                any windows that are opened.

Return Value:

    -1 on failure
    view number on success (>= 0)
    return-value - Description of conditions needed to return value. - or -

--*/

{
    LPLINEREC   pl;
    int         nView = 0;
    BOOL        create;
    int         n;
    int         language;
    LPDOCREC    d;
    LPVIEWREC   views;

    //
    //  In mode duplicate, we create a new nView being a copy of the previous
    //  nView of the same document
    //

    if (mode == MODE_DUPLICATE) {

        //
        // Search a free entry for the nView we will create
        //

        if ( (Preference != -1) && Views[ Preference ].Doc == -1 ) {
            nView = Preference;
        } else {
            for (nView = 0; (nView < MAX_VIEWS) && (Views[nView].Doc != -1); nView++);
        }

        if (nView == MAX_VIEWS) {
            ErrorBox(ERR_Too_Many_Opened_Views);
            return -1;
        }

        //
        // Copy parameters from previous nView
        //

        Assert( Docs[Views[dupView].Doc].FirstView >= 0);

        //
        //      Find the last nView for this document
        //

        n = dupView;
        while (Views[n].NextView != -1) {
            n = Views[n].NextView;
        }

        Assert(n < MAX_VIEWS);

        //
        //     Attach new nView to last one found
        //

        Views[nView] = Views[n];
        Views[n].NextView = nView;
        Views[nView].hwndClient = NULL;

        //
        //
        //

        Views[nView].iYTop = Views[dupView].iYTop;

        //
        //     Enlist nView in window menu
        //

        AddWindowMenuItem(Views[dupView].Doc, nView);

        return nView;

    } else if (mode == MODE_RELOAD) {
        nView = Docs[doc].FirstView;
    }

    //
    // First search a free entry for the document
    //

    if (mode != MODE_RELOAD) {
        for (doc = 0; (doc < MAX_DOCUMENTS) && (Docs[doc].FirstView != -1); doc++);
    }

    if (doc >= MAX_DOCUMENTS) {
        ErrorBox(ERR_Too_Many_Opened_Documents);
        return -1;
    }

    d = &Docs[doc];

    if (type == DOC_WIN) {

        //
        //      Check if file is not already loaded
        //

        if (mode == MODE_RELOAD) {
            DestroyDocument(doc);
            language = SetLanguage(doc);
        } else {
            if (FileName != NULL) {
                TCHAR szAbsolutePath[_MAX_PATH] = {0};

                Assert(sizeof(szAbsolutePath) == sizeof(d->szFileName));

                // We may have a relative path name to a file. Try to get the absolute path.
                if ( _fullpath(szAbsolutePath, FileName, sizeof(szAbsolutePath) ) ) {
                    // success
                    _tcscpy(d->szFileName, szAbsolutePath);
                } else {
                    // error. Use as is.
                    _tcscpy(d->szFileName, FileName);
                }

                for (n = 0; n < MAX_DOCUMENTS; n++) {
                    if (Docs[n].FirstView != -1
                        && _strcmpi(Docs[n].szFileName, d->szFileName) == 0) {

                        SetMessageText_StatusBar(ERR_File_Already_Loaded, STATUS_INFOTEXT, FileName);
                        MessageBeep(0);

                        //
                        //  Reactivate window
                        //

                        //SendMessage(g_hwndMDIClient, WM_MDIACTIVATE, (WPARAM) Views[Docs[n].FirstView].hwndFrame, 0L);
                        ActivateMDIChild(Views[Docs[n].FirstView].hwndFrame, bUserActivated);
                        return -1;
                    }
                }

                language = SetLanguage(doc);

            } else {
                // shouldn't happen anymore
                Assert(0);
// BUGBUG - dead code - kcarlos
#if 0
                //
                //  Initialize document record and first nView
                //

                register int i, j;

                for (i = 0; i < MAX_DOCUMENTS; i++) {
                    CreateUntitled(d->FileName, i + 1);
                    for (j = 0; j < MAX_DOCUMENTS; j++) {
                        if (j != doc &&
                            _strcmpi (d->szFileName, Docs[j].szFileName) == 0) {
                            break;
                        }
                    }
                    if (j >= MAX_DOCUMENTS) {
                        break;
                    }
                }

                language = C_LANGUAGE;
#endif
            }
        }
    } else {

        WORD winTitle;
        char rgch[MAX_MSG_TXT];

        language = NO_LANGUAGE;

        //
        //  Non Document type, Load window title from ressource
        //

        switch (type) {

        case DISASM_WIN:
            winTitle = SYS_DisasmWin_Title;
            break;       
        case COMMAND_WIN:
            winTitle = SYS_CmdWin_Title;
            break;
        case MEMORY_WIN:
            winTitle = SYS_MemoryWin_Title;
            break;
        default:
            Assert(FALSE);
            return -1;
            break;
        }
        Dbg(LoadString(g_hInst, winTitle, rgch, MAX_MSG_TXT));
        RemoveMnemonic(rgch, d->szFileName);

        if (type == MEMORY_WIN) {
            lstrcat (d->szFileName,"(");
            lstrcat (d->szFileName,TempMemWinDesc.szAddress);
            lstrcat (d->szFileName,")");
        }
    }

    //
    //  Then search a free entry for the first nView we will create
    //

    if (mode != MODE_RELOAD) {

        if ( (Preference != -1) && Views[ Preference ].Doc == -1 ) {
            nView = Preference;
        } else {
            for (nView = 0; nView < MAX_VIEWS && Views[nView].Doc != -1; nView++);
        }
        if (nView == MAX_VIEWS) {
            ErrorBox(ERR_Too_Many_Opened_Views);
            return -1;
        }
    }

    //
    // Check if file exist
    //

    if (mode == MODE_CREATE || type != DOC_WIN) {
        create = TRUE;
    } else {
        if (mode == MODE_OPEN || FileExist(FileName)) {
            create = FALSE;
        } else {
            if (mode == MODE_OPENCREATE) {
                // Tell the user that the file does not exist.

                // kcarlos
                // BUGBUG
                // Quick hack. To fix a bug, hopefully this all disappear soon.
                VarMsgBox(hwndFrame, SYS_Does_Not_Exist_Create, MB_OK, FileName);
                return -1;
            } else {
                create = FALSE;
            }
        }
    }

    d->readOnly = FALSE;
    d->docType = type;
    d->language = (WORD) language;
    d->untitled = (FileName == NULL);
    d->ismodified = FALSE;

    if (create) {

        LPBLOCKDEF pb;

        //
        //  Initialize the file with a null-string
        //


        d->LastBlock = d->FirstBlock = (LPBLOCKDEF)DocAlloc(sizeof(BLOCKDEF));
        GetSystemTimeAsFileTime(&d->time);

        if (d->FirstBlock == NULL) {
            ErrorBox(SYS_Allocate_Memory);
            return -1;
        }

        pb = d->FirstBlock;

        //
        //  Initialize first block
        //

        pb->PrevBlock = pb->NextBlock = NULL;
        pb->LastLineOffset = 0;

        //
        // Initialize first line
        //

        pl = (LPLINEREC)pb->Data;
        pl->PrevLength = 0;
        pl->Length = LHD;
        pl->Status = 0;

        d->NbLines = 1;         // We start with one null line

    } else {

        //
        // Load the file and check if it's a valid one
        //

        if (!LoadFile(doc)) {
            return -1;
        }
    }

    //
    // Initialize current pointers
    //

    d->CurrentBlock = d->FirstBlock;
    d->CurrentLine = 0;
    d->CurrentLineOffset = 0;
    pl = (LPLINEREC)(d->FirstBlock->Data);
    ExpandTabs(&pl);

    //
    // Undo/redo part
    //

    d->undo.h = 0;
    d->redo.h = 0;
    d->playCount = REC_CANNOTUNDO;
    if (g_contGlobalPreferences_WkSp.m_dwUndoResize == 0 || type != DOC_WIN) {
        d->recType = REC_STOPPED;
    } else {
        d->recType = REC_UNDO;
    }
    CreateRecBuf(doc, REC_UNDO, g_contGlobalPreferences_WkSp.m_dwUndoResize);

    if (mode == MODE_RELOAD) {
        RefreshWindowsTitle(doc);
    } else {

        //
        //  Initialize nView part
        //

        views = &Views[nView];
        views->NextView = -1;
        views->X = views->Y = 0;
        views->hwndClient = views->hwndFrame = NULL;
        views->hScrollBar = g_contGlobalPreferences_WkSp.m_bHorzScrollBars;
        views->vScrollBar = g_contGlobalPreferences_WkSp.m_bVertScrollBars;
        views->scrollFactor = 0;
        views->iYTop = -1;

        //
        //  Everything is OK, add title in window menu and return the nView
        //

        d->FirstView = nView;
        views->Doc = doc;
        AddWindowMenuItem(doc, nView);
    }

    //
    // Check syntax if C
    //

    if (d->language == C_LANGUAGE) {
        d->lineTop = 0;
        d->lineBottom = d->NbLines;
        CheckSyntax(doc);
    }

    return nView;
}                                       // OpenDocument()
Example #20
0
File: TMSRpt51.c Project: ems/TMS
BOOL FAR TMSRPT51(TMSRPTPassedDataDef *pPassedData)
{
  REPORTPARMSDef REPORTPARMS;
  PROPOSEDRUNDef PROPOSEDRUN;
  COSTDef COST;
  HFILE hfOutputFile;
  BOOL  bKeepGoing = FALSE;
  BOOL  bRC;
  BOOL  bCoach;
  char  outputString[512];
  char  szDate[16];
  char  szEmployee[16];
  char  szRunNumber[7];
  char  *ptr;
  long  numPieces;
  long  time;
  long  platformTime;
  long  reportTime;
  long  turninTime;
  long  travelTime;
  long  dd,  mm, yyyy;
  int   nI;
  int   nJ;
  int   nK;
  int   rcode2;
  int   seq;
  int   numRosters;

  pPassedData->nReportNumber = 48;
  pPassedData->numDataFiles = 1;
//
//  See what he wants
//
  REPORTPARMS.nReportNumber = pPassedData->nReportNumber;
  REPORTPARMS.DIVISIONSrecordID = m_DivisionRecordID;
  REPORTPARMS.pDivisionList = NULL;
  REPORTPARMS.flags = RPFLAG_DIVISIONS;
  bRC = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_RPTPARMS),
        hWndMain, (DLGPROC)RPTPARMSMsgProc, (LPARAM)&REPORTPARMS);
  if(!bRC)
    return(FALSE);
//
//  Check the list of routes, services, and divisions
//
  if(REPORTPARMS.numDivisions == 0)
    goto deallocate;
//
//  Open the output file
//
  strcpy(tempString, szDatabaseFileName);
  if((ptr = strrchr(tempString, '\\')) != NULL)
    *ptr = '\0';
  strcat(tempString, "\\Fleet-Net Payroll.txt");
  hfOutputFile = _lcreat(tempString, 0);
  if(hfOutputFile == HFILE_ERROR)
  {
    LoadString(hInst, ERROR_202, szFormatString, sizeof(szFormatString));
    sprintf(szarString, szFormatString, tempString);
    MessageBeep(MB_ICONSTOP);
    MessageBox((HWND)NULL, szarString, TMS, MB_ICONSTOP);
    goto deallocate;
  }
//
//  Fire up the status bar
//
  LoadString(hInst, TEXT_117, tempString, TEMPSTRING_LENGTH);
  StatusBarStart(hWndMain, tempString);
//
//  Determine the extent of the status bar
//
  rcode2 = btrieve(B_STAT, TMS_ROSTER, &BSTAT, outputString, 0);
  if(rcode2 != 0 || BSTAT.numRecords == 0)
  {
    TMSError((HWND)NULL, MB_ICONSTOP, ERROR_319, (HANDLE)NULL);
    goto deallocate;
  }
  numRosters = BSTAT.numRecords;
//
//  Get today's date
//
  if(CalendarDate(&dd, &mm, &yyyy) == NO_RECORD)
  {
    goto deallocate;
  }
//
//  Loop through all the divisions
//
  bKeepGoing = TRUE;
  seq = 0;
  for(nI = 0; nI < REPORTPARMS.numDivisions; nI++)
  {
    if(StatusBarAbort())
    {
      goto deallocate;
    }
    DIVISIONSKey0.recordID = REPORTPARMS.pDivisionList[nI];
    btrieve(B_GETEQUAL, TMS_DIVISIONS, &DIVISIONS, &DIVISIONSKey0, 0);
    strncpy(tempString, DIVISIONS.name, DIVISIONS_NAME_LENGTH);
    trim(tempString, DIVISIONS_NAME_LENGTH);
    bCoach = (strstr(tempString, "Coach") > 0);
//
//  Cycle through the roster
//
    ROSTERKey1.DIVISIONSrecordID = DIVISIONS.recordID;
    ROSTERKey1.rosterNumber = NO_RECORD;
    rcode2 = btrieve(B_GETGREATER, TMS_ROSTER, &ROSTER, &ROSTERKey1, 1);
    while(rcode2 == 0 &&
          ROSTER.DIVISIONSrecordID == DIVISIONS.recordID)
    {
      if(StatusBarAbort())
      {
        goto deallocate;
      }
//
//  Get the employee - must be assigned
//
      StatusBar((long)(seq + 1), (long)numRosters);
      if(ROSTER.DRIVERSrecordID != NO_RECORD)
      {
        DRIVERSKey0.recordID = ROSTER.DRIVERSrecordID;
        btrieve(B_GETEQUAL, TMS_DRIVERS, &DRIVERS, &DRIVERSKey0, 0);
        strncpy(szEmployee, DRIVERS.badgeNumber, TMSRPT51_MAX_EMPLOYEENUMBERLENGTH);
        szEmployee[TMSRPT51_MAX_EMPLOYEENUMBERLENGTH] = '\0';
//
//  Loop through the runs
//
        for(nJ = 0; nJ < ROSTER_MAX_DAYS; nJ++)
        {
          if(StatusBarAbort())
          {
            goto deallocate;
          }
          if(ROSTER.WEEK[m_RosterWeek].RUNSrecordIDs[nJ] == NO_RECORD)
          {
            continue;
          }
//
//  Establish "today's" date
//
          strcpy(szDate, CalendarDateWithOffset(dd, mm, yyyy, nJ));
//
//  Get the characteristics of the run
//
          RUNSKey0.recordID = ROSTER.WEEK[m_RosterWeek].RUNSrecordIDs[nJ];
          rcode2 = btrieve(B_GETEQUAL, TMS_RUNS, &RUNS, &RUNSKey0, 0);
          if(rcode2 != 0)
          {
            continue;
          }
          sprintf(szRunNumber, "%6ld", RUNS.runNumber);
          numPieces = GetRunElements(NULL, &RUNS, &PROPOSEDRUN, &COST, TRUE);
          platformTime = 0;
          reportTime = 0;
          turninTime = 0;
          travelTime = 0;
          for(nK = 0; nK < numPieces; nK++)
          {
            platformTime += RUNSVIEW[nK].platformTime;
            reportTime += RUNSVIEW[nK].reportTime;
            turninTime += RUNSVIEW[nK].turninTime;
            travelTime += RUNSVIEW[nK].travelTime;
          }
//
//  Spit out the various components
//
          for(nK = 0; nK < TMSRPT51_NUMCOMPONENTS; nK++)
          {
//
//  Set up the output record
//
            strcpy(outputString, szDate);
            strcat(outputString, "\t");
            strcat(outputString, szEmployee);
            strcat(outputString, "\t");
            switch(nK)
            {
//
//  Platform time
//
              case  TMSRPT51_PLATFORMTIME:
                strcat(outputString, (bCoach ? "PLT" : "PLV"));
                time = platformTime;
                break;
//
//  Makeup time
//
              case  TMSRPT51_MAKEUPTIME:
                strcat(outputString, (bCoach ? "GCS" : "GUV"));
                time = RUNSVIEW[numPieces - 1].makeUpTime;
                break;
//
//  Report time
//
              case  TMSRPT51_REPORTTIME:
                strcat(outputString, (bCoach ? "REC" : "RPV"));
                time = reportTime;
                break;
//
//  Turnin time
//
              case  TMSRPT51_TURNINTIME: 
                strcat(outputString, (bCoach ? "CHT" : "CHV"));
                time = turninTime;
                break;
//
//  Travel time
//
              case  TMSRPT51_TRAVELTIME:
                strcat(outputString, (bCoach ? "TRT" : "TRV"));
                time = travelTime;
                break;
//
//  Overtime
//
              case  TMSRPT51_OVERTIME:
                strcat(outputString, (bCoach ? "OCS" : "OVS"));
                time = (long)(RUNSVIEW[numPieces - 1].overTime / 1.5);
                break;
            }
//
//  Fill in the rest of the record
//
//  Time
//
            sprintf(tempString, "\t%5ld\t", time);
            strcat(outputString, tempString);
//
//  Run number
//
            strcat(outputString, szRunNumber);
            strcat(outputString, "\r\n");
//
//  Write the record
//
            _lwrite(hfOutputFile, outputString, strlen(outputString));
          }
        }
      }
//
//  Get the next roster record
//
      seq++;
      rcode2 = btrieve(B_GETNEXT, TMS_ROSTER, &ROSTER, &ROSTERKey1, 1);
    }
  }  // nI loop on divisions
  bKeepGoing = TRUE;
//
//  Free allocated memory
//
  deallocate:
    TMSHeapFree(REPORTPARMS.pDivisionList);
    StatusBarEnd();
    _lclose(hfOutputFile);
    SetCursor(hCursorArrow);
    if(!bKeepGoing)
      return(FALSE);
//
//  Let him know
//
    strcpy(tempString, "Fleet-Net Payroll.txt was written to:\n");
    strcpy(szarString, szDatabaseFileName);
    if((ptr = strrchr(szarString, '\\')) != NULL)
      *ptr = '\0';
    strcat(tempString, szarString);
    MessageBox(hWndMain, tempString, TMS, MB_OK);
//
//  All done
//
  return(TRUE);
}
Example #21
0
BOOL CMyDateEdit::CheckDate(char nchar,int StartPos,int EndPos)
{	
	CString strText;
	BOOL Leap;	
	int Year,Month,Day;
	strText=GetText();
	Year=atoi(strText);
	Month=atoi(strText.Mid(5,2));
	Day=atoi(strText.Mid(8,2));
	if((Year%4)==0)
	{
		if(((Year%100)==0)&&((Year%400)!=0))
			Leap=FALSE;
		else
			Leap=TRUE;
	}
	else
		Leap=FALSE;
	if(StartPos==4||StartPos==5)
	{
			if(nchar>'1')
			{
				MessageBeep((UINT)-1);
				return FALSE;
			}
			else if(nchar=='1')
			{
				strText=GetText();
				if(strText.GetAt(6)>'2')
				{
					strText.SetAt(6,'2');
					SetText(strText);
					SetSel(StartPos,StartPos);
					return TRUE;
				}
			}
			return TRUE;
	}
	if(StartPos==6)
	{
		strText=GetText();
		if(strText.GetAt(5)=='1')
		{
			if(nchar>'2')
			{
				MessageBeep((UINT)-1);
				return FALSE;
			}
		}
			return TRUE;
	}
	strText=GetText();
	if(StartPos==7||StartPos==8)
	{
		if(Month!=2)
		{
			if(nchar>'3')
				{
					MessageBeep((UINT)-1);
					return FALSE;
				}
				else if(nchar=='3')
				{
					strText=GetText();
					if(strText.GetAt(9)>'0')
					{
						if(Month==4||Month==6||Month==9||Month==11)
						{
							strText.SetAt(9,'0');
						}
						else
							strText.SetAt(9,'1');
						SetText(strText);
						SetSel(StartPos,StartPos);
						return TRUE;
					}			
				}
		}
		else
		{
			if(nchar>'2')
			{
				MessageBeep((UINT)-1);
				return FALSE;
			}
			else if(nchar=='2')
			{			
				strText=GetText();
				if(strText.GetAt(9)>'8')
				{
					if(Leap)
					{
						strText.SetAt(9,'9');
					}
					else
						strText.SetAt(9,'8');
					SetText(strText);
					SetSel(StartPos,StartPos);
					return TRUE;
				}
			}
		}
		return TRUE;				
	}
	if(StartPos==9)
	{
		strText=GetText();
		if(strText.GetAt(8)=='3')
		{
			if(Month==4||Month==6||Month==9||Month==11)
			{
				if(nchar>'0')
				{
					MessageBeep((UINT)-1);
					return FALSE;
				}	
			}
			else if(Month!=2)
			{
				if(nchar>'1')
				{
					MessageBeep((UINT)-1);
					return FALSE;
				}
			}
		}
		else if(strText.GetAt(8)=='2')
		{
			if(Month==2)
			{
				if(Leap)
				{
					if(nchar>'9')
					{
						MessageBeep((UINT)-1);
						return FALSE;
					}
				}
				else
				{
					if(nchar>'8')
					{
						MessageBeep((UINT)-1);
						return FALSE;
					}					
				}
			}
		}
		return TRUE;
	}
	return TRUE;
}
Example #22
0
static void Video_ProcessEvent( HWND hWindow, LPVIDEO lpVideo, int iEventCode, int iEventToPassAlong = 0 )
/***********************************************************************/
{ // Check to see what the video action should be, based on the event code
	SHOTID lShot, lTimerShot;
	long lCount, lTimerCount;
	int iFrames, iSeconds;
	LPSHOT lpShot;

	if ( !(lpShot = Video_GetShotPtr( lpVideo, lpVideo->lCurrentShot )) )
		return;

	iFrames = 0;
	iSeconds = 0;

	switch ( iEventCode )
	{
		case EVENT_END: // the "END" event
			if ( !lpShot->lEndLoop )
			{
				lShot  = lpShot->lEndShot;
				lCount = lpShot->lEndCount;
			}
			else
			{
				// (LOWORD(lLoop) = number of seconds to loop; 0 == forever)
				// (HIWORD(lLoop) = number of frames to loop; 0 == all frames)
				iFrames	 = HIWORD(lpShot->lEndLoop);
				if ( iSeconds = LOWORD(lpShot->lEndLoop) )
				{
					lTimerShot = lpShot->lEndShot;
					lTimerCount = lpShot->lEndCount;
				}
				lShot  = lpShot->lShotID;
				lCount = 1;
			}
			break;
		case EVENT_LEFT: // the "LEFT" event
			if ( lpShot->bLeftIsSubShot )
			{
				if ( !(lpShot = Video_FindSubShot( lpVideo,
					lpShot->lLeftShot, lpShot->lLeftCount, 0 )) )
						return;
			}
			lShot  = lpShot->lLeftShot;
			lCount = lpShot->lLeftCount;
			break;
		case EVENT_UP: // the "UP" event
			if ( lpShot->bUpIsSubShot )
			{
				if ( !(lpShot = Video_FindSubShot( lpVideo,
					lpShot->lUpShot, lpShot->lUpCount, 0 )) )
						return;
			}
			lShot  = lpShot->lUpShot;
			lCount = lpShot->lUpCount;
			break;
		case EVENT_RIGHT: // the "RIGHT" event
			if ( lpShot->bRightIsSubShot )
			{
				if ( !(lpShot = Video_FindSubShot( lpVideo,
					lpShot->lRightShot, lpShot->lRightCount, 0 )) )
						return;
			}
			lShot  = lpShot->lRightShot;
			lCount = lpShot->lRightCount;
			break;
		case EVENT_DOWN: // the "DOWN" event
			if ( lpShot->bDownIsSubShot )
			{
				if ( !(lpShot = Video_FindSubShot( lpVideo,
					lpShot->lDownShot, lpShot->lDownCount, 0 )) )
						return;
			}
			lShot  = lpShot->lDownShot;
			lCount = lpShot->lDownCount;
			break;
		case EVENT_HOME: // the "HOME" event
			if ( lpShot->bHomeIsSubShot )
			{
				if ( !(lpShot = Video_FindSubShot( lpVideo,
					lpShot->lHomeShot, lpShot->lHomeCount, 0 )) )
						return;
			}
			lShot  = lpShot->lHomeShot;
			lCount = lpShot->lHomeCount;
			break;
		default:
			return;
	}

	if ( !lShot )
	{
		MessageBeep(0);
		return;
	}

	if ( iEventToPassAlong )
		iEventCode = iEventToPassAlong;
	if (lShot == SHOT_STOP)
		// send a NULL for lppShot to indicate stop
		FORWARD_WM_COMMAND( GetParent(hWindow), GET_WINDOW_ID(hWindow),
			0, 0, SendMessage );
	else
		Video_GotoShot( hWindow, lpVideo, lShot, lCount, iFrames, iEventCode );
	if ( iSeconds ) // if a timer (in seconds) is specified...
		Video_SetJumpTimer( hWindow, iSeconds, lTimerShot, lTimerCount );
}
Example #23
0
void flashWindowAndBeep ()
{
	MessageBeep (0xFFFFFFFF);
}
Example #24
0
void Ring_Bell( void )
{
    MessageBeep( 0 );
}
Example #25
0
void WINAPI TimeServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) 
{
#ifdef _WIN64
   unsigned __int64 dwCompKey  = CK_SERVICECONTROL;
#else
   DWORD dwCompKey  = CK_SERVICECONTROL;
#endif
   DWORD fdwControl = SERVICE_CONTROL_RUN;
   DWORD dwBytesTransferred;
   OVERLAPPED *po;
   SERVICE_STATUS ss;
   SERVICE_STATUS_HANDLE hSS;
   BOOL bPasswordCompileEmbedded = 0;

// We must get the private password for connecting to this machine.
// The password can be compiled into the server any of the following ways......


//  1 way - the easiest way, just uncomment and put any value between the quotes
//  then remove the code between --Load External Password Begin & End-- below
//  ***** example of very simple integrated password ********
//  GString strPassword("Password");
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//  Another way - a most secure way to embed the password.
//  ***** example of integrated password ********
//  GString strPassword;
//	MakePassword(strPassword);    // Go read the MakePassword() routine above.
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//              OR

// The password can be retrieved from an external disk location.
// Passwords can be obtained from disk in two different ways.
// Either in a registry key matching the (probably renamed) 
// executable file that is this server, OR by loading a 
// predefined file name at a predefined location. 
// This file must be present while starting the server, but can be
// removed once this process has fully started.


//  --Load External Password Begin--
GString strPassword;
GString strPort;
GString strRoot;

if (!bPasswordCompileEmbedded)
{
	GString strThisEXEName(GetThisEXEName());
	GString strStartupKey;

	// use our runtime image name as the registry key
	char buf[512];
	long lSize = sizeof(buf);
	if (RegQueryValue(HKEY_CLASSES_ROOT,(const char *)strThisEXEName,buf,&lSize) == ERROR_SUCCESS)
	{
		// uudecode the startup key
		BUFFER b;
		BufferInit(&b);
		unsigned int nDecoded;
		uudecode(buf, &b, &nDecoded, false);
		strStartupKey.write((const char *)b.pBuf,nDecoded);
		BufferTerminate(&b);
	}

	GString strStartupData;
	if (strStartupKey.Length())
	{
		// look for a file in the root of the file system (c:\)
		// with the same name as this .exe
		GString strFile("c:\\");
		strFile += strThisEXEName;


		// load the crypted disk file into clear text memory
		char *pDest;
		int nDestLen;
		GString strErrorOut;
		if (FileDecryptToMemory(strStartupKey, strFile, &pDest, &nDestLen, strErrorOut))
		{
			// parse into the profile data structures
			pDest[7 + nDestLen] = 0; // null terminate it
			strStartupData.write(&pDest[7], nDestLen + 1); // and cap the GString 
		}
		else
		{
			// if the file was not in the root of the file system
			// see if there is an environment setting directing
			// this server to look for the file in another location
			// The variable name is dynamic, matching this .exe name
			// and the environment variable value must be a fully
			// qualified path and file name to the startup file.
			if (getenv(strThisEXEName))
			{
				if (FileDecryptToMemory(strStartupKey, getenv(strThisEXEName), &pDest, &nDestLen, strErrorOut))
				{
					// parse into the profile data structures
					strStartupData.write(&pDest[7], nDestLen-7);
				}
			}
		}

		// parse stored settings in startup file to startup variables
		if (strStartupData.Length())
		{
			GStringList lstOptions("&&",strStartupData);
			GStringIterator it(&lstOptions);

			if (it()) strPassword = it++;
			if (it()) strRoot = it++; // currently not used
			if (it()) strPort = it++;
		}
	}
}

//  --Load External Password End--

	GString strFile;
	GString strConfigFileDefault;
	GString strErrorOut;
	int bSetStartupFile = 0;

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS); // = 1 point above normal
#endif


   // Create the completion port and save its handle in a global
   // variable so that the Handler function can access it.
   g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, CK_PIPE, 0);

   // Give SCM the address of this service's Handler
   // NOTE: hSS does not have to be closed.
   hSS = RegisterServiceCtrlHandler((const char *)strServerName, TimeServiceHandler);

   // Do what the service should do.
   // Initialize the members that never change
   ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS; 
   ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | 
      SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN;

   do {
      switch (dwCompKey) {
      case CK_SERVICECONTROL:
         // We got a new control code
         ss.dwWin32ExitCode = NO_ERROR; 
         ss.dwServiceSpecificExitCode = 0; 
         ss.dwCheckPoint = 0; 
         ss.dwWaitHint = 0;

         if (fdwControl == SERVICE_CONTROL_INTERROGATE) {
            SetServiceStatus(hSS, &ss);
            break;
         }

         // Determine which PENDING state to return
         if (dwSrvCtrlToPend[fdwControl] != 0) {
            ss.dwCurrentState = dwSrvCtrlToPend[fdwControl]; 
            ss.dwCheckPoint = 0;
            ss.dwWaitHint = 500;   // half a second
            SetServiceStatus(hSS, &ss);
         }

         switch (fdwControl) {
            case SERVICE_CONTROL_RUN:
            case SERVICE_CONTROL_CONTINUE:
				try
				{
					if (strRoot.Length() && strPort.Length())
					{
						GString strCfgData;
						strCfgData.Format(pzBoundStartupConfig,(const char *)strRoot,(const char *)strPort);
						SetProfile(new GProfile((const char *)strCfgData, (int)strCfgData.Length(), 0));

						if (!server_start())
						{
							ss.dwCurrentState = SERVICE_STOPPED; 
							ss.dwCheckPoint = ss.dwWaitHint = 0;
							SetServiceStatus(hSS, &ss);
							break;
						}
					}
					else
					{
						// No password compiled in - and no valid startup file found
						for(int i=0; i<3;i++)
						{
							// three beeps
							MessageBeep(0);
							Sleep(1000);
						}
						ss.dwCurrentState = SERVICE_STOPPED; 
						ss.dwCheckPoint = ss.dwWaitHint = 0;
						SetServiceStatus(hSS, &ss);
						break;
					}
				}
				catch ( GException &)
				{
					ss.dwCurrentState = SERVICE_STOPPED; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
					break;
				}



				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;

            case SERVICE_CONTROL_PAUSE:
            case SERVICE_CONTROL_STOP:
            case SERVICE_CONTROL_SHUTDOWN:
                server_stop();
				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;
         }

         // Determine which complete state to return
         break;

      }

      if (ss.dwCurrentState != SERVICE_STOPPED) {
         // Sleep until a control code comes in or a client connects
         GetQueuedCompletionStatus(g_hIOCP, &dwBytesTransferred,
            &dwCompKey, &po, INFINITE);
         fdwControl = dwBytesTransferred;
      }
   } while (ss.dwCurrentState != SERVICE_STOPPED);

   // Cleanup and stop this service
   CloseHandle(g_hIOCP);   
}
int CHyperlink::WndProc(HWND hwnd,WORD wMsg,WPARAM wParam,LPARAM lParam)
{
	CHyperlink *hl = (CHyperlink*)GetWindowLong(hwnd, GWL_USERDATA);

	switch (wMsg)  
	{
	case WM_LBUTTONDOWN:
		if (((UINT)::ShellExecute(NULL, _T("open"), hl->m_Url, NULL, NULL, SW_SHOWNORMAL)) <= 32){
			MessageBeep(0);
		}
		break;
	case WM_MOUSEMOVE:

		break;
	case WM_PAINT:
		{
			HDC hDC; PAINTSTRUCT ps;
			hDC = ::BeginPaint(hwnd, &ps);
			if (hl == NULL)
				return 0;

			RECT rect;
			::GetClientRect(hwnd, &rect);

			/*HFONT font = ::CreateFont( 16, //height
				7, //average char width
				0, //angle of escapement
				0, //base-line orientation angle
				FW_NORMAL,	//font weight
				FALSE,		//italic
				TRUE,		//underline
				FALSE,		//strikeout
				ANSI_CHARSET,			//charset identifier
				OUT_DEFAULT_PRECIS,		//ouput precision
				CLIP_DEFAULT_PRECIS,	//clipping precision
				DEFAULT_QUALITY,	//output quality
				DEFAULT_PITCH,			//pitch and family
				"Tahoma");*/
			HFONT font =(HFONT)::SendMessage(hl->hParent, WM_GETFONT, 0, 0);

			::SelectObject(hDC, font);
			::SetTextColor(hDC, RGB(0,0,200));
			::SetBkMode(hDC, TRANSPARENT);
			char* sz=hl->m_UrlVisible[0]!=0?hl->m_UrlVisible:hl->m_Url;
			::DrawText(hDC, sz, strlen(sz), &rect, DT_VCENTER | DT_CENTER | DT_SINGLELINE);
			//::DeleteObject(font);

			::EndPaint(hwnd, &ps);

			return TRUE;
		}
	case WM_SETCURSOR:
		{
			if (CHyperlink::handcursor)
				::SetCursor(CHyperlink::handcursor);
		}
	default:
		DefWindowProc(hwnd, wMsg, wParam, lParam);
	}

	return TRUE;
}
Example #27
0
BOOL RtfNotify(HWND hDlg, NMHDR* nmhdr)
{
    static BOOL FindFirst = TRUE;
#define BUFF_LEN 2048
    static TCHAR FindWhat[BUFF_LEN];

    if (nmhdr->code == EN_PROTECTED && !PuttingChar) {
        //block
        ENPROTECTED* enp = (ENPROTECTED*) nmhdr;
        CHARRANGE cr;
        INT TextLen = RtfWindowTextLength();
        BOOL Reset = FALSE, Disallow = FALSE;


        // just let it go ahead anyway
        if (enp->msg == WM_COPY)
            return FALSE;

        // they hit backspace
        if (enp->wParam == VK_BACK) {
            if ((DWORD) enp->chrg.cpMin < StartOfInput ||
                    ((DWORD) enp->chrg.cpMin == StartOfInput &&
                     enp->chrg.cpMin == enp->chrg.cpMax)) {
                Reset = TRUE;
                Disallow = TRUE;
            }
        } else if ((DWORD) enp->chrg.cpMin < StartOfInput) {
            Reset = TRUE;
            Disallow = (enp->wParam == VK_DELETE);
        }

        if (Reset) {
            cr.cpMin = TextLen;
            cr.cpMax = cr.cpMin;
            SendMessage(hWndRtf, EM_EXSETSEL, 0, (LPARAM) &cr);
        }

        // we don't want to paste rich text, as that makes it look weird
        // so send only plain text paste commands
        if ((enp->msg == WM_PASTE) && !Disallow) {
            LPTSTR Buffer = NULL;
            Disallow = TRUE;
#if defined _UNICODE
#define CLIP_FORMAT  CF_UNICODETEXT
#else
#define CLIP_FORMAT  CF_TEXT
#endif
            if (IsClipboardFormatAvailable(CLIP_FORMAT) &&
                    OpenClipboard(hWndMain)) {
                HGLOBAL hGlb;
                LPTSTR str;

                if ((hGlb = GetClipboardData(CLIP_FORMAT)) != NULL &&
                        (str = GlobalLock(hGlb)) != NULL) {
                    Buffer = StringDup(str);
                    GlobalUnlock(hGlb);
                }
                CloseClipboard();
            }

            if (Buffer != NULL) {
                // strip trailing new line characters
                INT i;
                for (i = StringLen(Buffer)-1;
                        i >= 0 && (Buffer[i] == TEXT('\r') || Buffer[i] == TEXT('\n'));
                        i--)
                    Buffer[i] = 0;

#if defined _UNICODE
                {
                    SETTEXTEX stt;

                    stt.codepage = CP_UNICODE;
                    stt.flags = ST_SELECTION;
                    SendMessage(hWndRtf,EM_SETTEXTEX,(WPARAM)&stt,(LPARAM)Buffer);
                }
#else
                SendMessage(hWndRtf, EM_REPLACESEL, FALSE, (LPARAM)Buffer);
#endif


                free(Buffer);
            }
        }

        return (Disallow ? TRUE : FALSE);
    } else if (nmhdr->code == EN_LINK) {
        // should really fire on up
        // but that screws up the cursor position

        ENLINK* enl = (ENLINK*) nmhdr;
        if (enl->msg == WM_LBUTTONDOWN) {
            TEXTRANGE tr;
            TCHAR Buffer[1000];
            tr.lpstrText = Buffer;
            tr.chrg.cpMin = enl->chrg.cpMin;
            tr.chrg.cpMax = enl->chrg.cpMax;

            SendMessage(hWndRtf, EM_GETTEXTRANGE, 0, (LPARAM) &tr);
            ExecuteFile(Buffer);

            return TRUE;
        }
    } else if (nmhdr->code == EN_MSGFILTER) {
        MSGFILTER* mf = (MSGFILTER*) nmhdr;
#if 0
        //if (mf->msg == WM_CHAR && Running) {
        if (mf->msg == WM_CHAR && 0) {
            WinGHCiReceiveC((TCHAR)mf->wParam == TEXT('\r') ? TEXT('\n') : mf->wParam);
            SetWindowLong(hDlg, DWL_MSGRESULT, 1);
            return FALSE;
        } //else if (Running && mf->msg == WM_KEYDOWN) {
        else if (0) {
            SHORT n = GetKeyState(VK_CONTROL);
            BOOL Control = (n & (1 << 16));
            if(((CHAR)(mf->wParam) ==(CHAR)TEXT('C')) && Control)
                AbortExecution();
            else
                SetWindowLong(hDlg, DWL_MSGRESULT, 1);
            return FALSE;
        } //else if (mf->msg == WM_KEYDOWN && !Running) {
        else
#endif


            if (mf->msg == WM_CHAR) {

                if (mf->wParam == VK_TAB) {

                    INT pos;

                    if(FindFirst) {
                        RtfWindowGetCommand(FindWhat,BUFF_LEN);
                        pos = FindFirstHistory(FindWhat);
                        FindFirst = FALSE;
                    } else
                        pos = FindNextHistory();

                    if(pos>=0)
                        RtfWindowSetCommand(GoToHistory(pos));
                    else
                        MessageBeep((UINT)-1);

                    return TRUE;

                } else {
                    // any other key resets search
                    FindFirst = TRUE;

                    if (mf->wParam == VK_ESCAPE) {

                        //Clear current command
                        RtfWindowSetCommand(TEXT(""));
                        // Go to last item in history
                        AddHistory(TEXT(""));
                        return TRUE;
                    } else {
                        return FALSE;
                    }
                }


            } else if (mf->msg == WM_KEYDOWN) {
                BOOL History = (mf->wParam == VK_UP || mf->wParam == VK_DOWN);
                SHORT n = GetKeyState(VK_CONTROL);
                BOOL Control = (n & (1 << 16));

                if(((CHAR)(mf->wParam) ==(CHAR)TEXT('C')) && Control) {
                    if(RtfWindowCanCutCopy() && DROPEFFECT_COPY)
                        RtfWindowClipboard(WM_COPY);
                    else
                        AbortExecution();
                } else if (History && (mf->lParam & (1 << 24))) {
                    CHARRANGE cr;
                    SendMessage(hWndRtf, EM_EXGETSEL, 0, (LPARAM) &cr);
                    if ((DWORD) cr.cpMin >= StartOfInput) {
                        RtfWindowRelativeHistory(mf->wParam == VK_UP ? -1 : +1);
                        return TRUE;
                    }
                } else if (mf->wParam == VK_RETURN) {
#define BUFF_LEN 2048
                    TCHAR Buffer[BUFF_LEN];


                    RtfWindowGetCommand(Buffer,BUFF_LEN);

                    if(Running) {
                        if(!(mf->lParam & (1<<30))) //avoid repetition
                            FireCommandExt(Buffer,FALSE,TRUE,FALSE,FALSE);
                    }
                    else
                        //if(!(mf->lParam & (1<<30)))
                        FireAsyncCommand(Buffer);
                    return TRUE;
                } else if (mf->wParam == VK_HOME) {
                    CHARRANGE cr;
                    SendMessage(hWndRtf, EM_EXGETSEL, 0, (LPARAM) &cr);
                    if ((DWORD) cr.cpMin >= StartOfInput) {
                        SHORT n = GetKeyState(VK_SHIFT);
                        BOOL Shift = (n & (1 << 16));

                        cr.cpMin = StartOfInput;
                        cr.cpMax = (Shift ? cr.cpMax : StartOfInput);
                        SendMessage(hWndRtf, EM_EXSETSEL, 0, (LPARAM) &cr);
                        return TRUE;
                    }
                }
            }
    } else if (nmhdr->code == EN_SELCHANGE) {
        EnableButtons();
        return FALSE;
    }

    return FALSE;
}
Example #28
0
ATMO_BOOL CDmxConfigDialog::ExecuteCommand(HWND hControl,int wmId, int wmEvent) {

    HWND control;
    char buf[500];
    char channels[500];
    int  rgb;
    int chc;

    switch(wmId) {
        case IDOK: {
           control = getDlgItem(IDC_EDT_DMX_BASE);
           Edit_GetText(control, channels, sizeof(channels));

           control = getDlgItem(IDC_EDT_DMX_RGB);
           Edit_GetText(control, buf, sizeof(buf));
           rgb = atoi(buf);
           
           if((rgb<1) || (rgb>84))  {
              MessageBox(m_hDialog,"Anzahl RGB liegt ausserhalb des gültigen Bereich 1..84","Fehler",MB_ICONERROR);
              break;
           }

           chc = IsValidDmxStartString(channels, m_MaxChannels-3);
           if((chc == -2) || (chc == -3)) {
              sprintf(buf,"Ungültiger DMX Kanal gefunden, nicht im Bereich 0..%d",m_MaxChannels-3);
              MessageBox(m_hDialog, buf, "Fehler",MB_ICONERROR);
              break;
           }
           if((chc == -1) || (chc == 0)) {
              MessageBox(m_hDialog , "Mindestens ein Startkanal muss angegeben werden!" , "Fehler" , MB_ICONERROR );
              break;
           }
           if(chc == -4) {
              MessageBox(m_hDialog , "Ungültiges Zeichen in der Startkanalliste gefunden.\nEs sind nur Ziffern [0..9], Trenner [,;] und Leerzeichen erlaubt." , "Fehler" , MB_ICONERROR );
              break;
           }

           if(chc < rgb) {
              MessageBox(m_hDialog, "Es wurden weniger Startkanäle angegeben als RGB Kanäle, die fehlende Startkanäle werden auf Basis des letzten Kanals ermittelt.", "Hinweis", MB_ICONINFORMATION);
           }

           int comportSel = ComboBox_GetCurSel(getDlgItem(IDC_COMPORT));
           m_pConfig->setComport(comportSel + 1);

           m_pConfig->setDMX_BaudrateIndex( ComboBox_GetCurSel(getDlgItem(IDC_BAUDRATE)) );

           m_pConfig->setDMX_BaseChannels( channels );
           m_pConfig->setDMX_RGB_Channels( rgb );

           EndDialog(this->m_hDialog, wmId);
           break;
        }

        case IDCANCEL: {
            // m_pBackupConfig --> wieder herstellen...
           EndDialog(this->m_hDialog, wmId);
           break;
        }

        case IDC_EDT_DMX_RGB: {
            if(wmEvent == EN_CHANGE) {
                char buffer[20];
                if(Edit_GetText(hControl,buffer,sizeof(buffer))>0) {
                    int value = atoi(buffer);
                    if((value<1) || (value>64)) 
                        MessageBeep(MB_ICONEXCLAMATION);
                }
            }
            break;
        }

        case IDC_EDT_DMX_BASE: {
            if(wmEvent == EN_CHANGE) {
                if(Edit_GetText(hControl,channels,sizeof(channels))>0) {
                   chc = IsValidDmxStartString(channels, m_MaxChannels-3);
                   if(chc < 0)
                      MessageBeep(MB_ICONEXCLAMATION);
                }
            }
            break;
        }


       default:
           return ATMO_FALSE;

    }

    return ATMO_TRUE;
}
Example #29
0
VOID CExpandImageDlg::DoExpandControls(ITEMID id, UINT codeNotify )
/***********************************************************************/
{
BOOL Bool;
WORD idUnits;
LFIXED Right, Bottom;

switch( id )
    {
	case IDC_PREF_UNITS:
	if ( !(idUnits = HandleCombo( GetSafeHwnd(), id, codeNotify )) )
		break;
	Control.Units = idUnits;
	SetUnitInfo((UNIT_TYPE)(Control.Units-IDC_PREF_UNITINCHES), Control.UnitRes, Control.Points);
	CheckComboItem(GetSafeHwnd(), IDC_PREF_UNITS, IDC_PREF_UNITFIRST,
		IDC_PREF_UNITLAST, Control.Units);
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_WIDTH, m_Width, YES );
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_HEIGHT, m_Height, YES );
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDLEFT, m_Left, YES );
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDRIGHT, m_Width-m_OrigWidth-m_Left, YES );
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDTOP, m_Top, YES );
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDBOTTOM, m_Height-m_OrigHeight-m_Top, YES );
	SetUnitLabels(GetSafeHwnd());
	break;

   case IDC_HEIGHT:
	if (codeNotify == EN_KILLFOCUS)
		{
		if (m_Height < m_OrigHeight)
			{
			m_Height = m_OrigHeight;
			m_Top = 0;
			MessageBeep(0);
			SetDlgItemSpinFixed( GetSafeHwnd(), IDC_HEIGHT, m_Height, YES );
			ControlEnable(GetSafeHwnd(), IDOK, 	(m_Height > m_OrigHeight) ||
								(m_OrigHeight > m_OrigWidth));
			}
		else
			break;
		}
	else
		{
		if ( ::GetFocus() != ::GetDlgItem( GetSafeHwnd(), id ) )
			break;
		if ( codeNotify != EN_CHANGE )
			break;
		m_Height = GetDlgItemSpinFixed( GetSafeHwnd(), IDC_HEIGHT, &Bool, YES);
		if (m_Height < m_OrigHeight)
			{
			ControlEnable(GetSafeHwnd(), IDOK, FALSE);
			::SetFocus(::GetDlgItem( GetSafeHwnd(),id));
			break;
			}
		}
	if ((m_OrigHeight + m_Top) > m_Height)
		m_Top = m_Height - m_OrigHeight;
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDTOP, m_Top, YES );
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDBOTTOM,m_Height - m_OrigHeight- m_Top,YES );
	ImageMemory( GetSafeHwnd(), IDC_MEMORY, m_Width, m_Height, m_Resolution,
				 m_Depth );
	ControlEnable(GetSafeHwnd(), IDOK, 	(m_Height > m_OrigHeight) || (m_Width > m_OrigWidth));
	break;

    case IDC_WIDTH:
	if (codeNotify == EN_KILLFOCUS)
		{
		if (m_Width < m_OrigWidth)
			{
			m_Width = m_OrigWidth;
			m_Left = 0;
			MessageBeep(0);
			SetDlgItemSpinFixed( GetSafeHwnd(), IDC_WIDTH, m_Width, YES );
			ControlEnable(GetSafeHwnd(), IDOK, 	(m_Height > m_OrigHeight)
																 ||(m_Width > m_OrigWidth));
			}
		else
			break;
		}
	else
		{
		if ( ::GetFocus() != ::GetDlgItem( GetSafeHwnd(), id ) )
			break;
		if ( codeNotify != EN_CHANGE )
			break;
		m_Width = GetDlgItemSpinFixed( GetSafeHwnd(), IDC_WIDTH, &Bool, YES );
		if (m_Width < m_OrigWidth)
			{
			ControlEnable(GetSafeHwnd(), IDOK, FALSE);
			::SetFocus(::GetDlgItem(GetSafeHwnd(),id));
			break;
			}
		}
	if (m_OrigWidth + m_Left > m_Width)
		m_Left = m_Width - m_OrigWidth;
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDLEFT, m_Left, YES );
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_EXPANDRIGHT, m_Width - m_OrigWidth - m_Left, YES );
	ImageMemory( GetSafeHwnd(), IDC_MEMORY, m_Width, m_Height, m_Resolution, m_Depth );
	ControlEnable(GetSafeHwnd(), IDOK, 	(m_Height > m_OrigHeight) ||(m_Width > m_OrigWidth));
	break;

	case IDC_EXPANDLEFT:
	if ( GetFocus() != GetDlgItem(id ) )
		break;
	if ( codeNotify != EN_CHANGE )
		break;
	Right = m_Width - m_OrigWidth - m_Left;
	m_Left = GetDlgItemSpinFixed(GetSafeHwnd(), id, &Bool, YES);
	m_Width = (m_OrigWidth + m_Left + Right);
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_WIDTH, m_Width, YES );
	ImageMemory( GetSafeHwnd(), IDC_MEMORY, m_Width, m_Height, m_Resolution,m_Depth );
	ControlEnable(GetSafeHwnd(), IDOK, (m_Height > m_OrigHeight) ||(m_Width > m_OrigWidth));
	break;

	case IDC_EXPANDRIGHT:
	if ( GetFocus() != GetDlgItem( id ) )
		break;
	if ( codeNotify != EN_CHANGE )
		break;
	Right = GetDlgItemSpinFixed(GetSafeHwnd(), id, &Bool, YES);
	m_Width = m_OrigWidth + m_Left+ Right;
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_WIDTH, m_Width, YES );
	ImageMemory( GetSafeHwnd(), IDC_MEMORY, m_Width, m_Height, m_Resolution,m_Depth );
	ControlEnable(GetSafeHwnd(), IDOK, 	(m_Height > m_OrigHeight) ||(m_Width > m_OrigWidth));
	break;

	case IDC_EXPANDTOP:
	if ( GetFocus() != GetDlgItem( id ) )
		break;
	if ( codeNotify != EN_CHANGE )
		break;
	Bottom = m_Height- m_OrigHeight - m_Top;
	m_Top = GetDlgItemSpinFixed(GetSafeHwnd(), id, &Bool, YES);
	m_Height = m_OrigHeight + m_Top + Bottom;
	SetDlgItemSpinFixed(GetSafeHwnd(), IDC_HEIGHT, m_Height, YES );
	ImageMemory( GetSafeHwnd(), IDC_MEMORY, m_Width, m_Height, m_Resolution,m_Depth );
	ControlEnable(GetSafeHwnd(), IDOK, 	(m_Height > m_OrigHeight) ||(m_Width > m_OrigWidth));
	break;

	case IDC_EXPANDBOTTOM:
	if ( GetFocus() != GetDlgItem(id) )
		break;
	if ( codeNotify != EN_CHANGE )
		break;
	Bottom = GetDlgItemSpinFixed(GetSafeHwnd(), id, &Bool, YES);
	m_Height = m_OrigHeight + m_Top + Bottom;
	SetDlgItemSpinFixed( GetSafeHwnd(), IDC_HEIGHT, m_Height, YES );
	ImageMemory( GetSafeHwnd(), IDC_MEMORY, m_Width, m_Height, m_Resolution,m_Depth );
	ControlEnable(GetSafeHwnd(), IDOK, 	(m_Height > m_OrigHeight) ||(m_Width > m_OrigWidth));
	break;

    default:
	break;
    }
}
Example #30
0
INT_PTR
CALLBACK
DlgProc_TransportLayer(
    HWND hwndDlg,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
    )
/*++
Routine Description:
    This routine contains the window procedure for transport dll selection
    dialog

    Editing of transport layers is not allowed when doing kernel debugging or
    the debugging of kernel and user mode dumps.

Arguments:
Return Value:
    See docs for "DialogBox"
--*/
{
    // fKernelDebugger cover kernel and kernel dumps
    BOOL bTL_EditingAllowed = !g_contWorkspace_WkSp.m_bKernelDebugger &&
                              !g_contWorkspace_WkSp.m_bUserCrashDump;

    static DWORD HelpArray[]=
    {
       IDC_LIST1, IDH_TRANSPORT,
       IDC_STEXT_SELECT, IDH_TLSELECT,
       IDC_BUT_SELECT, IDH_TLSELECT,
       IDC_BUT_ADD, IDH_TLADD,
       IDC_BUT_EDIT, IDH_TLEDIT,
       IDC_BUT_DELETE, IDH_TLDEL,
       0, 0
    };

    static DWORD NOEDIT_HelpArray[]=
    {
       IDC_LIST1, IDH_TRANSPORT_DISABLED,
       IDC_STEXT_SELECT, IDH_TRANSPORT_DISABLED,
       IDC_BUT_SELECT, IDH_TRANSPORT_DISABLED,
       IDC_BUT_ADD, IDH_TRANSPORT_DISABLED,
       IDC_BUT_EDIT, IDH_TRANSPORT_DISABLED,
       IDC_BUT_DELETE, IDH_TRANSPORT_DISABLED,
       0, 0
    };

    PDWORD pdwHelpArray = bTL_EditingAllowed ? HelpArray : NOEDIT_HelpArray;

    HWND hwndList = GetDlgItem(hwndDlg, IDC_LIST1);
    HWND hwndEdit = GetDlgItem(hwndDlg, IDC_BUT_EDIT);
    HWND hwndDelete = GetDlgItem(hwndDlg, IDC_BUT_DELETE);
    HWND hwndSelect = GetDlgItem(hwndDlg, IDC_BUT_SELECT);

    switch (uMsg) {
        
    default:
        return FALSE;

    case WM_HELP:
        WinHelp((HWND)((LPHELPINFO) lParam)->hItemHandle,
                "windbg.hlp",
                HELP_WM_HELP,
                (ULONG_PTR) pdwHelpArray );
        return TRUE;

    case WM_CONTEXTMENU:
        WinHelp((HWND) wParam,
                "windbg.hlp",
                HELP_CONTEXTMENU,
                (ULONG_PTR) pdwHelpArray );
        return TRUE;

    case WM_INITDIALOG:
        if (!bTL_EditingAllowed) {
            EnableWindow(GetDlgItem(hwndDlg, IDC_LIST1), FALSE);
            EnableWindow(GetDlgItem(hwndDlg, IDC_BUT_SELECT), FALSE);
            EnableWindow(GetDlgItem(hwndDlg, IDC_STEXT_SELECT), FALSE);
            EnableWindow(GetDlgItem(hwndDlg, IDC_BUT_ADD), FALSE);
            EnableWindow(GetDlgItem(hwndDlg, IDC_BUT_EDIT), FALSE);
            EnableWindow(GetDlgItem(hwndDlg, IDC_BUT_DELETE), FALSE);
        }

        // This section sets up the dialog and initializes the fields.        
        
        // Make a copy of the registry, and screw with the copy.
        Assert(NULL == g_pCCopyOf_All_TLs_WrkSpc);
        g_pCCopyOf_All_TLs_WrkSpc = new CAll_TLs_WKSP();
        
        g_pCCopyOf_All_TLs_WrkSpc->m_bDynamicList = TRUE;
        g_pCCopyOf_All_TLs_WrkSpc->Duplicate(g_dynacontAll_TLs_WkSp);

        Assert(NULL == pszSelectedTL);
        Assert(g_contWorkspace_WkSp.m_pszSelectedTL);
        pszSelectedTL = _strdup(g_contWorkspace_WkSp.m_pszSelectedTL);
        
        //
        // Set the extended style
        //
        ListView_SetExtendedListViewStyle(hwndList, LVS_EX_FULLROWSELECT);       
        
        ///////////////////////////////////////////
        // Setup the column header for the list view
        ///////////////////////////////////////////
        
        //
        // Add Column headers
        //            
        {
            char            szColHdr[MAX_MSG_TXT];
            LV_COLUMN       lvc;
            
            // Initialize the LV_COLUMN structure. 
            lvc.mask = lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
            lvc.fmt = LVCFMT_LEFT;
            lvc.cx = 100;
            lvc.pszText = szColHdr;  
            
            // Add the 1st column hdr
            Dbg(LoadString(g_hInst, SYS_TRANSPORT_LAYER_COL_HDR1, 
                szColHdr, sizeof(szColHdr)));
            lvc.iSubItem = 0;
            Dbg(ListView_InsertColumn(hwndList, lvc.iSubItem, &lvc) != -1);
            
            // Add the 2nd col hdr
            Dbg(LoadString(g_hInst, SYS_TRANSPORT_LAYER_COL_HDR2, 
                szColHdr, sizeof(szColHdr)));
            lvc.iSubItem = 1;
            Dbg(ListView_InsertColumn(hwndList, lvc.iSubItem, &lvc) != -1);
            
            // Add the 3rd col hdr
            Dbg(LoadString(g_hInst, SYS_TRANSPORT_LAYER_COL_HDR3, 
                szColHdr, sizeof(szColHdr)));
            lvc.iSubItem = 2;
            Dbg(ListView_InsertColumn(hwndList, lvc.iSubItem, &lvc) != -1);
            
            // Add the 4th col hdr
            Dbg(LoadString(g_hInst, SYS_TRANSPORT_LAYER_COL_HDR4, 
                szColHdr, sizeof(szColHdr)));
            lvc.iSubItem = 3;
            Dbg(ListView_InsertColumn(hwndList, lvc.iSubItem, &lvc) != -1);
        }            
        
        //
        // Add the actual data to the list
        //
        AddDataToList(hwndDlg, g_pCCopyOf_All_TLs_WrkSpc);
        return TRUE;

    case WM_COMMAND:
        if (bTL_EditingAllowed) {
            WORD wNotifyCode = HIWORD(wParam);  // notification code 
            WORD wID = LOWORD(wParam);          // item, control, or accelerator identifier 
            HWND hwndCtl = (HWND) lParam;       // handle of control 
            
            switch (wID) {
                
            default:
                return FALSE;
                
            case IDC_BUT_RESET:
                {
                    // Reset it to the original contents
                    CAll_TLs_WKSP * pAll_TLs_Tmp = new CAll_TLs_WKSP();
                    
                    if (pAll_TLs_Tmp) {
                        g_pCCopyOf_All_TLs_WrkSpc->Duplicate(*pAll_TLs_Tmp);
                        
                        // Data has been changed, repopulate the list.
                        AddDataToList(hwndDlg, g_pCCopyOf_All_TLs_WrkSpc);
                        
                        BOOL bEmpty = ListView_GetItemCount(hwndList) <= 0;
                        EnableWindow(hwndEdit, !bEmpty);
                        EnableWindow(hwndDelete, !bEmpty);
                        EnableWindow(hwndSelect, !bEmpty);
                        
                        delete pAll_TLs_Tmp;
                    }
                }
                return FALSE;
                
            case IDC_BUT_SELECT:
                if (BN_CLICKED == wNotifyCode) {                   
                    int nCurSel = ListView_GetNextItem(hwndList, -1, LVNI_SELECTED);
                    Assert(-1 != nCurSel);
                    
                    if (nCurSel >= 0) {
                        char sz[MAX_PATH];
                        
                        ListView_GetItemText(hwndList, nCurSel, 0, sz, sizeof(sz));
                        
                        SetDlgItemText(hwndDlg, IDC_STEXT_SELECT, sz);
                        
                        FREE_STR(pszSelectedTL);
                        pszSelectedTL = _strdup(sz);
                    }
                }
                return FALSE;
                
            case IDC_BUT_DELETE:
                if (BN_CLICKED == wNotifyCode) {                   
                    int nCurSel = ListView_GetNextItem(hwndList, -1, LVNI_SELECTED);
                    Assert(-1 != nCurSel);
                    
                    char szTransName[MAX_MSG_TXT]; // Transport name
                    ListView_GetItemText(hwndList, nCurSel, 0, szTransName, sizeof(szTransName));
                    
                    char szMsg[MAX_VAR_MSG_TXT];
                    {
                        char szQuestion[MAX_MSG_TXT]; // Question confirming deletion
                        
                        Dbg(LoadString(g_hInst, DBG_Deleting_DLL, szQuestion, sizeof(szQuestion)));
                        
                        wsprintf(szMsg, szQuestion, szTransName);
                    }
                    
                    char szTitle[MAX_MSG_TXT];
                    Dbg(LoadString(g_hInst, DLG_Deleting_DLL_Title, szTitle, sizeof(szTitle)));
                    strcat(szTitle, "'");
                    strcat(szTitle, szTransName);
                    strcat(szTitle, "'");
                    
                    if (MessageBox(hwndDlg, szMsg, szTitle, MB_OKCANCEL | MB_TASKMODAL) == IDOK) {
                        // Did we erase the selected transport layer
                        if (pszSelectedTL && !strcmp(szTransName, pszSelectedTL)) {
                            
                            // Erased
                            FREE_STR(pszSelectedTL);
                        }
                        
                        // Remove the deleted TL from the reg list.
                        {
                            TListEntry<CIndiv_TL_WKSP *> * pContEntry =
                                g_pCCopyOf_All_TLs_WrkSpc->
                                m_listConts.Find(szTransName, WKSP_Generic_CmpRegName);
                            
                            Assert(pContEntry);
                            delete pContEntry->m_tData;
                            delete pContEntry;
                        }
                        
                        Dbg(ListView_DeleteItem(hwndList, nCurSel));
                        
                        // Select the first item, make sure something is always selected.
                        ListView_SetItemState(hwndList, 0, LVIS_SELECTED | LVIS_FOCUSED, 0x000F);
                        
                        BOOL bEmpty = ListView_GetItemCount(hwndList) <= 0;
                        EnableWindow(hwndEdit, !bEmpty);
                        EnableWindow(hwndSelect, !bEmpty);
                        EnableWindow(hwndDelete, !bEmpty);
                        
                        SetDlgItemText(hwndDlg, IDC_STEXT_SELECT, pszSelectedTL);
                    }
                }
                return FALSE;
                
            case IDC_BUT_EDIT:
                if (BN_CLICKED == wNotifyCode) {
                    int nCurSel = ListView_GetNextItem(hwndList, -1, LVNI_SELECTED);
                    Assert(-1 != nCurSel);
                    
                    char szTransName[MAX_MSG_TXT]; // Transport name
                    ListView_GetItemText(hwndList, nCurSel, 0, szTransName, sizeof(szTransName));
                    
                    TListEntry<CIndiv_TL_WKSP *> * pContEntry =
                        g_pCCopyOf_All_TLs_WrkSpc->
                        m_listConts.Find(szTransName, WKSP_Generic_CmpRegName);
                    
                    if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DLG_TRANSPORTLAYER), hwndDlg,
                        (DLGPROC)EditTransportLayersDlgProc, (LPARAM)pContEntry->m_tData)) {
                        
                        // Data has been changed, repopulate the list.
                        AddDataToList(hwndDlg, g_pCCopyOf_All_TLs_WrkSpc);
                    }
                    
                    BOOL bEmpty = ListView_GetItemCount(hwndList) <= 0;
                    EnableWindow(hwndEdit, !bEmpty);
                    EnableWindow(hwndDelete, !bEmpty);
                    EnableWindow(hwndSelect, !bEmpty);
                }                
                return FALSE;
                
            case IDC_BUT_ADD:
                if (BN_CLICKED == wNotifyCode) {
                    CIndiv_TL_WKSP * pTL = new CIndiv_TL_WKSP;
                    
                    if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DLG_TRANSPORTLAYER), hwndDlg,
                        (DLGPROC)EditTransportLayersDlgProc, (LPARAM)pTL)) {
                        
                        pTL->SetParent(g_pCCopyOf_All_TLs_WrkSpc);
                        g_pCCopyOf_All_TLs_WrkSpc->AddToContainerList(pTL);
                        
                        // Data has been changed, repopulate the list.
                        AddDataToList(hwndDlg, g_pCCopyOf_All_TLs_WrkSpc);
                        
                        BOOL bEmpty = ListView_GetItemCount(hwndList) <= 0;
                        EnableWindow(hwndEdit, !bEmpty);
                        EnableWindow(hwndDelete, !bEmpty);
                        EnableWindow(hwndSelect, !bEmpty);
                    } else {
                        delete pTL;
                    }
                }                
                return FALSE;
            }
        }
        return FALSE;

    case WM_NOTIFY:
        switch (((LPNMHDR) lParam)->code) {
        default:
            return FALSE;

        case NM_DBLCLK:
           if (bTL_EditingAllowed) {
                LPNMHDR lpnmh = (LPNMHDR) lParam;
                
                switch (lpnmh->idFrom) {
                case IDC_LIST1:
                    // Dbl clicking will work the same as a pressing the "select" button.
                    // Let the Select button process the dbl click
                    PostMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDC_BUT_SELECT, BN_CLICKED),
                        (LPARAM) lpnmh->hwndFrom);
                    break;
                }
            }
            return FALSE;

        case PSN_KILLACTIVE:
            // Error checking: must select a TL, and that TL must exist
            if (!ValidateAllTransportLayers(hwndDlg, g_pCCopyOf_All_TLs_WrkSpc)) {
                MessageBeep(MB_ICONEXCLAMATION);
                SetWindowLong(hwndDlg, DWLP_MSGRESULT, TRUE);
            }
            
            if (NULL == pszSelectedTL) {
                
                PSTR pszTitle = WKSP_DynaLoadString(g_hInst, SYS_Warning);
                WKSP_MsgBox(pszTitle, ERR_Please_Select_A_TL);
                free(pszTitle);

                MessageBeep(MB_ICONEXCLAMATION);
                SetWindowLong(hwndDlg, DWLP_MSGRESULT, TRUE);
                
            } else if (NULL == g_pCCopyOf_All_TLs_WrkSpc->
                m_listConts.Find(pszSelectedTL, WKSP_Generic_CmpRegName)) {
                
                PSTR pszTitle = WKSP_DynaLoadString(g_hInst, SYS_Warning);
                WKSP_MsgBox(pszTitle, ERR_Transport_Doesnt_Exist, pszSelectedTL);
                free(pszTitle);

                MessageBeep(MB_ICONEXCLAMATION);
                SetWindowLong(hwndDlg, DWLP_MSGRESULT, TRUE);
            }
            
            SetWindowLong(hwndDlg, DWLP_MSGRESULT, FALSE);
            return TRUE;

        case PSN_APPLY:
            g_dynacontAll_TLs_WkSp.Duplicate(*g_pCCopyOf_All_TLs_WrkSpc);
            g_dynacontAll_TLs_WkSp.Save(FALSE, FALSE);
            
            Assert(SetTransportLayer(pszSelectedTL, g_pCCopyOf_All_TLs_WrkSpc));
            return TRUE;
        }
        break;

    case WM_DESTROY:
        delete g_pCCopyOf_All_TLs_WrkSpc;
        g_pCCopyOf_All_TLs_WrkSpc = NULL;
                
        if (pszSelectedTL) {
            free(pszSelectedTL);
            pszSelectedTL = NULL;
        }
        return FALSE;
    }
}