//--------------------------------------------------------------------------- void CXMMRCtrl::OnTimer(UINT nIDEvent) { if( nIDEvent == m_nTimerID ){ switch(m_TimerMode){ case 0: if( m_TimerCount ){ m_TimerCount--; break; } if( m_pCom ){ m_pCom->smpFFT = m_smpFFT; STRNCPY(m_pCom->title, m_Title, sizeof(m_pCom->title)); if( m_ComName.IsEmpty() ){ m_ComName = m_pCom->comName; } else { STRNCPY(m_pCom->comName, m_ComName, sizeof(m_pCom->comName)); } if( m_RadioName.IsEmpty() ){ m_RadioName = m_pCom->comRadio; } else { STRNCPY(m_pCom->comRadio, m_RadioName, sizeof(m_pCom->comRadio)); } } VERIFY(m_hWnd == (HWND)GetHwnd()); if( !m_hWnd ){ AfxMessageBox(IDS_XMMR_NO_WINDOW); return; } { TCHAR bf[512]; wsprintf(bf, _T("%s -h%X"), m_InvokeCommand, (DWORD)m_hWnd); #ifdef _UNICODE char bbf[512]; STRNCPY(bbf, bf, sizeof(bbf)); UINT r = ::WinExec(bbf, SW_SHOW); #else UINT r = ::WinExec(bf, SW_SHOW); #endif m_TimerMode++; m_TimerCount = (r > 31) ? m_Timeup : 1; } //break; case 1: m_TimerCount--; if( !m_TimerCount ){ DeleteTimer(); FireOnDisconnected(2); } else if( !m_bConnected && m_bInitialClose && (m_TimerCount < (m_Timeup-50)) ){ // For insurance HWND hWnd = ::FindWindow(_T("TMmttyWd"), NULL); if( hWnd ){ ::PostMessage(hWnd, gMsgMmtty, RXM_HANDLE, (DWORD)m_hWnd); ::PostMessage(hWnd, gMsgMmtty, RXM_REQHANDLE, 0); } } break; } } else { COleControl::OnTimer(nIDEvent); } }
BOOL CPeraProcessDesignerApp::InitInstance() { ZTools::InitZToolsLog(); if ( !m_CmdLine.Parse() ) { MessageBox( NULL, "解析命令行失败!", g_lpszAppTitle, MB_OK | MB_TOPMOST ); return FALSE; } m_hMetux = CreateMutex(NULL,TRUE,"PeraProcessDesigner.exe"); if (m_hMetux) { if (ERROR_ALREADY_EXISTS== GetLastError()) { HWND hwndPeraProcessDesignerCopied = FindPeraProcessDesignerMainWindow(); //当有互斥,但是没找到窗口时,认为之前的进程还在启动中,简单处理,直接退出 if ( hwndPeraProcessDesignerCopied) { if ( !m_CmdLine.GetValue( NULL ).IsEmpty() ) { #define WS_OPENWS_SENDMSG #ifdef WS_OPENWS_SENDMSG DWORD dwProcessId = 0; GetWindowThreadProcessId(hwndPeraProcessDesignerCopied, &dwProcessId); if ( GetTopModalWindow( dwProcessId ) == NULL ) { CSharedMemory Mem; CString sMemData = g_lpszDoubleOpenWsMemStr; Mem.Init( g_lpszDoubleOpenWsMemName, sMemData.GetLength()+MAX_PATH ); SendCopyData( hwndPeraProcessDesignerCopied, CPMSG_WORKSPACE_MAKESUREINFO, (LPVOID)NULL, 0 ); sMemData.Empty(); sMemData = (LPCTSTR)Mem.GetData(); if ( sMemData.CompareNoCase( g_lpszDoubleOpenWsMemStr ) == 0 ) { MessageBox( NULL, "建模环境处于活动状态,请先保存模型后重试!", g_lpszAppTitle, MB_OK | MB_TOPMOST ); } else { CString sCmdLine = ::GetCommandLine(); SendCopyData( hwndPeraProcessDesignerCopied, CPMSG_WORKSPACE_OPENWS, (LPVOID)(LPCTSTR)sCmdLine, sCmdLine.GetLength()+1 ); } } else { MessageBox( NULL, "建模环境处于活动状态,请先保存模型后重试!", g_lpszAppTitle, MB_OK | MB_TOPMOST ); } #else MessageBox( hwndPeraProcessDesignerCopied, "建模环境已打开,请在建模环境中打开本文件!", g_lpszAppTitle, MB_OK | MB_TOPMOST ); #endif } if (IsIconic(hwndPeraProcessDesignerCopied)) ShowWindow(hwndPeraProcessDesignerCopied,SW_RESTORE); SetForegroundWindow(hwndPeraProcessDesignerCopied); ZTools::WriteZToolsFormatLog("将已经运行的建模窗口激活,并前端显示..."); } CloseHandle(m_hMetux); m_hMetux = NULL; ZTools::WriteZToolsFormatLog("已经存在一个建模客户端,本运行实例将退出..."); return FALSE; } } m_LoginData.m_strRealName = m_CmdLine.GetValue( "realName" ); m_LoginData.m_strUser = m_CmdLine.GetValue( "userName" ); m_LoginData.m_strTicket = m_CmdLine.GetValue( "ticket-proxy" ); WriteShareMemoryLoginInfo(); CCrashHandler ch; ch.SetProcessExceptionHandlers(); ch.SetThreadExceptionHandlers(); //如果PeraTaskService进程不存在,自动启动 StartPeraTaskService(); //_CrtSetBreakAlloc(1300); // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); //hModule = ::LoadLibrary("C:\\Users\\kunmiao-li\\Desktop\\TestBuild\\PeraLicMgr\\Release\\PeraLicMgr.dll"); //#ifndef _DEBUG if (!InitLicense("PeraWorkSpace")) return FALSE; // if(!m_FlexNetMgr.CheckOutLicense("PeraWorkSpace")) // { // return FALSE; // } // hModule = ::LoadLibrary(ZTools::FormatString("%s\\PeraLicMgr.dll", GetFlexwareBinPathMethod()).c_str()); // if( hModule != NULL ) // { // lpFnDLLfunc = (LPFNDLLFUNC) ::GetProcAddress(hModule, "CheckOutLicense"); // if(lpFnDLLfunc != NULL) // { // if(!lpFnDLLfunc("PeraProcessDesigner")) // { // return FALSE; // } // } // else // { // return FALSE; // } // } // else // { // AfxMessageBox("检测到系统安装不完整,请联系管理员重新安装!", MB_OK|MB_ICONINFORMATION); // return FALSE; // } //#endif //if(!m_FlexNetMgr.InitNewJob("PeraProcessDesigner")) //{ // return FALSE; //} CWinApp::InitInstance(); InitGDIPlus(); LoadResLibImageSet(); //LoadDefaultFont(); //CBCGPPopupMenuBar::SetPeraPaint( g_crToolbarBg ); //CXmlBase xml; //MSXML2::IXMLDOMDocument2Ptr pdoc = xml.GetXmlDocPtrByFile(GetExecDir() + "\\Manifest.xml"); //MSXML2::IXMLDOMNodeListPtr pModels; //MSXML2::IXMLDOMNodePtr pModel; //long lModelCount; //HRESULT hr = S_OK; //map<CString, CString> mapAttrs; //map<CString, CString>::iterator iterAttrs; //CString str; //pModels = xml.GetNodeListPtr("/Manifest/Component", pdoc); //if (pModels != NULL) //{ // lModelCount = pModels->Getlength(); // for (long i=0; i<lModelCount; i++) // { // hr = pModels->get_item(i, &pModel); // if (FAILED(hr) || NULL == pModel) // { // continue; // } // if (0 == xml.GetAttrsOfNode(mapAttrs, pModel)) // { // continue; // } // iterAttrs = mapAttrs.find("RobotName"); // if (iterAttrs != mapAttrs.end()) str= iterAttrs->second; // } //} //CCxArray3D a3d(DT_ARRAY3D_INT); //CString str3d = "[1,2,3,4,5,](4,3,2)" //CString str = "[1e150,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24](2,3,4)"; // CString str = "[\"\\\\\\\",,1e150\",\"2\"](2)"; //{ // CString str1; // for (int a=0;a<2;a++) // { // for (int b=0;b<3;b++) // { // for (int c=0;c<4;c++) // { // } // } // } //} // //CxArrayND nd( DT_ARRAY1D_STRING ); //nd.Parse( str ); //vector<int> vPos; //vPos.push_back(0); ////vPos.push_back(0); ////vPos.push_back(0); //LPARAM lpData = nd.GetDataPtr( vPos ); //CString * pData = reinterpret_cast< CString * > ( lpData ); //nd.Clear(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskBarInteraction(FALSE); globalData.SetDPIAware (); //globalData.bDisableAero = TRUE; //Bar挺靠后,Slider宽度,由于Splitter最小宽度为4,所以此值不应小于4,否则与Splitter不协调。 CBCGPSlider::m_nDefaultWidth = 4; // All registry read/write operations will be produced via CBCGPXMLSettings gateway: CBCGPRegistrySP::SetRuntimeClass (RUNTIME_CLASS (CBCGPXMLSettings)); // Read settings: CBCGPXMLSettings::ReadXMLFromFile (FALSE, GetExecDir() + _T("\\user.xml")); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization //SetRegistryKey(_T("PeraProcessDesigner")); //LoadStdProfileSettings(0); // Load standard INI file options (including MRU) //SetRegistryBase (_T("Settings")); RECT rectDesktop; SystemParametersInfo(SPI_GETWORKAREA,0,(PVOID)&rectDesktop,0); m_rcLastWindowPlacement = rectDesktop; CRect rectDesktop2 = rectDesktop; int nFlag = 0; int nShowCmd = 0; LoadWindowPlacement( m_rcLastWindowPlacement, nFlag, nShowCmd ); StoreWindowPlacement (rectDesktop2, 2, SW_SHOWMAXIMIZED); theGlobalConfig.Load(); m_bAloneVersionWs = IsPeraProcessRunnerInstalled(); CCxBCGPVisualManager2007::SetStyle (CCxBCGPVisualManager2007::VS2007_Silver); CCxBCGPVisualManager2007::SetDefaultManager (RUNTIME_CLASS (CCxBCGPVisualManager2007)); //globalData.bDisableAero = TRUE; //globalData.bIsOSAlphaBlendingSupport = TRUE; // Initialize all Managers for usage. They are automatically constructed // if not yet present InitMouseManager(); //InitContextMenuManager(); InitKeyboardManager(); // Enable user-defined tools. If you want allow more than 10 tools, // add tools entry to resources (ID_USER_TOOL11, ID_USER_TOOL12,...) EnableUserTools (ID_TOOLS_ENTRY, ID_USER_TOOL1, ID_USER_TOOL10); // TODO: Remove this if you don't want extended tooltips: InitTooltipManager(); CBCGPToolTipParams params; params.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager ()->SetTooltipParams ( BCGP_TOOLTIP_TYPE_ALL, RUNTIME_CLASS (CBCGPToolTipCtrl), ¶ms); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_MAIN, RUNTIME_CLASS(CPeraProcessDesignerDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CPeraProcessDesignerView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame->LoadFrame(IDR_MAIN)) return FALSE; m_bCreate = TRUE; m_pMainWnd = pMainFrame; //basehtmldialog中,屏蔽快捷键 g_hwndMainWindow = pMainFrame->GetSafeHwnd(); g_pLoadingWindow = new CLoadingWindow( TIMER_LOADING_WINDOW, IDD_DIALOG_LOGIN_BK, m_pMainWnd ); g_pLoadingWindow->Create( IDD_DIALOG_LOGIN_BK, m_pMainWnd ); g_pLoadingWindow->Init( GetExecDir() + "\\Res\\DlgProgress\\DlgProgress.png" ); pMainFrame->m_wndMenuBar.LoadData(); //pMainFrame->OnMenuModuleOpenjianmo(); // call DragAcceptFiles only if there's a suffix // In an MDI app, this should occur immediately after setting m_pMainWnd // Parse command line for standard shell commands, DDE, file open //CCommandLineInfo cmdInfo; //ParseCommandLine(cmdInfo); //if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew) //{ // if (!pMainFrame->LoadMDIState (GetRegSectionPath ()) || // DYNAMIC_DOWNCAST(CMDIChildWnd, pMainFrame->GetActiveFrame()) == NULL) // { // if (!ProcessShellCommand(cmdInfo)) // return FALSE; // } //} //else //{ // // Dispatch commands specified on the command line // if (!ProcessShellCommand(cmdInfo)) // return FALSE; //} // The main window has been initialized, so show and update it pMainFrame->OnMenuModuleOpenjianmo(); m_bInitMDI = TRUE; m_nCmdShow = SW_SHOWMAXIMIZED; pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); ////////////////////////////////////////////////////////////////////////// //日志输出窗口 #ifdef USE_DLGLOG m_dlgLog.Create(CDlgLog::IDD, NULL); //m_dlgLog.ShowWindow(SW_SHOW); // int x, y; // x = GetSystemMetrics(SM_CXFULLSCREEN); //屏幕宽度 // y = GetSystemMetrics(SM_CYFULLSCREEN); //屏幕高度 CRect rectFull; SystemParametersInfo(SPI_GETWORKAREA,0,&rectFull,0); CRect rect; m_dlgLog.GetWindowRect(rect); rect.MoveToXY(0, rectFull.bottom - rect.Height()); m_dlgLog.MoveWindow(rect); #endif // USE_DLGLOG ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //延长票据有效期 StartKeepTicketThread(); ////////////////////////////////////////////////////////////////////////// //在线编辑用到的共享内存初始化 m_pSharedMemoryOnlineEdit = NULL; m_pSharedMemoryOnlineEdit = new SharedMemoryOnlineEdit(); ////////////////////////////////////////////////////////////////////////// g_ReadRobotDB.Load(); pMainFrame->m_wndLoginBar.RedrawWindow(); CString sParamFile = m_CmdLine.GetValue( NULL ); if ( !sParamFile.IsEmpty() ) { ZTools::WriteZToolsFormatLog( "--------------********打开文件[%s]**********-------------", sParamFile ); theApp.m_processMgr.Open( sParamFile ); } else { ZTools::WriteZToolsLog( "--------------********未打开文件逻辑**********-------------" ); CDlgStart lgn; lgn.DoModal(); } #ifdef USE_DLGLOG m_dlgLog.ShowWindow(SW_SHOW); #endif // USE_DLGLOG ////////////////////////////////////////////////////////////////////////// WINDOWPLACEMENT wp; memset(&wp, NULL, sizeof(wp)); wp.length = sizeof (WINDOWPLACEMENT); if (pMainFrame->GetWindowPlacement (&wp)) { wp.rcNormalPosition = m_rcLastWindowPlacement; RECT rectDesktop; SystemParametersInfo(SPI_GETWORKAREA,0,(PVOID)&rectDesktop,0); OffsetRect(&wp.rcNormalPosition, -rectDesktop.left, -rectDesktop.top); pMainFrame->SetWindowPlacement (&wp); } return TRUE; }
void CKeyValue::OnOK() { BOOL bRetVal = TRUE; // Check for duplicate selection // Get key handler array from the document // Check for valid pointer if (m_pDoc != NULL && m_bDataSaved == false) { CStringArray* pKeyArray = m_pDoc->omStrGetKeyHandlerPrototypes(); if (pKeyArray) { CString omStrMsgPro = STR_EMPTY; UINT unKeyHandlerCount = 0; unKeyHandlerCount = (COMMANUINT)pKeyArray->GetSize(); for (UINT nCount = 0; nCount < unKeyHandlerCount; nCount++) { omStrMsgPro = pKeyArray->GetAt( nCount ); CString omStrFuncName = defKEY_HANDLER; CString omStrKeyPressed = ""; if((*m_pcKeyVal) == defGENERIC_KEY) { omStrKeyPressed = defGENERIC_KEY_HANDLER_TEXT; } else { omStrKeyPressed = m_pcKeyVal; } omStrFuncName += omStrKeyPressed; // Construct Function definiton CString omStrFuncPrototype = defDEFAULT_KEY_HANDLER_CODE; omStrFuncPrototype.Replace("KEYNAME", omStrKeyPressed ); if ( omStrMsgPro == omStrFuncPrototype ) { omStrMsgPro = defMSG_DUPL_KEY_HANDLER; omStrMsgPro.Replace( "KEYNAME", m_pcKeyVal ); // Duplicate message hanlder, shout AfxMessageBox( omStrMsgPro, MB_OK|MB_ICONINFORMATION ); nCount = (COMMANUINT)pKeyArray->GetSize(); bRetVal = FALSE; } } } } if ( bRetVal == TRUE && m_bDataSaved == false) { CDialog::OnOK(); } else { if ( m_bDataSaved == true) { m_bDataSaved = false; CDialog::OnCancel(); } else { CDialog::OnOK(); } } }
void CDlgCrearUsuario::OnBnClickedOk() { UpdateData(TRUE); /* Se comprueba si se ha introducido el usuario*/ if (m_strUsuario.IsEmpty()) { AfxMessageBox(IDS_NO_USUARIO); return; } /* Se comprueba que se haya introducido la contraseña */ if (m_strPassword.IsEmpty()) { AfxMessageBox(IDS_NO_PASSW); return; } /* Se comprueba que se haya introducido la comprobación de la contraseña */ if (m_strPassword2.IsEmpty()) { AfxMessageBox(IDS_NO_PASSW2); return; } /* Se comprueba que el usuario no haya excedido de 8 caracteres */ if (m_strUsuario.GetLength() > LONG_USUARIO) { AfxMessageBox(IDS_USUARIO_LARGO); return; } /* Se comprueba que no la contraseña y su comprobación son iguales */ if (m_strPassword != m_strPassword2) { AfxMessageBox(IDS_INVALID_PASSW); return; } /* Se comprueba que la contraseña no exceda de 8 caracteres */ if (m_strPassword.GetLength() > LONG_USUARIO) { AfxMessageBox(IDS_PASSW_LARGA); return; } /* Se obtiene el identificador del perfil */ CPerfiles rsPerfiles(m_db); m_strPerfil = m_strPerfil.Trim(); rsPerfiles.m_strFilter = "DESCRIPCION LIKE '" + m_strPerfil + "'"; if (!rsPerfiles.Open(CRecordset::dynaset)) { AfxMessageBox(IDC_ERROR_BD); return; } if (rsPerfiles.GetRecordCount() != 1) { AfxMessageBox(IDC_INVALID_PERFIL); return; } int iIdPerfil = rsPerfiles.m_ID; rsPerfiles.Close(); /* Se inserta el usuario en la tabla de Usuario */ CUsuario rsUsuario(m_db); rsUsuario.m_USUARIO = m_strUsuario; /* Se cifra la contraseña */ CEncriptar cEncriptar; CString strPasswCifrada = m_strPassword; cEncriptar.Encriptar (strPasswCifrada); strPasswCifrada.Replace("'", "''"); rsUsuario.m_PASSWORD = strPasswCifrada; rsUsuario.m_IDPERFIL = iIdPerfil; HRESULT hErr = rsUsuario.Insert(); OnOK(); }
bool CCommunicationManager::Init(void) { ASSERT(m_pSettings); //ты забыл меня инициализировать! ASSERT(m_pBootLoader); ASSERT(m_pControlApp); ASSERT(m_pAppAdapter); ASSERT(m_pBldAdapter); bool status = true; m_pBootLoader->SetPlatformParameters(PlatformParamHolder(m_pSettings->GetECUPlatformType())); //останавливаем работу контроллеров интерфейсов, конкретный контроллер будет активирован //позже - в зависимости от текущего контекста программы m_pControlApp->SwitchOn(false); m_pBootLoader->SwitchOn(false); //для того чтобы можно было применить новые настройки к порту, необходимо его заново открыть m_pComPort->Terminate(); //Set protocol data encoding/decoding mode (Hex or Bin) m_pControlApp->SetProtocolDataMode(m_pSettings->GetHexDataMode()); //Set parameters for speed sensor calculations m_pControlApp->SetNumPulsesPer1Km(m_pSettings->GetNumPulsesPer1Km()); //Set clock frequency (16 or 20 mHz) m_pControlApp->SetQuartzFrq((EP_ATMEGA644==m_pSettings->GetECUPlatformType()) ? 20000000 : 16000000); try { //на скорость переданную в эту функцию не нужно обращать внимания (она будет установлена конкретным контроллером интрерфейса) m_pComPort->Initialize(_TSTRING(m_pSettings->GetPortName()), 9600, NOPARITY, ONESTOPBIT, false, true); } catch(CComPort::xInitialize e) { //говорим пользователю что нам не удалось открыть указанный порт! AfxMessageBox(e.GetDetailStr()); status = false; } m_pComPort->Purge(); //инициализируем контроллеры интерфейсов try { m_pControlApp->Initialize(m_pComPort,m_pSettings->GetBaudRateApplication(),500); } catch(CControlApp::xThread) { ASSERT(0); //because, strange situation! status = false; } try { m_pBootLoader->Initialize(m_pComPort,m_pSettings->GetBaudRateBootloader()); } catch (CBootLoader::xThread) { ASSERT(0); status = false; } //Инициализруем адаптеры коммуникационных контроллеров CWnd* pParent = AfxGetApp()->m_pMainWnd; VERIFY(m_pAppAdapter->Create(pParent)); VERIFY(m_pBldAdapter->Create(pParent)); //Связываем адаптеры с коммуникационными контроллерами m_pControlApp->SetEventHandler(m_pAppAdapter); m_pBootLoader->SetEventHandler(m_pBldAdapter); //оповещаем объект слушателя об изменении настроек. Получатель этого оповещения должен активировать //необходимый ему коммуникационный контроллер. if (m_OnSettingsChanged) m_OnSettingsChanged(); return status; }
BOOL CAOIDApp::InitInstance() { CWinAppEx::InitInstance(); // 初始化 OLE 库 if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(FALSE); // 使用 RichEdit 控件需要 AfxInitRichEdit2() // AfxInitRichEdit2(); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); LoadStdProfileSettings(4); // 加载标准 INI 文件选项(包括 MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // 注册应用程序的文档模板。文档模板 // 将用作文档、框架窗口和视图之间的连接 CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CAOIDDoc), RUNTIME_CLASS(CMainFrame), // 主 SDI 框架窗口 RUNTIME_CLASS(CAOIDView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // 分析标准 shell 命令、DDE、打开文件操作的命令行 CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); #if !defined(_WIN32_WCE) || defined(_CE_DCOM) // 通过 CoRegisterClassObject() 注册类工厂。 if (FAILED(_AtlModule.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE))) return FALSE; #endif // !defined(_WIN32_WCE) || defined(_CE_DCOM) // 应用程序是用 /Embedding 或 /Automation 开关启动的。 // 将应用程序作为自动化服务器运行。 if (cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated) { // 不显示主窗口 return TRUE; } // 应用程序是用 /Unregserver 或 /Unregister 开关启动的。 if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister) { _AtlModule.UpdateRegistryAppId(FALSE); _AtlModule.UnregisterServer(TRUE); return FALSE; } // 应用程序是用 /Register 或 /Regserver 开关启动的。 if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppRegister) { _AtlModule.UpdateRegistryAppId(TRUE); _AtlModule.RegisterServer(TRUE); return FALSE; } // 调度在命令行中指定的命令。如果 // 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。 if (!ProcessShellCommand(cmdInfo)) return FALSE; m_pMainWnd->SetWindowText(_T("AOID"));//在主窗口显示的程序名 // 唯一的一个窗口已初始化,因此显示它并对其进行更新 m_pMainWnd->ShowWindow(SW_SHOW);//SW_SHOWMAXIMIZED);显示应用程序框架窗口 m_pMainWnd->UpdateWindow(); //**** CMainFrame * pwnd = (CMainFrame *)AfxGetMainWnd(); pwnd->m_pOpPaneWnd->SwitchToView(VIEW_F8SUBITEM1);//主界面为工作状态界面 /*pwnd->m_pMenuPaneWnd->m_pProgView->OnF8(); pwnd->m_pMenuPaneWnd->m_pProgView->m_TreeF8.Select(pwnd->m_pMenuPaneWnd->m_pProgView->hF8SubItem1,TVGN_DROPHILITE);//使选择的菜单项显示为选择状态 */ // 仅当具有后缀时才调用 DragAcceptFiles // 在 SDI 应用程序中,这应在 ProcessShellCommand 之后发生 return TRUE; }
BOOL CCalcApp::InitInstance() { // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #if _MFC_VER < 0x0700 Enable3dControls(); #endif // Initialize OLE 2.0 libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } // Parse command line for automation or reg/unreg switches. CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); if (RunEmbedded() || RunAutomated()) { // Register all OLE server (factories) as running. This enables the // OLE 2.0 libraries to create objects from other applications. COleTemplateServer::RegisterAll(); // Do not continue with rest of initialization. Wait for // client to create a CCalcDlg object instead. return TRUE; } // App was launched with /Unregserver or /Unregister switch. Remove // entries from the registry. else if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister) { COleObjectFactory::UpdateRegistryAll(FALSE); AfxOleUnregisterTypeLib(_tlid, _wVerMajor, _wVerMinor); return FALSE; } // App was launched standalone or with other switches (e.g. /Register // or /Regserver). Update registry entries, including typelibrary. else { COleObjectFactory::UpdateRegistryAll(); AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid); if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppRegister) return FALSE; } // create a modeless dialog as the main window of the application //suppress warning because an object of CDialog is self-destructing #pragma warning (suppress: 6014) CCalcDlg* pDlg = new CCalcDlg; pDlg->SetVisible(TRUE); if (!pDlg->GetVisible()) { AfxMessageBox(IDP_UNABLE_TO_SHOW_CALC); return FALSE; } pDlg->RegisterActive(); // We are using a modeless dialog so we can translate accelerator keys // against the dialog. In order to run the main message pump, // InitInstance must return TRUE even though this application is // a dialog-based application. return TRUE; }
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { // 要求用户设置工作控件目录 ///* CWorkSpaceDlg workSpaceDlg ; if(workSpaceDlg.DoModal()==IDOK && workSpaceDlg.folderpath != ""){ // 取得用户指定的文件夹 m_workSpacePath = workSpaceDlg.folderpath; // 将该文件夹名称留存,以便下次回填 CStdioFile workspace ; workspace.Open("workspace.txt",CFile::modeCreate|CFile::modeWrite|CFile::typeText); workspace.WriteString(m_workSpacePath); // 如果工作空间目录不存在则创建 DWORD dwAttr = GetFileAttributes(m_workSpacePath); if(dwAttr==-1||(dwAttr&FILE_ATTRIBUTE_DIRECTORY)==0)//目录不存在 { if ( !MakeDir(m_workSpacePath)) { AfxMessageBox("can't create directionary:"+m_workSpacePath); PostMessage(WM_QUIT,0,0); //return; } } }else{ PostMessage(WM_QUIT,0,0); } //*/ if (CMDIFrameWndEx::OnCreate(lpCreateStruct) == -1) return -1; BOOL bNameValid; // set the visual manager and style based on persisted value OnApplicationLook(theApp.m_nAppLook); CMDITabInfo mdiTabParams; mdiTabParams.m_style = CMFCTabCtrl::STYLE_3D_ONENOTE; // other styles available... mdiTabParams.m_bActiveTabCloseButton = TRUE; // set to FALSE to place close button at right of tab area mdiTabParams.m_bTabIcons = FALSE; // set to TRUE to enable document icons on MDI taba mdiTabParams.m_bAutoColor = TRUE; // set to FALSE to disable auto-coloring of MDI tabs mdiTabParams.m_bDocumentMenu = TRUE; // enable the document menu at the right edge of the tab area EnableMDITabbedGroups(TRUE, mdiTabParams); if (!m_wndMenuBar.Create(this)) { TRACE0("Failed to create menubar\n"); return -1; // fail to create } m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY); // prevent the menu bar from taking the focus on activation CMFCPopupMenu::SetForceMenuFocus(FALSE); if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } CString strToolBarName; bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD); ASSERT(bNameValid); m_wndToolBar.SetWindowText(strToolBarName); CString strCustomize; bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE); ASSERT(bNameValid); m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize); // Allow user-defined toolbars operations: InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId); if (!m_wndStatusBar.Create(this)) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT)); // TODO: Delete these five lines if you don't want the toolbar and menubar to be dockable m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY); m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndMenuBar); DockPane(&m_wndToolBar); // enable Visual Studio 2005 style docking window behavior CDockingManager::SetDockingMode(DT_SMART); // enable Visual Studio 2005 style docking window auto-hide behavior EnableAutoHidePanes(CBRS_ALIGN_ANY); // Load menu item image (not placed on any standard toolbars): CMFCToolBar::AddToolBarForImageCollection(IDR_MENU_IMAGES, theApp.m_bHiColorIcons ? IDB_MENU_IMAGES_24 : 0); // create docking windows if (!CreateDockingWindows()) { TRACE0("Failed to create docking windows\n"); return -1; } m_wndFileView.EnableDocking(CBRS_ALIGN_ANY); m_wndClassView.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndFileView); CDockablePane* pTabbedBar = NULL; m_wndClassView.AttachToTabWnd(&m_wndFileView, DM_SHOW, TRUE, &pTabbedBar); m_wndOutput.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndOutput); m_wndProperties.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndProperties); // Enable enhanced windows management dialog EnableWindowsDialog(ID_WINDOW_MANAGER, ID_WINDOW_MANAGER, TRUE); // Enable toolbar and docking window menu replacement EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR); // enable quick (Alt+drag) toolbar customization CMFCToolBar::EnableQuickCustomization(); if (CMFCToolBar::GetUserImages() == NULL) { // load user-defined toolbar images if (m_UserImages.Load(_T(".\\UserImages.bmp"))) { CMFCToolBar::SetUserImages(&m_UserImages); } } // enable menu personalization (most-recently used commands) // TODO: define your own basic commands, ensuring that each pulldown menu has at least one basic command. CList<UINT, UINT> lstBasicCommands; lstBasicCommands.AddTail(ID_FILE_NEW); lstBasicCommands.AddTail(ID_FILE_OPEN); lstBasicCommands.AddTail(ID_FILE_SAVE); lstBasicCommands.AddTail(ID_FILE_PRINT); lstBasicCommands.AddTail(ID_APP_EXIT); lstBasicCommands.AddTail(ID_EDIT_CUT); lstBasicCommands.AddTail(ID_EDIT_PASTE); lstBasicCommands.AddTail(ID_EDIT_UNDO); lstBasicCommands.AddTail(ID_APP_ABOUT); lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR); lstBasicCommands.AddTail(ID_VIEW_TOOLBAR); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2003); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_VS_2005); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLUE); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_SILVER); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLACK); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_AQUA); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_WINDOWS_7); lstBasicCommands.AddTail(ID_SORTING_SORTALPHABETIC); lstBasicCommands.AddTail(ID_SORTING_SORTBYTYPE); lstBasicCommands.AddTail(ID_SORTING_SORTBYACCESS); lstBasicCommands.AddTail(ID_SORTING_GROUPBYTYPE); CMFCToolBar::SetBasicCommands(lstBasicCommands); // Switch the order of document name and application name on the window title bar. This // improves the usability of the taskbar because the document name is visible with the thumbnail. ModifyStyle(0, FWS_PREFIXTITLE); return 0; }
BOOL CPPageFormats::OnApply() { m_bHaveRegisteredCategory = false; if (!m_bInsufficientPrivileges) { UpdateData(); int iSelectedItem = m_list.GetSelectionMark(); if (iSelectedItem >= 0) { DWORD_PTR i = m_list.GetItemData(iSelectedItem); m_mf[i].SetExts(m_exts); m_exts = m_mf[i].GetExtsWithPeriod(); UpdateData(FALSE); } CFileAssoc::RegisterApp(); int fSetContextFiles = m_fContextFiles.GetCheck(); int fSetAssociatedWithIcon = m_fAssociatedWithIcons.GetCheck(); if (m_bFileExtChanged) { if (fSetAssociatedWithIcon && IsNeededIconsLib() && !CFileAssoc::LoadIconLib()) { AfxMessageBox(IDS_MISSING_ICONS_LIB, MB_ICONEXCLAMATION | MB_OK, 0); } for (int i = 0, cnt = m_list.GetItemCount(); i < cnt; i++) { int iChecked = IsCheckedMediaCategory(i); if (!m_bHaveRegisteredCategory && iChecked) { m_bHaveRegisteredCategory = true; } if (iChecked == 2) { continue; } CFileAssoc::Register(m_mf[m_list.GetItemData(i)], !!iChecked, !!fSetContextFiles, !!fSetAssociatedWithIcon); } m_bFileExtChanged = false; if (fSetAssociatedWithIcon) { CFileAssoc::FreeIconLib(); } } CFileAssoc::RegisterFolderContextMenuEntries(!!m_fContextDir.GetCheck()); UpdateMediaCategoryState(m_list.GetSelectionMark()); CFileAssoc::RegisterAutoPlay(CFileAssoc::AP_VIDEO, !!m_apvideo.GetCheck()); CFileAssoc::RegisterAutoPlay(CFileAssoc::AP_MUSIC, !!m_apmusic.GetCheck()); CFileAssoc::RegisterAutoPlay(CFileAssoc::AP_AUDIOCD, !!m_apaudiocd.GetCheck()); CFileAssoc::RegisterAutoPlay(CFileAssoc::AP_DVDMOVIE, !!m_apdvd.GetCheck()); m_mf.SetRtspHandler(m_iRtspHandler == 0 ? RealMedia : m_iRtspHandler == 1 ? QuickTime : DirectShow, !!m_fRtspFileExtFirst); CAppSettings& s = AfxGetAppSettings(); s.m_Formats = m_mf; s.fAssociatedWithIcons = !!m_fAssociatedWithIcons.GetCheck(); SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); } return __super::OnApply(); }
bool NoteGenerator::Ask_User_Merge_or_Save_New_Notes( long lastProcessedSampleIdx, bool& retUserDidMerge, CString& retErrorMesg ) { retErrorMesg.Empty(); retUserDidMerge = false; if( m_tempNoteList == NULL ) { retErrorMesg = "NoteGenerator::Ask_User_Merge_or_Save_New_Notes FAILED, m_tempNoteList is NULL." ; return false; } if( m_masterNoteList == NULL ) { retErrorMesg = "NoteGenerator::Ask_User_Merge_or_Save_New_Notes FAILED, m_masterNoteList is NULL." ; return false; } ASSERT( m_bitSourceStreaming != NULL ); long noteCount = m_tempNoteList->Count(); if( noteCount < 3 ) { retErrorMesg = "Not enough notes were recorded during your Recording Session. Try again to record more notes." ; return false; } int reslt = AfxMessageBox( "Do you want to MERGE the Recorded Notes to the Current NoteList? \n\n( YES: Merge, NO: Save notes to a new File )", MB_YESNOCANCEL | MB_ICONQUESTION ); if( reslt == IDYES ) { Begin_Wait_Cursor_GLB(); if( ! Merge_TempList_to_Master_Notelist( retErrorMesg ) ) { m_bitSourceStreaming->m_recordNotesNow = false; End_Wait_Cursor_GLB(); return false; } End_Wait_Cursor_GLB(); retUserDidMerge = true; // tell calling function of this action } else if( reslt == IDNO ) { if( ! Save_Recorded_Notes_withDialog( lastProcessedSampleIdx, retErrorMesg ) ) { m_bitSourceStreaming->m_recordNotesNow = false; return false; } } else if( reslt == IDCANCEL ) { int dummy = 9; } return true; }
// ---------------------------------------------------------------------------- // 2006-10-23 오전 4:36:18 추가(New), Sun.H.D // 호출 시점 : Arrow Line // // 특 징 : // // 매개 변수 : // // 리 턴 값 : // ---------------------------------------------------------------------------- void CArrowLine::Draw(CDC* pDC) { CPen aPen; UINT nType = 0; CPoint ArrowPoint; if(!aPen.CreatePen(PS_SOLID, 1, m_clrColor)) { // Pen creation failed. Close the program AfxMessageBox("Pen creation failed drawing a curve", MB_OK); AfxAbort(); } CPen* pOldPen = pDC->SelectObject(&aPen); // Select the pen pDC->MoveTo(m_ptStartPoint); pDC->LineTo(m_ptEndPoint); if(m_ptStartPoint.y == m_ptEndPoint.y) nType = 0; else nType = 1; // 수평선 if(nType==0) { ArrowPoint = m_ptStartPoint; ArrowPoint.x += m_nArrowSize; ArrowPoint.y -= m_nArrowSize; pDC->MoveTo(ArrowPoint); pDC->LineTo(m_ptStartPoint); ArrowPoint = m_ptStartPoint; ArrowPoint.x += m_nArrowSize; ArrowPoint.y += m_nArrowSize; pDC->LineTo(ArrowPoint); ArrowPoint = m_ptEndPoint; ArrowPoint.x -= m_nArrowSize; ArrowPoint.y -= m_nArrowSize; pDC->MoveTo(ArrowPoint); pDC->LineTo(m_ptEndPoint); ArrowPoint = m_ptEndPoint; ArrowPoint.x -= m_nArrowSize; ArrowPoint.y += m_nArrowSize; pDC->LineTo(ArrowPoint); } else { // 수직선 ArrowPoint = m_ptStartPoint; ArrowPoint.x -= m_nArrowSize; ArrowPoint.y += m_nArrowSize; pDC->MoveTo(ArrowPoint); pDC->LineTo(m_ptStartPoint); ArrowPoint = m_ptStartPoint; ArrowPoint.x += m_nArrowSize; ArrowPoint.y += m_nArrowSize; pDC->LineTo(ArrowPoint); ArrowPoint = m_ptEndPoint; ArrowPoint.x -= m_nArrowSize; ArrowPoint.y -= m_nArrowSize; pDC->MoveTo(ArrowPoint); pDC->LineTo(m_ptEndPoint); ArrowPoint = m_ptEndPoint; ArrowPoint.x += m_nArrowSize; ArrowPoint.y -= m_nArrowSize; pDC->LineTo(ArrowPoint); } pDC->SelectObject(pOldPen); // Restore the old pen }
bool NoteGenerator::Merge_TempList_to_Master_Notelist( CString& retErrorMesg ) { retErrorMesg.Empty(); if( m_tempNoteList == NULL ) // the TEMP-list has the newly recorded notes ( Recorded notes go directly here, then they can be saved to harddisk { retErrorMesg = "NoteGenerator::Merge_TempList_to_Master_Notelist FAILED, m_tempNoteList is NULL. " ; return false; } if( m_masterNoteList == NULL ) // These are the notes that we HEAR and SEE on the display. { retErrorMesg = "NoteGenerator::Merge_TempList_to_Master_Notelist FAILED, m_masterNoteList is NULL. " ; return false; } if( m_tempNoteList->Count() < 3 ) { retErrorMesg = "Record some notes. (not enough notes were recorded)" ; // also get this if not in Detection for Mini-Source Mode return false; } long retStartOffset = -1, retEndOffset = -1, retConcurentCount = -1, retNoteCountAdded = -1; short retDeleteCount= -1; if( ! SPitchCalc::Calc_StartOffset_EndOffset_for_NoteLists_Merge( retStartOffset, retEndOffset, *m_tempNoteList, retErrorMesg ) ) return false; // Now excluding the FIRST and LAST detected-notes if( ! SPitchCalc::Delete_Notes_in_TimeSpan( retStartOffset, retEndOffset, retDeleteCount, *m_masterNoteList, *m_tempNoteList, retErrorMesg ) ) return false; // Its OK for this to NOT delete anyting. Just means that the new notes' Zone did not intersect any old notes. if( ! SPitchCalc::Add_TempLists_Notes_to_Master_Notelist( *m_tempNoteList, *m_masterNoteList, // m_sampleIdxRecordingStart, m_sampleIdxRecordingEnd, retStartOffset, retEndOffset, retNoteCountAdded, retErrorMesg ) ) return false; long swapCount = SPitchCalc::Sort_NoteList_by_TimePosition( *m_masterNoteList, retErrorMesg ); // since we blindly added the notes to the end of list if( swapCount == 0 ) { int dummy = 0; // Can easily happen, if user's Recorded-Notes go into a LATER Time-Zone that is EMPTY of notes } if( ! SPitchCalc::Count_Concurrent_Notes_in_List( *m_masterNoteList, retConcurentCount, retErrorMesg ) ) // check for error in my Algo. 1/21/2012 AfxMessageBox( retErrorMesg ); long totalNotesInMasterList = m_masterNoteList->Count(); long totalNotesInTempList = m_tempNoteList->Count(); m_masterNoteList->m_lastFoundCalcNoteLink = NULL; // Reset the CACHE. BIG, the next play command will have to do a FULL Notelist search. 1/23/2012 TRACE( "MERGE is completed. [ NoteCOUNT in TempList %d ] [ %d notes deleted ] [ %d Notes added ] [ Master %d notes ] \n" , totalNotesInTempList, retDeleteCount, retNoteCountAdded, totalNotesInMasterList ); if( retConcurentCount >= 1 ) // ******************** TEMP, DEBUG **************** { CString mesg; mesg.Format( "*** MERGE PROBLEM: Found %d CONCURRENT Notes." , retConcurentCount ); AfxMessageBox( mesg ); // ******** OMIT for RELEASE **************** } // ******* Should I automatically switch to NoteList-Mode for Midi-Source ?????? 1/12 ********* return true; }
void NoteGenerator::Add_CalcedNote_to_Record_List( CalcedNote& calcedNote, long endSampleIdx, bool justSwitchingToANewPitch ) { // Only CALLED by Record_Midi_Note() double volumeBoost = m_volumeBoost; // 3.0 ; // 1.5 ************* ADJUST ******************************* long chunkSize = 512; long detectZonePaddingInSamples = chunkSize * 4; // 4[ harly visible] *********** ADJUST ****************** bool showTraceText = false; if( m_tempNoteList == NULL ) // think that calling function does this test { AfxMessageBox( "Add_CalcedNote_to_Record_List FAILED, m_tempNoteList is NULL. " ); return; } MidiNote *nuCalcNote = new MidiNote(); if( nuCalcNote == NULL ) { AfxMessageBox( "Add_CalcedNote_to_Record_List FAILED, could NOT alloc CalcedNote." ); return; } if( m_sampleIdxFirstRecordedNote < 0 ) // not yet written to for this recording session ? { // This will be saved in the file as the DetectZone's start. long detectZoneStart = calcedNote.beginingSampleIdxFile - detectZonePaddingInSamples; if( detectZoneStart < 0 ) detectZoneStart = 0; m_sampleIdxFirstRecordedNote = detectZoneStart; // ***** SLOPPY, but use this for the start of detect zone } short harmonicsMagnitude = calcedNote.detectAvgHarmonicMag; // we use this for AUDIBLE Volumne control in Process_Midi_Event() short detectScoreHarms = calcedNote.detectScoreHarms; // BUT ScoreHarms is what determines volume for PitchScope ??? // and the Britness of the notes on the display. // ********* NOT sure why I change this score, maybe for OLD PitchScope, maybe for when PixelBrightness depended on Score and not HarmMag 2/6/2012 ***************** short nuDetectScoreHarms = (short)( volumeBoost * (double)detectScoreHarms ); // make bigger // ************************************************************************************* // *nuCalcNote = calcedNote; // Copy all of the struct for a ROUGH initialization... nuCalcNote->Copy_In_CalcNotes_Data( calcedNote ); nuCalcNote->endingSampleIdxFile = endSampleIdx; // ...then refine the initialization nuCalcNote->detectScoreHarms = nuDetectScoreHarms; m_tempNoteList->Add_Tail( *nuCalcNote ); if( showTraceText ) { if( justSwitchingToANewPitch ) TRACE( " ...added NEW NOTE [ %d ] to list ( start - stop sampleIdx: %d %d ) Just PITCH-SWITCH \n", nuCalcNote->scalePitch, nuCalcNote->beginingSampleIdxFile, nuCalcNote->endingSampleIdxFile ); else TRACE( " ...added NEW NOTE [ %d ] to list ( start - stop sampleIdx: %d %d ) \n", nuCalcNote->scalePitch, nuCalcNote->beginingSampleIdxFile, nuCalcNote->endingSampleIdxFile ); } }
void CIPFilterDlg::OnBnClickedAppend() { CString strFilePath; if (DialogBrowseFile(strFilePath, GetResString(IDS_IPFILTERFILES))) { CWaitCursor curWait; CString strTempUnzipFilePath; CZIPFile zip; if (zip.Open(strFilePath)) { CZIPFile::File* zfile = zip.GetFile(_T("guarding.p2p")); if (zfile) { _tmakepath(strTempUnzipFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetConfigDir(), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp")); strTempUnzipFilePath.ReleaseBuffer(); if (zfile->Extract(strTempUnzipFilePath)) strFilePath = strTempUnzipFilePath; else { CString strError; strError.Format(_T("Failed to extract IP filter file \"guarding.p2p\" from ZIP file \"%s\"."), strFilePath); AfxMessageBox(strError); } } else { CString strError; strError.Format(_T("Failed to find IP filter file \"guarding.p2p\" in ZIP file \"%s\"."), strFilePath); AfxMessageBox(strError); } zip.Close(); } else { CGZIPFile gz; if (gz.Open(strFilePath)) { _tmakepath(strTempUnzipFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetConfigDir(), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp")); strTempUnzipFilePath.ReleaseBuffer(); // add filename and extension of uncompressed file to temporary file CString strUncompressedFileName = gz.GetUncompressedFileName(); if (!strUncompressedFileName.IsEmpty()) { strTempUnzipFilePath += _T('.'); strTempUnzipFilePath += strUncompressedFileName; } if (gz.Extract(strTempUnzipFilePath)) strFilePath = strTempUnzipFilePath; } gz.Close(); } if (theApp.ipfilter->AddFromFile(strFilePath, true)) { InitIPFilters(); m_ipfilter.Update(-1); } if (!strTempUnzipFilePath.IsEmpty()) _tremove(strTempUnzipFilePath); } }
void CRTEXToolView::OnDraw(CDC* pDC) { //CRTEXToolDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: 在此加入原生資料的描繪程式碼 UINT sizenum = pDoc->m_view_resolution * 5 / uiscale; CPen axisPen; if(!axisPen.CreatePen(PS_DOT,10,RGB(255,0,0))) { // Pen creation failed. Abort the program AfxMessageBox(_T("Pen creation failed drawing a line"), MB_OK); AfxAbort(); } CPen* pOldPen = pDC->SelectObject(&axisPen); // Select the pen CRect cr; CSize size; GetClientRect(&cr); pDC->DPtoLP(&cr); int showaxis = pDoc->m_view_resolution; CPoint ptAxis; pDC->MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(showaxis,0,0); pDC->LineTo(ptAxis.x,ptAxis.y); pDC->Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); pDC->TextOut(ptAxis.x,ptAxis.y,"X"); pDC->MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,showaxis,0); pDC->LineTo(ptAxis.x,ptAxis.y); pDC->Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); pDC->TextOut(ptAxis.x,ptAxis.y,"Y"); pDC->MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,0,showaxis); pDC->LineTo(ptAxis.x,ptAxis.y); pDC->Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); pDC->TextOut(ptAxis.x,ptAxis.y,"Z"); /* pDC->MoveTo(cr.TopLeft().x,0); pDC->LineTo(cr.BottomRight().x,0); pDC->MoveTo(0,cr.BottomRight().y); pDC->LineTo(0,cr.TopLeft().y); pDC->TextOut(cr.TopLeft().x,cr.TopLeft().y,"X vs Y"); */ pDC->SelectObject(pOldPen); CPen axisPen1; if(!axisPen1.CreatePen(PS_DOT,10,RGB(0,0,255))) { // Pen creation failed. Abort the program AfxMessageBox(_T("Pen creation failed drawing a line"), MB_OK); AfxAbort(); } pOldPen = pDC->SelectObject(&axisPen1); // Select the pen pDC->MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(-showaxis,0,0); pDC->LineTo(ptAxis.x,ptAxis.y); pDC->MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,-showaxis,0); pDC->LineTo(ptAxis.x,ptAxis.y); pDC->MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,0,-showaxis); pDC->LineTo(ptAxis.x,ptAxis.y); pDC->TextOut(cr.TopLeft().x,cr.TopLeft().y,"X vs Y vs Z"); pDC->SelectObject(pOldPen); /* CPoint* currentPt; for(auto iter = pDoc->begin() ; iter != pDoc->end() ; ++iter) { currentPt = *iter; pDC->Ellipse(currentPt->x-sizenum,currentPt->y+sizenum,currentPt->x+sizenum,currentPt->y-sizenum); } */ if(!pDoc->m_fgskipRedraw) { sizenum = pDoc->m_view_resolution / uiscale; CString str; int xx,yy,zz; pDoc->savefile.SeekToBegin(); while(pDoc->savefile.ReadString(str)) { if(str.Left(4) =="XYZ:") { xx = atoi((LPCSTR)str.Mid(39,9)); yy = atoi((LPCSTR)str.Mid(49,9)); zz = atoi((LPCSTR)str.Mid(59,9)); CPoint pt; pt = Cpt3DptTo2Dpt(xx,yy,zz); pDC->Ellipse(pt.x-sizenum,pt.y+sizenum,pt.x+sizenum,pt.y-sizenum); //pDC->Ellipse(xx-sizenum,yy+sizenum,xx+sizenum,yy-sizenum); } } pDoc->savefile.SeekToEnd(); } }
BOOL CAStudioApp::InitInstance() { Enable3dControlsStatic(); // Call this when linking to MFC statically AOptions *Options = NULL; // options structure holds INI file options char IniFilePath[MAX_PATH] ; // Set up INI file path { char AppPath[MAX_PATH]; ::GetModuleFileName (NULL, AppPath, MAX_PATH); ::FilePath_GetDriveAndDir (AppPath, AppPath); ::FilePath_AppendName (AppPath, rcstring_Load (AfxGetInstanceHandle (), IDS_INIFILE_NAME), IniFilePath); // Set our INI file ::free ((void *)m_pszProfileName); m_pszProfileName = ::_tcsdup (IniFilePath); } // Parse command line for filename CAStudioCommandLineInfo cmdInfo; ParseCommandLine (cmdInfo); AProject *pProject = NULL; // load program options Options = AOptions_CreateFromFile (IniFilePath); bool KeepGoing = true; if (Options == NULL) { // couldn't load options. Man, we're REALLY out of memory... AfxMessageBox (IDS_OPTIONSERR); return FALSE; } char LoadProjectName[2*MAX_PATH] = ""; // if filename specified on command line, then try to load it if ((cmdInfo.ErrFlag == false) && (cmdInfo.InputFile != "")) { char Ext[MAX_PATH]; if (::ShortPathToLongPath (cmdInfo.InputFile, LoadProjectName) == false) { // ShortPathToLongPath failed for some reason. Use short filename. strcpy (LoadProjectName, cmdInfo.InputFile); } // if no extension, then append .apj if (FilePath_GetExt (LoadProjectName, Ext) == GE_FALSE) { FilePath_SetExt (LoadProjectName, ".apj", LoadProjectName); } pProject = AProject_CreateFromFilename (LoadProjectName); if (pProject == NULL) { // If unable to load, then tell user and ask for Ok/Cancel // Ok will create new project and launch program. // Cancel will exit program. CString ErrMsg; AfxFormatString1 (ErrMsg, IDS_READERROR, LoadProjectName); if (AfxMessageBox (ErrMsg, MB_ICONEXCLAMATION | MB_OKCANCEL) == IDCANCEL) { KeepGoing = false; } } } if (KeepGoing) { CAStudioPropSheet dlg (NULL, &pProject, Options, LoadProjectName); m_pMainWnd = &dlg; dlg.DoModal (); // all done. Save options. AOptions_WriteToFile (Options, IniFilePath); } // Cleanup // Destroy options structure if (Options != NULL) { AOptions_Destroy (&Options); } // Destroy project structure if (pProject != NULL) { AProject_Destroy (&pProject); } geRam_ReportAllocations(); // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
void CConnectRemoteMachineWindow::OnBnClickedOk() { // TODO: Add your control notification handler code here CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); byte ips[4]; if (0 == m_ip.GetAddress(ips[0],ips[1],ips[2],ips[3])) { AfxMessageBox(L"address is error!"); return; } char strip[256]; sprintf_s(strip, 256, "%d.%d.%d.%d", ips[0],ips[1],ips[2],ips[3]); KBEngine::u_int16_t port = 0; CString sport; m_port.GetWindowTextW(sport); char* csport = KBEngine::strutil::wchar2char(sport.GetBuffer(0)); port = atoi(csport); std::string command = strip; command += ":"; command += csport; free(csport); KBEngine::Network::EndPoint* endpoint = KBEngine::Network::EndPoint::ObjPool().createObject(); KBEngine::u_int32_t address; Network::Address::string2ip(strip, address); KBEngine::Network::Address addr(address, htons(port)); if(addr.ip == 0) { ::AfxMessageBox(L"address is error!"); KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint); return; } endpoint->socket(SOCK_STREAM); if (!endpoint->good()) { AfxMessageBox(L"couldn't create a socket\n"); KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint); return; } endpoint->addr(addr); if(endpoint->connect(addr.port, addr.ip) == -1) { CString err; err.Format(L"connect server is error! %d", ::WSAGetLastError()); AfxMessageBox(err); KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint); return; } endpoint->setnonblocking(false); int8 findComponentTypes[] = {LOGGER_TYPE, BASEAPP_TYPE, CELLAPP_TYPE, BASEAPPMGR_TYPE, CELLAPPMGR_TYPE, LOGINAPP_TYPE, DBMGR_TYPE, BOTS_TYPE, UNKNOWN_COMPONENT_TYPE}; int ifind = 0; while(true) { int8 findComponentType = findComponentTypes[ifind++]; if(findComponentType == UNKNOWN_COMPONENT_TYPE) { //INFO_MSG("Componentbridge::process: not found %s, try again...\n", // COMPONENT_NAME_EX(findComponentType)); break; } KBEngine::Network::Bundle bhandler; bhandler.newMessage(KBEngine::MachineInterface::onFindInterfaceAddr); KBEngine::MachineInterface::onFindInterfaceAddrArgs7::staticAddToBundle(bhandler, KBEngine::getUserUID(), KBEngine::getUsername(), CONSOLE_TYPE, g_componentID, (COMPONENT_TYPE)findComponentType, 0, 0); endpoint->send(&bhandler); KBEngine::Network::TCPPacket packet; packet.resize(65535); endpoint->setnonblocking(true); KBEngine::sleep(300); packet.wpos(endpoint->recv(packet.data(), 65535)); while(packet.length() > 0) { MachineInterface::onBroadcastInterfaceArgs24 args; try { args.createFromStream(packet); }catch(MemoryStreamException &) { goto END; } INFO_MSG(fmt::format("CConnectRemoteMachineWindow::OnBnClickedOk: found {}, addr:{}:{}\n", COMPONENT_NAME_EX((COMPONENT_TYPE)args.componentType), inet_ntoa((struct in_addr&)args.intaddr), ntohs(args.intport))); Components::getSingleton().addComponent(args.uid, args.username.c_str(), (KBEngine::COMPONENT_TYPE)args.componentType, args.componentID, args.globalorderid, args.grouporderid, args.intaddr, args.intport, args.extaddr, args.extport, args.extaddrEx, args.pid, args.cpu, args.mem, args.usedmem, args.extradata, args.extradata1, args.extradata2, args.extradata3); } } END: dlg->updateTree(); KBEngine::Network::EndPoint::ObjPool().reclaimObject(endpoint); wchar_t* wcommand = KBEngine::strutil::char2wchar(command.c_str()); bool found = false; std::deque<CString>::iterator iter = m_historyCommand.begin(); for(; iter != m_historyCommand.end(); iter++) { if((*iter) == wcommand) { found = true; break; } } if(!found) { m_historyCommand.push_front(wcommand); if(m_historyCommand.size() > 10) m_historyCommand.pop_back(); saveHistory(); } free(wcommand); OnOK(); }
void CAbfTraceIdealization::ExportLocalExtremaHist() { FILE *fpOut; CString sAbfFileName; CString sMessage="Can not open the file. Please check if this file is being used by other applications."; CFileDialog aFileDlg( false, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, NULL, NULL ); char* pch="text file (*.txt)\0*.txt\0\0"; aFileDlg.m_ofn.lpstrFilter=pch; aFileDlg.m_ofn.lpstrTitle="Export the local extrema of the trace segments"; float fTemp=0.f; float fAmp=0.f; float fCounts=0.f; float bLargestLine=true; int i,j,nSize; if(aFileDlg.DoModal()==IDOK) { sAbfFileName=aFileDlg.GetPathName(); if(!(fpOut=fopen(sAbfFileName,"wb"))) { // AfxFormatString1(sMessage,-1,sAbfFileName); AfxMessageBox(sMessage,MB_OK,0); } else { for(i=0;i<100000;i++) { bLargestLine=true; for(j=0;j<m_nMaxLevel+1;j++) { fAmp=m_vstructSegMinimaHist[j].fMin+m_vstructSegMinimaHist[j].fInterval*float(i); nSize=m_vstructSegMinimaHist[j].vfHist.size(); if(i<nSize) { fCounts=m_vstructSegMinimaHist[j].vfHist[i]; bLargestLine=false; } else { fCounts=0.; } fprintf(fpOut," %10.2f %16.2f", fAmp, fCounts); } for(j=0;j<m_nMaxLevel+1;j++) { fAmp=m_vstructSegMaximaHist[j].fMin+m_vstructSegMaximaHist[j].fInterval*float(i); nSize=m_vstructSegMaximaHist[j].vfHist.size(); if(i<nSize) { fCounts=m_vstructSegMaximaHist[j].vfHist[i]; bLargestLine=false; } else { fCounts=0.; } fprintf(fpOut," %10.2f %16.2f", fAmp, fCounts); } fprintf(fpOut,"\n"); if(bLargestLine) break; } fclose(fpOut); } } }
BOOL CKLinePrintApp::InitInstance() { #if 0 // 维持网络连接/会话 Net net("192.168.1.1:8080"); net.start(); // 执行命令 CommandExecutor ce(&net); string ret = ce.Execute("login"); // 接收数据 DataHandler dh(&net); // 初始化网络连接 // 创建线程,发起并维持连接 // CLoginDialog loginDlg; if(loginDlg.DoModal()!=IDOK) { return FALSE; } CommandExecutor ce(); string result = ce.Execute("login:oscar,12345,sr"); #endif // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // 初始化 OLE 库 if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("Oscar")); LoadStdProfileSettings(4); // 加载标准 INI 文件选项(包括 MRU) InitContextMenuManager(); InitKeyboardManager(); // 注册应用程序的文档模板。文档模板 // 将用作文档、框架窗口和视图之间的连接 CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CKLinePrintDoc), RUNTIME_CLASS(CMainFrame), // 主 SDI 框架窗口 RUNTIME_CLASS(CKLinePrintView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // 分析标准外壳命令、DDE、打开文件操作的命令行 CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // 调度在命令行中指定的命令。如果 // 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。 if (!ProcessShellCommand(cmdInfo)) return FALSE; CalendarGenerator cg; cg.Generate("C:\\FutureData\\ZZ", m_cal); // 读入账户/品种信息 EXCHANGE.SetBalance(Utility::ReadBalance()); TP = Utility::ReadExchangeConfig(); // 设置默认交易日志文件 EXCHANGE.SetLogFile(Utility::GetProgramPath() + "log\\manual.log.txt"); srand(time(0)); // 加载回放配置并生成日历 m_PlaybackConfig = Utility::ReadPlaybackConfig(); LoadPlaybackCalendar(m_PlaybackConfig); // 自动打开上次的文件 char path[MAX_PATH]; ::GetPrivateProfileStringA("Files","Current","", path, sizeof(path), (Utility::GetProgramPath() + "klinep.ini").c_str()); CKLinePrintDoc* pDoc = NULL; if(strlen(path)) { pDoc = (CKLinePrintDoc*)OpenDocumentFile(CString(path)); pDoc->LoadNextDay(); } // 唯一的一个窗口已初始化,因此显示它并对其进行更新 m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // 仅当具有后缀时才调用 DragAcceptFiles // 在 SDI 应用程序中,这应在 ProcessShellCommand 之后发生 return TRUE; }
BOOL CMlsPrint::Print(CMlsPrintInfo* pInfo, CWnd* pParent) { BOOL fSuccess = FALSE; ASSERT(pInfo != NULL); m_pInfo = pInfo; m_pParent = pParent; if (OnPreparePrinting()) { fSuccess = TRUE; ASSERT(m_pInfo->m_pPD->m_pd.hDC != NULL); CDC dcPrint; dcPrint.Attach(m_pInfo->m_pPD->m_pd.hDC); dcPrint.m_bPrinting = TRUE; m_pDC = &dcPrint; OnBeginPrinting(); OnCreatePrintingDialog(); dcPrint.SetAbortProc(MlsPrintAbortProc); CString docTitle; GetTitle(docTitle); if (docTitle.GetLength() > 31) { docTitle.ReleaseBuffer(31); } DOCINFO docInfo; memset(&docInfo, 0, sizeof(DOCINFO)); docInfo.cbSize = sizeof(DOCINFO); docInfo.lpszDocName = docTitle; // docInfo.lpszOutput = NULL; if (dcPrint.StartDoc(&docInfo) != SP_ERROR) { UINT nEndPage = m_pInfo->GetToPage(); UINT nStartPage = m_pInfo->GetFromPage(); // Guarantee values are in the valid range if (nEndPage < m_pInfo->GetMinPage()) nEndPage = m_pInfo->GetMinPage(); if (nEndPage > m_pInfo->GetMaxPage()) nEndPage = m_pInfo->GetMaxPage(); if (nStartPage < m_pInfo->GetMinPage()) nStartPage = m_pInfo->GetMinPage(); if (nStartPage > m_pInfo->GetMaxPage()) nStartPage = m_pInfo->GetMaxPage(); int nStep = (nEndPage >= nStartPage) ? 1 : -1; nEndPage = (nEndPage == 0xffff) ? 0xffff : nEndPage + nStep; BOOL bError = FALSE; for (m_pInfo->m_nCurPage = nStartPage; !bError && m_pInfo->m_nCurPage != nEndPage; m_pInfo->m_nCurPage += nStep) { OnPrepareDC(); if (!m_pInfo->m_bContinuePrinting) { break; } // Set up drawing rect to entire page (in logical coordinates) m_pInfo->m_rectDraw.SetRect(0, 0, dcPrint.GetDeviceCaps(HORZRES), dcPrint.GetDeviceCaps(VERTRES)); dcPrint.DPtoLP(&m_pInfo->m_rectDraw); OnUpdatePrintingDialog(); VERIFY(dcPrint.StartPage()); OnPrint(); if (dcPrint.EndPage() < 0) { bError = TRUE; } } if (!bError) { dcPrint.EndDoc(); } } else { AfxMessageBox(AFX_IDP_FAILED_TO_START_PRINT); } OnEndPrinting(); OnReleasePrintingDialog(); m_pDC = NULL; } m_pInfo = NULL; return fSuccess; }
BOOL CMFCTestApp::InitInstance() { // 응용 프로그램 매니페스트가 ComCtl32.dll 버전 6 이상을 사용하여 비주얼 스타일을 // 사용하도록 지정하는 경우, Windows XP 상에서 반드시 InitCommonControlsEx()가 필요합니다. // InitCommonControlsEx()를 사용하지 않으면 창을 만들 수 없습니다. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 응용 프로그램에서 사용할 모든 공용 컨트롤 클래스를 포함하도록 // 이 항목을 설정하십시오. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // OLE 라이브러리를 초기화합니다. if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(); // RichEdit 컨트롤을 사용하려면 AfxInitRichEdit2()가 있어야 합니다. // AfxInitRichEdit2(); // 표준 초기화 // 이들 기능을 사용하지 않고 최종 실행 파일의 크기를 줄이려면 // 아래에서 필요 없는 특정 초기화 // 루틴을 제거해야 합니다. // 해당 설정이 저장된 레지스트리 키를 변경하십시오. // TODO: 이 문자열을 회사 또는 조직의 이름과 같은 // 적절한 내용으로 수정해야 합니다. SetRegistryKey(_T("로컬 응용 프로그램 마법사에서 생성된 응용 프로그램")); LoadStdProfileSettings(4); // MRU를 포함하여 표준 INI 파일 옵션을 로드합니다. InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // 응용 프로그램의 문서 템플릿을 등록합니다. 문서 템플릿은 // 문서, 프레임 창 및 뷰 사이의 연결 역할을 합니다. CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_MFCTestTYPE, RUNTIME_CLASS(CMFCTestDoc), RUNTIME_CLASS(CChildFrame), // 사용자 지정 MDI 자식 프레임입니다. RUNTIME_CLASS(CMFCTestView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // 주 MDI 프레임 창을 만듭니다. CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME)) { delete pMainFrame; return FALSE; } m_pMainWnd = pMainFrame; // 접미사가 있을 경우에만 DragAcceptFiles를 호출합니다. // MDI 응용 프로그램에서는 m_pMainWnd를 설정한 후 바로 이러한 호출이 발생해야 합니다. // 표준 셸 명령, DDE, 파일 열기에 대한 명령줄을 구문 분석합니다. CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // 명령줄에 지정된 명령을 디스패치합니다. // 응용 프로그램이 /RegServer, /Register, /Unregserver 또는 /Unregister로 시작된 경우 FALSE를 반환합니다. if (!ProcessShellCommand(cmdInfo)) return FALSE; // 주 창이 초기화되었으므로 이를 표시하고 업데이트합니다. pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; }
//鼠标左键单击响应函数 void CChildView::OnLButtonDown(UINT nFlags, CPoint point) { char bufPos[50]; sprintf(bufPos,"你单击了点X:%d,Y:%d",point.x,point.y); AfxMessageBox(bufPos); }
void CLogin::OnBnClickedOk2() { // TODO: 在此添加控件通知处理程序代码 USES_CONVERSION; CString user, passwd; m_user.GetWindowText(user); m_passwd.GetWindowText(passwd); MD5tool MD5tool; passwd = MD5tool.PutMD5(passwd); cJSON *rootback, *data; rootback = cJSON_CreateObject(); cJSON_AddStringToObject(rootback, "Type", "21"); cJSON_AddItemToObject(rootback, "Data", data = cJSON_CreateObject()); cJSON_AddStringToObject(data, "user", T2A(user)); cJSON_AddStringToObject(data, "passwd", T2A(passwd)); char* back = cJSON_Print(rootback); cJSON_Delete(rootback); //cJSON_Delete(data); WORD wVersion = MAKEWORD(2, 2); WSADATA wsadata; if ((::WSAStartup(wVersion, &wsadata)) == SOCKET_ERROR) { return; } if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 2) { WSACleanup(); return; } SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); int port = 12126; SOCKADDR_IN addSock; inet_pton(AF_INET, theApp.Getip(), &addSock.sin_addr.S_un.S_addr); addSock.sin_family = AF_INET; addSock.sin_port = htons(port); int Ret = connect(sockSrv, (SOCKADDR*)&addSock, sizeof(SOCKADDR)); if (Ret != 0) { WSACleanup(); return; } CString Socketdata; Socketdata.Format(_T("%s"), CStringW(back)); theApp.SocketSend(sockSrv, Socketdata); //send(sockSrv, back, strlen(back) + 1, 0); free(back); /*char revData[100000]; int ret = recv(sockSrv, revData, 100000, 0);*/ CString Sockrec = theApp.SocketRecv(sockSrv); if (Sockrec == CString()) return; /* if (ret == 0) { // 此处连接WM_PAINT显示,待实现 //MessageBox((HWND)pM, _T("错误 7. 请检查网络连接!"), _T("程序异常"), MB_OK); return; } if (ret == SOCKET_ERROR) return; revData[ret] = '\0';*/ cJSON * root; root = cJSON_Parse(T2A(Sockrec)); if (NULL == root) { //错误处理 return; } //size = cJSON_GetArraySize(root); cJSON * pSub = cJSON_GetObjectItem(root, "Type"); char* type = pSub->valuestring; CString Type, Data; Type.Format(_T("%s"), CStringW(type)); pSub = cJSON_GetObjectItem(root, "Data"); type = pSub->valuestring; Data.Format(_T("%s"), CStringW(type)); cJSON_Delete(root); if (Type.CompareNoCase(_T("21")) == 0) { if (Data.CompareNoCase(_T("OK")) != 0) { closesocket(sockSrv); WSACleanup(); m_user.SetWindowText(_T("")); m_passwd.SetWindowText(_T("")); AfxMessageBox(_T("用户名或密码错误!")); return; } } else { closesocket(sockSrv); WSACleanup(); m_user.SetWindowText(_T("")); m_passwd.SetWindowText(_T("")); AfxMessageBox(_T("用户名或密码错误!")); return; } theApp.User = user; closesocket(sockSrv); WSACleanup(); CDialogEx::OnOK(); }
// Process context menu items... BOOL CStatisticsTree::OnCommand(WPARAM wParam, LPARAM /*lParam*/) { switch (wParam) { case MP_STATTREE_RESET: { if(AfxMessageBox(GetResString(IDS_STATS_MBRESET_TXT), MB_YESNO | MB_ICONEXCLAMATION) == IDNO) break; thePrefs.ResetCumulativeStatistics(); AddLogLine(false, GetResString(IDS_STATS_NFORESET)); theApp.emuledlg->statisticswnd->ShowStatistics(); CString myBuffer; myBuffer.Format(GetResString(IDS_STATS_LASTRESETSTATIC), thePrefs.GetStatsLastResetStr(false)); GetParent()->GetDlgItem(IDC_STATIC_LASTRESET)->SetWindowText(myBuffer); break; } case MP_STATTREE_RESTORE: { if (AfxMessageBox(GetResString(IDS_STATS_MBRESTORE_TXT), MB_YESNO | MB_ICONQUESTION) == IDNO) break; if(!thePrefs.LoadStats(1)) LogError(LOG_STATUSBAR, GetResString(IDS_ERR_NOSTATBKUP)); else { AddLogLine(false, GetResString(IDS_STATS_NFOLOADEDBKUP)); CString myBuffer; myBuffer.Format(GetResString(IDS_STATS_LASTRESETSTATIC), thePrefs.GetStatsLastResetStr(false)); GetParent()->GetDlgItem(IDC_STATIC_LASTRESET)->SetWindowText(myBuffer); } break; } case MP_STATTREE_EXPANDMAIN: { SetRedraw(false); ExpandAll(true); goto lblSaveExpanded; } case MP_STATTREE_EXPANDALL: { SetRedraw(false); ExpandAll(); goto lblSaveExpanded; } case MP_STATTREE_COLLAPSEALL: { SetRedraw(false); CollapseAll(); lblSaveExpanded: thePrefs.SetExpandedTreeItems(GetExpandedMask()); SetRedraw(true); break; } case MP_STATTREE_COPYSEL: case MP_STATTREE_COPYVIS: case MP_STATTREE_COPYALL: { CopyText(wParam); break; } case MP_STATTREE_HTMLCOPYSEL: case MP_STATTREE_HTMLCOPYVIS: case MP_STATTREE_HTMLCOPYALL: { CopyHTML(wParam); break; } case MP_STATTREE_HTMLEXPORT: { ExportHTML(); break; } } return true; }
void CGnucleusDoc::ConnectCore() { m_autCore = new CAutCore; if(!m_autCore->CreateDispatch("GnucCOM.Core")) { AfxMessageBox("Could not load GnucDNA"); return; } // Make sure version of core is same or newer than what we built with CString CoreVersion = m_autCore->GetCoreVersion(); CoreVersion.Remove('.'); CString BuildVersion = BUILD_CORE_VERSION; BuildVersion.Remove('.'); if(atoi(CoreVersion) < atoi(BuildVersion)) { AfxMessageBox("GnucDNA " + CString(BUILD_CORE_VERSION) + " or higher needed, please update"); return; } // Attach prefs object m_autPrefs = new CAutPrefs; m_autPrefs->AttachDispatch( m_autCore->GetIPrefs(), false ); // Attach network object m_autNetwork = new CAutNetwork; m_autNetwork->AttachDispatch( m_autCore->GetINetwork(), false ); // Attach cache object m_autCache = new CAutCache; m_autCache->AttachDispatch( m_autCore->GetICache(), false ); // Attach meta object m_autMeta = new CAutMeta; m_autMeta->AttachDispatch( m_autCore->GetIMeta(), false ); // Attach share object m_autShare = new CAutShare; m_autShare->AttachDispatch( m_autCore->GetIShare(), false ); // Attach share object m_autSearch = new CAutSearch; m_autSearch->AttachDispatch( m_autCore->GetISearch(), false ); // Attach download object m_autDownload = new CAutDownload; m_autDownload->AttachDispatch( m_autCore->GetIDownload(), false ); // Attach upload object m_autUpload = new CAutUpload; m_autUpload->AttachDispatch( m_autCore->GetIUpload(), false ); // Attach update object m_autUpdate = new CAutUpdate; m_autUpdate->AttachDispatch( m_autCore->GetIUpdate(), false ); // Attach chat object m_autChat = new CAutChat; m_autChat->AttachDispatch( m_autCore->GetIChat(), false ); // Network event object and establish a connection between source and sink. m_autNetworkSink = new CAutNetworkSink(this); AfxConnectionAdvise(m_autNetwork->m_lpDispatch, IID_INetworkEvent, m_autNetworkSink->GetIDispatch(false), false, &m_NetEventCookie); // Share event object and establish a connection between source and sink. m_autShareSink = new CAutShareSink(this); AfxConnectionAdvise(m_autShare->m_lpDispatch, IID_IShareEvent, m_autShareSink->GetIDispatch(false), false, &m_ShareEventCookie); // Share event object and establish a connection between source and sink. m_autSearchSink = new CAutSearchSink(this); AfxConnectionAdvise(m_autSearch->m_lpDispatch, IID_ISearchEvent, m_autSearchSink->GetIDispatch(false), false, &m_SearchEventCookie); // Download event object and establish a connection between source and sink. m_autDownloadSink = new CAutDownloadSink(this); AfxConnectionAdvise(m_autDownload->m_lpDispatch, IID_IDownloadEvent, m_autDownloadSink->GetIDispatch(false), false, &m_DownloadEventCookie); // Upload event object and establish a connection between source and sink. m_autUploadSink = new CAutUploadSink(this); AfxConnectionAdvise(m_autUpload->m_lpDispatch, IID_IUploadEvent, m_autUploadSink->GetIDispatch(false), false, &m_UploadEventCookie); // Update event object and establish a connection between source and sink. m_autUpdateSink = new CAutUpdateSink(this); AfxConnectionAdvise(m_autUpdate->m_lpDispatch, IID_IUpdateEvent, m_autUpdateSink->GetIDispatch(false), false, &m_UpdateEventCookie); // Chat event object and establish a connection between source and sink. m_autChatSink = new CAutChatSink(this); AfxConnectionAdvise(m_autChat->m_lpDispatch, IID_IChatEvent, m_autChatSink->GetIDispatch(false), false, &m_ChatEventCookie); }
// ************************************************************************** // OnApply () // // Description: // Apply button event handler. // // Parameters: // none // // Returns: // void // ************************************************************************** void CKServerGetErrorStringDlg::OnApply () { // Initialize some variables needed for request: HRESULT hr = E_FAIL; DWORD dwError = -1; LPWSTR pszError = NULL; bool bIsHex = false; TCHAR cChar; // Look for invalid characters in error code. Loop over // all characters in error code string: for (int i = 0; i < m_strErrorCode.GetLength (); i++) { // Get current character: cChar = m_strErrorCode [i]; // All digits are valid. Other characters may be valid. if (!_istdigit (cChar)) { // If first non-digit character is "x" or "X", then // we are probably looking at a hexidecimal value. In // that case, accept the character, set the bIsHex flag, // and continue checking the string. if (!bIsHex && (cChar == _T('x') || cChar == _T('X'))) bIsHex = true; // If we have seen the "X", and this character is a hex // digit, then it is valid. else if (bIsHex && _istxdigit (cChar)) continue; // Else we have seen the "X", but current character is not // a valid hex digit. Show message box that tells user error // code is invalid the return. else { // "Invalid hexadecimal number." AfxMessageBox (IDS_INVALIDHEXNUMBER); return; } } } // If we make it here, then error code has a valid format. // Convert string to number. if (bIsHex) _stscanf (m_strErrorCode, _T("%X"), &dwError); else dwError = (DWORD) _ttol (m_strErrorCode); // Get the error string: hr = m_pIServer->GetErrorString (dwError, 0, &pszError); // If request succeeded, process the results: if (SUCCEEDED (hr) && pszError != NULL) { m_strErrorDescription = pszError; } // Else if request failed, inform user of problem: else { CString strMsg; // "The server could not resolve this error code." strMsg.Format (IDS_UNABLETORESOLVEERRORCODE); AfxMessageBox (strMsg); } // Free memory server allocated for error string: if (pszError) CoTaskMemFree (pszError); // Reformat the error code as a hex number: m_strErrorCode.Format (_T("0x%08X"), dwError); // Update the controls to show reformatted code and error string: UpdateData (FALSE); }
BOOL CFriendListCtrl::OnCommand(WPARAM wParam, LPARAM /*lParam*/) { wParam = LOWORD(wParam); CFriend* cur_friend = NULL; int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED); if (iSel != -1) cur_friend = (CFriend*)GetItemData(iSel); switch (wParam) { case MP_MESSAGE: if (cur_friend) { theApp.emuledlg->chatwnd->StartSession(cur_friend->GetClientForChatSession()); } break; case MP_REMOVEFRIEND: if (cur_friend) { theApp.friendlist->RemoveFriend(cur_friend); // auto select next item after deleted one. if (iSel < GetItemCount()) { SetSelectionMark(iSel); SetItemState(iSel, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); } theApp.emuledlg->chatwnd->UpdateSelectedFriendMsgDetails(); } break; case MP_ADDFRIEND:{ CAddFriend dialog2; dialog2.DoModal(); break; } case MP_DETAIL: case MPG_ALTENTER: case IDA_ENTER: if (cur_friend) ShowFriendDetails(cur_friend); break; case MP_SHOWLIST: if (cur_friend) { if (cur_friend->GetLinkedClient(true)) cur_friend->GetLinkedClient()->RequestSharedFileList(); else { CUpDownClient* newclient = new CUpDownClient(0, cur_friend->m_nLastUsedPort, cur_friend->m_dwLastUsedIP, 0, 0, true); newclient->SetUserName(cur_friend->m_strName); //Xman Code Improvement don't search new generated clients in lists /* theApp.clientlist->AddClient(newclient); */ theApp.clientlist->AddClient(newclient,true); //Xman end newclient->RequestSharedFileList(); } } break; case MP_FRIENDSLOT: if (cur_friend) { bool bIsAlready = cur_friend->GetFriendSlot(); theApp.friendlist->RemoveAllFriendSlots(); if (!bIsAlready) { //Xman cur_friend->SetFriendSlot(true); //Xman friend visualization UpdateFriend(iSel,cur_friend); //Xman end } //Xman } break; // - show requested files (sivka/Xman) case MP_LIST_REQUESTED_FILES: { if (cur_friend && cur_friend->GetLinkedClient()) { cur_friend->GetLinkedClient()->ShowRequestedFiles(); } break; } //Xman end // MORPH START - Added by Commander, Friendlinks [emulEspaa] - added by zz_fly case MP_PASTE: { CString link = theApp.CopyTextFromClipboard(); link.Trim(); if ( link.IsEmpty() ) break; try{ CED2KLink* pLink = CED2KLink::CreateLinkFromUrl(link); if (pLink && pLink->GetKind() == CED2KLink::kFriend ) { // Better with dynamic_cast, but no RTTI enabled in the project CED2KFriendLink* pFriendLink = static_cast<CED2KFriendLink*>(pLink); uchar userHash[16]; pFriendLink->GetUserHash(userHash); if ( ! theApp.friendlist->IsAlreadyFriend(userHash) ) theApp.friendlist->AddFriend(userHash, 0U, 0U, 0U, 0U, pFriendLink->GetUserName(), 1U); else { CString msg; msg.Format(GetResString(IDS_USER_ALREADY_FRIEND), pFriendLink->GetUserName()); AddLogLine(true, msg); } } if(pLink) delete pLink; //zz_fly :: memleak :: thanks DolphinX } catch(CString strError){ AfxMessageBox(strError); } } break; case MP_GETFRIENDED2KLINK: { CString sCompleteLink; if ( cur_friend && cur_friend->HasUserhash() ) { CString sLink; CED2KFriendLink friendLink(cur_friend->m_strName, cur_friend->m_abyUserhash); friendLink.GetLink(sLink); if ( !sCompleteLink.IsEmpty() ) sCompleteLink.Append(_T("\r\n")); sCompleteLink.Append(sLink); } if ( !sCompleteLink.IsEmpty() ) theApp.CopyTextToClipboard(sCompleteLink); } break; case MP_GETHTMLFRIENDED2KLINK: { CString sCompleteLink; if ( cur_friend && cur_friend->HasUserhash() ) { CString sLink; CED2KFriendLink friendLink(cur_friend->m_strName, cur_friend->m_abyUserhash); friendLink.GetLink(sLink); sLink = _T("<a href=\"") + sLink + _T("\">") + StripInvalidFilenameChars(cur_friend->m_strName) + _T("</a>"); if ( !sCompleteLink.IsEmpty() ) sCompleteLink.Append(_T("\r\n")); sCompleteLink.Append(sLink); } if ( !sCompleteLink.IsEmpty() ) theApp.CopyTextToClipboard(sCompleteLink); } break; // MORPH END - Added by Commander, Friendlinks [emulEspaa] case MP_FIND: OnFindStart(); break; } return true; }
void CRTEXToolView::DrawArm(int x1, int y1,int z1,float m_fYaw,float theta1,float theta2) { UINT sizenum = pDoc->m_view_resolution / uiscale; CClientDC pDC(this); OnPrepareDC(&pDC); CPoint pt,ptAxis; float m_fScaraRobot_L1 = 325; float m_fScaraRobot_L2 = 225; float m_fScaraRobot_Height_Asix1 = (290+74); float fXpos=0,fYpos=0,fZpos=0; int xJ1, yJ1,zJ1,xJ2, yJ2,zJ2,xJ3, yJ3,zJ3; /////////////////////////////////////////////////////////////// CPen axisPen2; if(!axisPen2.CreatePen(PS_SOLID ,500,RGB(255,255,255))) { // Pen creation failed. Abort the program AfxMessageBox(_T("Pen creation failed drawing a line"), MB_OK); AfxAbort(); } CPen* pOldPen = pDC.SelectObject(&axisPen2); // Select the pen /////////////////////////////////////////////////////////////// pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(xJ1_backup,yJ1_backup,zJ1_backup); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); ptAxis = Cpt3DptTo2Dpt(xJ2_backup,yJ2_backup,zJ2_backup); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); ptAxis = Cpt3DptTo2Dpt(xJ3_backup,yJ3_backup,zJ3_backup); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); ptAxis = Cpt3DptTo2Dpt(x1_backup,y1_backup,z1_backup); pDC.LineTo(ptAxis.x,ptAxis.y); // pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum/5,ptAxis.y-sizenum/5); pDC.SelectObject(pOldPen); ////////////////draw xyz back ////////////////////////////////////// CPen axisPen; if(!axisPen.CreatePen(PS_DOT,10,RGB(255,0,0))) { // Pen creation failed. Abort the program AfxMessageBox(_T("Pen creation failed drawing a line"), MB_OK); AfxAbort(); } pOldPen = pDC.SelectObject(&axisPen); // Select the pen int showaxis = pDoc->m_view_resolution; // CPoint ptAxis; pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(showaxis,0,0); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); pDC.TextOut(ptAxis.x,ptAxis.y,"X"); pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,showaxis,0); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); pDC.TextOut(ptAxis.x,ptAxis.y,"Y"); pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,0,showaxis); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); pDC.TextOut(ptAxis.x,ptAxis.y,"Z"); pDC.SelectObject(pOldPen); CPen axisPen1; if(!axisPen1.CreatePen(PS_DOT,10,RGB(0,0,255))) { // Pen creation failed. Abort the program AfxMessageBox(_T("Pen creation failed drawing a line"), MB_OK); AfxAbort(); } pOldPen = pDC.SelectObject(&axisPen1); // Select the pen pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(-showaxis,0,0); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,-showaxis,0); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(0,0,-showaxis); pDC.LineTo(ptAxis.x,ptAxis.y); // pDC.TextOut(cr.TopLeft().x,cr.TopLeft().y,"X vs Y vs Z"); pDC.SelectObject(pOldPen); ////////////////draw xyz back end////////////////////////////////////// /////////////////////////////////////////////////////////////// CPen axisPen3; if(!axisPen3.CreatePen(PS_SOLID ,500,RGB(50,100,150))) { // Pen creation failed. Abort the program AfxMessageBox(_T("Pen creation failed drawing a line"), MB_OK); AfxAbort(); } CPen* pOldPen3 = pDC.SelectObject(&axisPen3); // Select the pen /////////////////////////////////////////////////////////////// xJ1 = 0 ; yJ1 = 0 ; zJ1 = 0 +(int)(0.5 + (m_fScaraRobot_Height_Asix1 * 1000)); fXpos = (float)(m_fScaraRobot_L1 * cos((theta1)*M_PI/180)); fYpos = (float)(m_fScaraRobot_L1 * sin((theta1)*M_PI/180)); xJ2 = xJ1+(int)(0.5 + (fXpos * 1000)); yJ2 = yJ1+(int)(0.5 + (fYpos * 1000)); zJ2 = zJ1; fXpos = (float)(m_fScaraRobot_L2 * cos((theta1+theta2)*M_PI/180)); fYpos = (float)(m_fScaraRobot_L2 * sin((theta1+theta2)*M_PI/180)); xJ3 = xJ2+(int)(0.5 + (fXpos * 1000)); yJ3 = yJ2+(int)(0.5 + (fYpos * 1000)); zJ3 = zJ2; pDC.MoveTo(0,0); ptAxis = Cpt3DptTo2Dpt(xJ1,yJ1,zJ1); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); ptAxis = Cpt3DptTo2Dpt(xJ2,yJ2,zJ2); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); ptAxis = Cpt3DptTo2Dpt(xJ3,yJ3,zJ3); pDC.LineTo(ptAxis.x,ptAxis.y); pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); ptAxis = Cpt3DptTo2Dpt(x1,y1,z1); pDC.LineTo(ptAxis.x,ptAxis.y); // pDC.Ellipse(ptAxis.x-sizenum,ptAxis.y+sizenum,ptAxis.x+sizenum,ptAxis.y-sizenum); pDC.SelectObject(pOldPen3); xJ1_backup = xJ1; yJ1_backup = yJ1; zJ1_backup = zJ1; xJ2_backup = xJ2; yJ2_backup = yJ2; zJ2_backup = zJ2; xJ3_backup = xJ3; yJ3_backup = yJ3; zJ3_backup = zJ3; x1_backup = x1; y1_backup = y1; z1_backup = z1; }
void CALLBACK CDirectSoundPlayer::TimerCallBack(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) { HRESULT hr; LPVOID lpbuf1 = NULL; LPVOID lpbuf2 = NULL; LPBYTE lynxpointer = NULL; LPBYTE tmppointer = NULL; DWORD lynxbytesavail =0; DWORD dwsize1 = 0; DWORD dwsize2 = 0; DWORD dwbyteswritten1 = 0; DWORD dwbyteswritten2 = 0; CDirectSoundPlayer *dsp = (CDirectSoundPlayer*) dwUser; // Check for reentrance if (InterlockedExchange (&(dsp->m_InService), TRUE) == FALSE) { // Not reentered, proceed normally DWORD writelen=dsp->CalcWriteSize(); if(writelen) { // Lock required amount of buffer hr = dsp->m_BufferSecondary->Lock (dsp->m_WriteCursor, writelen, &lpbuf1, &dwsize1, &lpbuf2, &dwsize2,0); if (hr == DS_OK && writelen>0) { // We only write the available amount of lynx data into the sound buffers. // If there is underrun then the last byte is repeated. // If there is overrun then it is truncated // Fetch temp lynx pointer lynxpointer=dsp->m_LynxBufferBasePtr; lynxbytesavail=*dsp->m_LynxBufferIndexPtr; dwbyteswritten1 = dwsize1; tmppointer=(LPBYTE)lpbuf1; for(DWORD loop=0;loop<dwsize1;loop++) { *(tmppointer++)=*lynxpointer; if(lynxbytesavail) { lynxbytesavail--; lynxpointer++; } else { // if(*dsp->m_LynxBufferIndexPtr>2) lynxpointer-=2; else lynxpointer-=*dsp->m_LynxBufferIndexPtr; // if(*dsp->m_LynxBufferIndexPtr>2) lynxbytesavail=2; else lynxbytesavail=*dsp->m_LynxBufferIndexPtr; } } // Second write required? if (lpbuf2) { dwbyteswritten2 = dwsize2; tmppointer=(LPBYTE)lpbuf2; for(DWORD loop=0;loop<dwsize2;loop++) { *(tmppointer++)=*lynxpointer; if(lynxbytesavail) { lynxbytesavail--; lynxpointer++; } else { // if(*dsp->m_LynxBufferIndexPtr>2) lynxpointer-=2; else lynxpointer-=*dsp->m_LynxBufferIndexPtr; // if(*dsp->m_LynxBufferIndexPtr>2) lynxbytesavail=2; else lynxbytesavail=*dsp->m_LynxBufferIndexPtr; } } } // Update our buffer offset and unlock sound buffer dsp->m_WriteCursor = (dsp->m_WriteCursor + dwbyteswritten1 + dwbyteswritten2) % dsp->m_LynxBufferLength; dsp->m_BufferSecondary->Unlock (lpbuf1, dwbyteswritten1, lpbuf2, dwbyteswritten2); // Now update the lynx variables *dsp->m_LynxBufferIndexPtr=0; } else { CString message ("CDirectSoundPlayer::TimerCallBack - Lock Error: \n"); message += DXAppErrorToString (hr); AfxMessageBox (message); dsp->Stop(); } } // Reset reentrancy semaphore InterlockedExchange (&(dsp->m_InService), FALSE); } }
void CBatchSNDlg::OnBnClickedCalibrationPointReport() { CString Product_Head_File_Name; CString strFilter; CString strFilename; CString strTemp; CString RegisterName; CString RegisterID; CString logstr; _variant_t temp_variant; _Application app; Workbooks books; _Workbook book; Worksheets sheets; _Worksheet sheet; Range range; Range rgMyRge1, rgMyRge2; COleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); int CurrentRow; if (!app.CreateDispatch(_T("Excel.Application"),NULL)) { AfxMessageBox(_T("Create Excel false!")); return; } //遍历所有行 strFilename=g_strExePth+_T("Calibration Sensor Report.xls"); books.AttachDispatch(app.GetWorkbooks()); book.AttachDispatch(books.Add(_variant_t(strFilename))); sheets.AttachDispatch(book.GetWorksheets()); sheet.AttachDispatch(sheets.GetItem(_variant_t("Sheet1"))); range.AttachDispatch(sheet.GetCells()); CString ContentData; CTime time = CTime::GetCurrentTime(); ContentData.Format(_T("Calibration Date")); range.SetItem(_variant_t((long)(1)),_variant_t((long)(1)),_variant_t(ContentData)); ContentData.Format(_T("%d-%d-%d"),time.GetYear(),time.GetMonth(),time.GetDay()); range.SetItem(_variant_t((long)(1)),_variant_t((long)(3)),_variant_t(ContentData)); range.AttachDispatch(sheet.GetCells()); for (int i=0;i<(int)m_modbus_IDs.size();i++) { if (!m_modbus_IDs.at(i).Result) { continue; } CurrentRow = 3 + 7*i; unsigned short databuffer[30]; Read_Multi(m_modbus_IDs.at(i).ModbusID,&databuffer[0],2000,30); ContentData = _T("Serial Number"); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(1)),_variant_t(ContentData)); ContentData.Format(_T("%d"),databuffer[2027 - 2000]); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(2)),_variant_t(ContentData)); ContentData = _T("Points"); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(3)),_variant_t(ContentData)); ContentData.Format(_T("%d"),databuffer[2003 - 2000]); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(4)),_variant_t(ContentData)); ++CurrentRow; ContentData = _T("Temperature"); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(1)),_variant_t(ContentData)); ContentData.Format(_T("%0.1f"),((float)((short)databuffer[2000 - 2000]))/10); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(2)),_variant_t(ContentData)); ContentData = _T("Humidity"); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(3)),_variant_t(ContentData)); ContentData.Format(_T("%0.1f"),((float)((short)databuffer[2001 - 2000]))/10); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(4)),_variant_t(ContentData)); ++CurrentRow; ContentData = _T("RH"); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(1)),_variant_t(ContentData)); for (int j = 0;j<10;j++) { ContentData.Format(_T("%0.1f"),((float)((short)databuffer[2004 - 2000 + 2*j]))/10); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(2+j)),_variant_t(ContentData)); } ++CurrentRow; ContentData = _T("Frequency"); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(1)),_variant_t(ContentData)); for (int j = 0;j<10;j++) { ContentData.Format(_T("%d"),databuffer[2005 - 2000 + 2*j]); range.SetItem(_variant_t((long)(CurrentRow)),_variant_t((long)(2+j)),_variant_t(ContentData)); } } AfxMessageBox(_T("Export Completely")); app.SetVisible(true); range.ReleaseDispatch(); sheet.ReleaseDispatch(); sheets.ReleaseDispatch(); book.ReleaseDispatch(); books.ReleaseDispatch(); app.ReleaseDispatch(); }