bool cdxCDynamicControlsManager::StoreWindowPosition(CWnd & rWnd, LPCTSTR lpszProfile)
{
	ASSERT(::IsWindow(rWnd.m_hWnd) && lpszProfile && *lpszProfile);
	// can't use an empty profile section string; see CWinApp::GetProfileInt() for further information

	WINDOWPLACEMENT	wpl;
	VERIFY( rWnd.GetWindowPlacement(&wpl) );
	BOOL	bVisible	=	rWnd.IsWindowVisible();
	int	iState	=	REGVAL_NOSTATE;

	if(rWnd.IsIconic())
		iState	=	REGVAL_ICONIC;
	else
		if(rWnd.IsZoomed())
			iState	=	REGVAL_MAXIMIZED;

	return	AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_Valid,	REGVAL_INVALID) &&	// invalidate first
				AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_Left,		wpl.rcNormalPosition.left) &&
				AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_Right,		wpl.rcNormalPosition.right) &&
				AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_Top,		wpl.rcNormalPosition.top) &&
				AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_Bottom,	wpl.rcNormalPosition.bottom) &&
				AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_Visible,	bVisible ? REGVAL_VISIBLE : REGVAL_HIDDEN) &&
				AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_State,		iState) &&
				AfxGetApp()->WriteProfileInt(lpszProfile,	lpszRegVal_Valid,	REGVAL_VALID);		// validate position
}
예제 #2
0
void COXRollup::ReArrangeArranged()
	{
	POSITION pos = m_ArrangedRollups.GetHeadPosition();
	if (pos == NULL)
		return;	// this function has to be as fast as possible
	
	CWnd* pMainWnd = AfxGetMainWnd();
	ASSERT((pMainWnd != NULL) && ::IsWindow(pMainWnd->m_hWnd));		// don´t care about OLE
	if (!pMainWnd->IsWindowEnabled() && pMainWnd->IsIconic())
		return;
	
	// set out new top point; because we have to move to first position
	CWnd* pWndLeftOverPane = pMainWnd->GetDlgItem(AFX_IDW_PANE_FIRST);
	ASSERT(pWndLeftOverPane != NULL);
	
	CRect rcWndNewPos;
	pWndLeftOverPane->GetWindowRect(&rcWndNewPos);
	int nLeft = rcWndNewPos.left;
	int nNewTop = rcWndNewPos.top;
	
	COXRollup* pRoll = NULL;
	while (pos != NULL)
		{
		pRoll = (COXRollup*)m_ArrangedRollups.GetNext(pos);
		pRoll->GetWindowRect(&rcWndNewPos);
		pRoll->SetWindowPos(NULL, nLeft, nNewTop, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
		nNewTop += rcWndNewPos.Height() - 1;
		}
	}
예제 #3
0
LRESULT CDocSelector::OnSelChange(WPARAM wParam, LPARAM)
{
	// Killing the timer, because timer can change the
	// selection in between the procedure...
	KillTimer( DS_TIMER_ID ); // Yogesh Jagota

	// sent when a button gets clicked
	CSwitcherButton* newsel = (CSwitcherButton*)wParam;

	// Yogesh Jagota
	CMDIFrameWnd *pFrame = (CMDIFrameWnd *)AfxGetMainWnd();
	//CWnd* Window = (CWnd*)newsel->m_FrameWnd;//Y.Ivanov
	CWnd* Window = (CWnd*)newsel->m_AttachedView->GetParentFrame();//Yuriy Ivanov
	pFrame->MDIActivate( Window );
	if(Window->IsIconic())
		Window->ShowWindow(SW_SHOWNORMAL);
	pFrame->Invalidate();

	// End Yogesh Jagota

	if (m_iSelectedButton > -1)
		GetButtonFromID(m_iSelectedButton)->Unselect();

	m_iSelectedButton = newsel->m_iID;

	// Reactivate the timer...
	SetTimer( DS_TIMER_ID, 10, NULL ); // Yogesh Jagota


	return 1;
}
예제 #4
0
BOOL CALLBACK EnumWindowsProc(HWND hwnd/*当前找到的窗口句柄*/, LPARAM lParam/*自定义参数*/)  //枚举当前窗口
{
	TCHAR tcClass[256];
	LPWSTR  pStr = (LPWSTR)lParam;
	HWND htmpWnd = NULL;
	::GetClassName(hwnd, tcClass, 255);

	DWORD dwProcessID;
	TCHAR szProcessName[260] = { 0 };
	GetWindowThreadProcessId(hwnd, &dwProcessID);
	HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessID);

	GetModuleFileNameEx(hProcess, NULL, szProcessName, MAX_PATH);

	if (strstr(szProcessName, _T("\\PaperEditor.exe")) != NULL)
	{
		CWnd * pWndPrev = CWnd::FromHandle(hwnd);
		pWndPrev = pWndPrev->GetParent();
		if (pWndPrev != NULL)
		{
			CWnd * pWndChild = pWndPrev->GetLastActivePopup();
			if (pWndPrev->IsIconic())
				pWndPrev->ShowWindow(SW_RESTORE);
			pWndChild->SetForegroundWindow();
		}
	}
	return TRUE;
}
예제 #5
0
bool CCpDesktop::FirstInstance()
{
	// Determine if another window with our class name or caption exists...
	CString strCaption;
	strCaption.LoadString(GetTitleId());
	CWnd* pWndApp = CWnd::FindWindow(NULL, strCaption);
	if (!pWndApp)
		return true;

	// An instance of the app exists
	// Does it have any popups?
	CWnd* pPopupWnd = pWndApp->GetLastActivePopup();

	// Bring the main window to the top
	pWndApp->BringWindowToTop();
	pWndApp->SetForegroundWindow();

	// If iconic, restore the main window
	if (pWndApp->IsIconic())
		pWndApp->ShowWindow(SW_RESTORE);

	// If there was an active popup, bring it along too
	if (pPopupWnd && (pPopupWnd != pWndApp))
	{
		pPopupWnd->BringWindowToTop();
		pPopupWnd->SetForegroundWindow();
	}

	return false;
}
예제 #6
0
파일: SingleCtrl.cpp 프로젝트: 10jschen/acl
BOOL CSingleCtrl::Check()
{
	CWnd *pPrevWnd = CWnd::GetDesktopWindow()->GetWindow(GW_CHILD);

	::CreateMutex(NULL, TRUE, m_sExeName.GetString());
	if (GetLastError() != ERROR_ALREADY_EXISTS)
		return TRUE;

	while (pPrevWnd)
	{
		if (::GetProp(pPrevWnd->GetSafeHwnd(), m_sExeName.GetString()))
		{
			TRACE("Check: %s found\r\n", m_sExeName.GetString());
			if (pPrevWnd->IsIconic()) {
				TRACE("Check: show it now\r\n");
				pPrevWnd->ShowWindow(SW_RESTORE);
			} else
				pPrevWnd->ShowWindow(SW_NORMAL);
			pPrevWnd->SetForegroundWindow();
			pPrevWnd->GetLastActivePopup()->SetForegroundWindow();
			return FALSE;
		}

		pPrevWnd = pPrevWnd->GetWindow(GW_HWNDNEXT);
	}

	TRACE("Could not find previous instance main window!\r\n");
	return FALSE;
}
예제 #7
0
BOOL CBCGPPopupDlg::HasFocus () const
{
	if (GetSafeHwnd () == NULL)
	{
		return FALSE;
	}

	if (m_bMenuIsActive)
	{
		return TRUE;
	}

	CWnd* pWndMain = AfxGetMainWnd ();
	if (pWndMain->GetSafeHwnd () == NULL)
	{
		return FALSE;
	}

	if (pWndMain->IsIconic () ||
		!pWndMain->IsWindowVisible() ||
		pWndMain != GetForegroundWindow ())
	{
		return FALSE;
	}

    CWnd* pFocus = GetFocus();

    BOOL bActive = (pFocus->GetSafeHwnd () != NULL && 
		(IsChild (pFocus) || pFocus->GetSafeHwnd () == GetSafeHwnd ()));

	return bActive;
}
예제 #8
0
// Idle Processing
BOOL CMyglApp::OnIdle(LONG lcount)
{
	CWnd* pMainWnd = m_pMainWnd;

	if (pMainWnd != NULL && pMainWnd->m_hWnd != NULL && pMainWnd->IsWindowVisible() && !pMainWnd->IsIconic())
	{
		if (lcount==0) {
		   CWinApp::OnIdle(lcount); // this does an WM_UPDATEIDLE ...
		}
		if (m_ActiveView) return(m_ActiveView->OnIdle(lcount));
	} 
	
	return FALSE;

		
#if 0
  if (!CWinApp::OnIdle(lcount)) {
		// if lcount == 0, there was a message before
		// pass up message to view
		if (m_ActiveView) return(m_ActiveView->OnIdle(lcount));

  }
  return TRUE; // send more messages
#endif

}
예제 #9
0
파일: SInstance.cpp 프로젝트: flebel/Dorgem
// Activate the Previous Instance of our Application.
HWND CInstanceChecker::ActivatePreviousInstance()
{
  //Try to open the previous instances MMF
  HANDLE hPrevInstance = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, GetMMFFilename());
  if (hPrevInstance)
  {
    // Open up the MMF
    int nMMFSize = sizeof(CWindowInstance);
    CWindowInstance* pInstanceData = (CWindowInstance*) ::MapViewOfFile(hPrevInstance, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, nMMFSize);
    if (pInstanceData != NULL) //Opening the MMF should work
    {
      // Lock the data prior to reading from it
      CSingleLock dataLock(&m_instanceDataMutex, TRUE);

      //activate the old window
      ASSERT(pInstanceData->hMainWnd); //Something gone wrong with the MMF
      HWND hWindow = pInstanceData->hMainWnd;

      if (hWindow)
      {
        CWnd wndPrev;
        wndPrev.Attach(hWindow);
        CWnd* pWndChild = wndPrev.GetLastActivePopup();

        // Restore the focus to the previous instance and bring it to the foreground
        if (wndPrev.IsIconic())
          wndPrev.ShowWindow(SW_RESTORE);
        pWndChild->SetForegroundWindow();

        //Detach the CWnd we were using
        wndPrev.Detach();
      }

      //Unmap the MMF we were using
      ::UnmapViewOfFile(pInstanceData);

      //Close the file handle now that we 
      ::CloseHandle(hPrevInstance);

      //return the Window handle of the previous instance
      return hWindow;
    }

    //Close the file handle now that we 
    ::CloseHandle(hPrevInstance);

    //When we have activate the previous instance, we can release the lock
    ReleaseLock();
  }

  return NULL;
}
예제 #10
0
void COXRollup::ArrangeAll()
	{
	ASSERT_VALID(this);
	
	CWnd* pMainWnd = AfxGetMainWnd();
	ASSERT((pMainWnd != NULL) && ::IsWindow(pMainWnd->m_hWnd));		// don´t care about OLE
	if (!pMainWnd->IsWindowEnabled() && pMainWnd->IsIconic())
		return;
	
	// set out new top point; because we have to move to first position
	CWnd* pWndLeftOverPane = pMainWnd->GetDlgItem(AFX_IDW_PANE_FIRST);
	ASSERT(pWndLeftOverPane != NULL);
	
	CRect rcWndNewPos;
	pWndLeftOverPane->GetWindowRect(&rcWndNewPos);
	int nLeft = rcWndNewPos.left;
	int nNewTop = rcWndNewPos.top;
	
	POSITION pos = m_ArrangedRollups.GetHeadPosition();
	COXRollup* pRoll = NULL;
	while (pos != NULL)
		{
		pRoll = (COXRollup*)m_ArrangedRollups.GetNext(pos);
		pRoll->GetWindowRect(&rcWndNewPos);
		pRoll->SetWindowPos(NULL, nLeft, nNewTop, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
		nNewTop += rcWndNewPos.Height() - 1;
		}
	// now add the ones that haven´t been rolled up before
	POSITION posNotArranged = m_RollupList.GetHeadPosition();
	while (posNotArranged != NULL)
		{
		pRoll = (COXRollup*)m_ArrangedRollups.GetNext(posNotArranged);
		if (m_ArrangedRollups.Find(pRoll, NULL) == NULL)
			{
			if ((::IsWindow(pRoll->m_hWnd)) && pRoll->IsWindowVisible())
				{
				pRoll->InternalRollUp();
				pRoll->SetArrangeFlagTrue();
				pRoll->GetWindowRect(&rcWndNewPos);
				pRoll->SetWindowPos(NULL, nLeft, nNewTop, 0, 0,SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
				nNewTop += rcWndNewPos.Height() - 1;
				m_ArrangedRollups.AddTail(pRoll);	// add it to list
				}
			}
		}
	}
예제 #11
0
파일: MapMgrApp.cpp 프로젝트: hkaiser/TRiAS
BOOL CMapMgrApp::FirstInstance()
{
	CString	strCaption;
	strCaption.LoadString(AFX_IDS_APP_TITLE);
	CWnd *pWndFirst = CWnd::FindWindow(NULL,strCaption);
	if( pWndFirst )
	{
		CWnd *pWndPopup = pWndFirst->GetLastActivePopup();
		pWndFirst->BringWindowToTop();
		if(pWndFirst->IsIconic())
			pWndFirst->ShowWindow(SW_SHOWNORMAL);
		if(pWndFirst != pWndPopup)
			pWndPopup->BringWindowToTop();
		return FALSE;
	}
	return TRUE;
}
예제 #12
0
bool cdxCDynamicWndEx::StoreWindowPosition(LPCTSTR lpszProfile)
{
	if(!IsWindow() || !lpszProfile || !*lpszProfile)
	{
		ASSERT(false);
		return false;
	}

	CWnd	*pWnd	=	Window();

	WINDOWPLACEMENT	wpl;
	VERIFY( pWnd->GetWindowPlacement(&wpl) );
	CRect windowRect;
	pWnd->GetWindowRect(&windowRect);

	BOOL	bVisible	=	pWnd->IsWindowVisible();
	int	iState	=	REGVAL_NOSTATE;

	if(pWnd->IsIconic())
		iState	=	REGVAL_ICONIC;
	else
		if(pWnd->IsZoomed())
			iState	=	REGVAL_MAXIMIZED;

	CWinApp	*app	=	AfxGetApp();

	if(!app->m_pszRegistryKey || !*app->m_pszRegistryKey)
	{
		TRACE(_T("*** NOTE[cdxCDynamicWndEx::StoreWindowPosition()]: To properly store and restore a window's position, please call CWinApp::SetRegistryKey() in you app's InitInstance() !\n"));
		return false;
	}

	return	app->WriteProfileInt(lpszProfile,	lpszRegVal_Valid,	REGVAL_INVALID) &&	// invalidate first
				app->WriteProfileInt(lpszProfile,	lpszRegVal_Left,		windowRect.left) &&
				app->WriteProfileInt(lpszProfile,	lpszRegVal_Right,		windowRect.right) &&
				app->WriteProfileInt(lpszProfile,	lpszRegVal_Top,		windowRect.top) &&
				app->WriteProfileInt(lpszProfile,	lpszRegVal_Bottom,	windowRect.bottom) &&
//				app->WriteProfileInt(lpszProfile,	lpszRegVal_Left,		wpl.rcNormalPosition.left) &&
//				app->WriteProfileInt(lpszProfile,	lpszRegVal_Right,		wpl.rcNormalPosition.right) &&
//				app->WriteProfileInt(lpszProfile,	lpszRegVal_Top,		wpl.rcNormalPosition.top) &&
//				app->WriteProfileInt(lpszProfile,	lpszRegVal_Bottom,	wpl.rcNormalPosition.bottom) &&
				app->WriteProfileInt(lpszProfile,	lpszRegVal_Visible,	bVisible ? REGVAL_VISIBLE : REGVAL_HIDDEN) &&
				app->WriteProfileInt(lpszProfile,	lpszRegVal_State,		iState) &&
				app->WriteProfileInt(lpszProfile,	lpszRegVal_Valid,	REGVAL_VALID);		// validate position
}
예제 #13
0
bool CEtsEodManagerApp::_IsFirstInstance()
{
	CWnd* pWndPrev = CWnd::FindWindow(g_cszMainFrameClassName, NULL);

	if(pWndPrev)
	{
		CWnd* pWndChild = pWndPrev->GetLastActivePopup();

		if(pWndPrev->IsIconic())
			pWndPrev->ShowWindow(SW_RESTORE);
		else if(!pWndPrev->IsWindowVisible())
			pWndPrev->ShowWindow(SW_SHOW);

		pWndChild->SetForegroundWindow();
		return false;
	}

	return true;
}
예제 #14
0
void COXRollup::Arrange()
	{
	ASSERT_VALID(this);
	if (IsArranged()) return;
	
	CWnd* pMainWnd = AfxGetMainWnd();
	ASSERT((pMainWnd != NULL) && ::IsWindow(pMainWnd->m_hWnd));		// don´t care about OLE
	if (!pMainWnd->IsWindowEnabled() && pMainWnd->IsIconic())
		return;
	
	InternalRollUp();
	
	COXRollup* pRollup = NULL;
	if (!m_ArrangedRollups.IsEmpty())
		pRollup = (COXRollup*)m_ArrangedRollups.GetTail();	// get last rolled up element
	
	// we have got a rollup (or not...)
	CPoint topLeft(0,0);
	if (pRollup == NULL)
		{
		// we found no college that was rolled up, so we arrange to the left of the screen
		CRect rcLeftOver;
		CWnd* pWndLeftOverPane = pMainWnd->GetDlgItem(AFX_IDW_PANE_FIRST);
		ASSERT(pWndLeftOverPane != NULL);
		pWndLeftOverPane->GetWindowRect(&rcLeftOver);
		topLeft = CPoint(rcLeftOver.left, rcLeftOver.top);
		}
	else
		{
		ASSERT(pRollup != this);		// can´t happen, otherwise we would have been arranged
		ASSERT(pRollup->IsRolledUp());	// must be up if arranged
		CRect rcLastRollup;
		pRollup->GetWindowRect(&rcLastRollup);
		topLeft = CPoint(rcLastRollup.left, rcLastRollup.bottom - 1);
		}
	
	SetWindowPos(NULL, topLeft.x, topLeft.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
	m_ArrangedRollups.AddTail(this);
	m_bIsArranged = TRUE;			
	}
예제 #15
0
CPrivateChatFrame* CChatWindows::OpenPrivate(GGUID* pGUID, SOCKADDR_IN* pHost, BOOL bMustPush, PROTOCOLID nProtocol, SOCKADDR_IN* pServer)
{
	CPrivateChatFrame* pFrame = NULL;

	ASSERT ( pHost != NULL );

	if ( ( nProtocol == PROTOCOL_BT ) || ( nProtocol == PROTOCOL_FTP ) )
		return NULL;

	if ( ! MyProfile.IsValid() )
	{
		CString strMessage;
		LoadString( strMessage, IDS_CHAT_NEED_PROFILE );
		if ( AfxMessageBox( strMessage, MB_YESNO|MB_ICONQUESTION ) == IDYES )
			AfxGetMainWnd()->PostMessage( WM_COMMAND, ID_TOOLS_PROFILE );
		return NULL;
	}

	if ( nProtocol == PROTOCOL_ED2K )
	{
		CEDClient* pClient;

		// First, check if it's a low ID user on another server. 
		if ( bMustPush && pServer ) 
		{
			// It's a firewalled user (Low ID). If they are using another server, we 
			// can't (shouldn't) contact them. (It places a heavy load on the ed2k servers)
			CSingleLock pLock1( &Network.m_pSection );
			if ( ! pLock1.Lock( 250 ) ) return NULL;
			if ( Neighbours.Get( &pServer->sin_addr ) == NULL ) return NULL;
			pLock1.Unlock();
		}

		// ED2K chat is handled by the EDClient section. (Transfers)
		// We need to find (or create) an EDClient to handle this chat session, since everything 
		// on ed2k shares a TCP link.

		// First, lock the section to prevent a problem with other threads
		CSingleLock pLock( &Transfers.m_pSection );
		if ( ! pLock.Lock( 250 ) ) return NULL;

		// We need to connect to them, so either find or create an EDClient
		if ( pServer )
			pClient = EDClients.Connect(pHost->sin_addr.S_un.S_addr, pHost->sin_port, &pServer->sin_addr, pServer->sin_port, pGUID );
		else
			pClient = EDClients.Connect(pHost->sin_addr.S_un.S_addr, pHost->sin_port, NULL, 0, pGUID );
		// If we weren't able to create a client (Low-id and no server), then exit.
		if ( ! pClient ) return NULL;
		// Have it connect (if it isn't)
		if ( ! pClient->m_bConnected ) pClient->Connect();
		// Tell it to start a chat session as soon as it's able
		pClient->OpenChat();
		pLock.Unlock();

		// Check for / make active any existing window
		pFrame = FindPrivate( &pHost->sin_addr );
		// Check for an empty frame
		if ( pFrame == NULL )
		{
			if ( bMustPush ) pFrame = FindED2KFrame( pHost->sin_addr.S_un.S_addr, pServer );
			else pFrame = FindED2KFrame( pHost );
		}
		if ( pFrame != NULL ) 
		{
			// Open window if we found one
			CWnd* pParent = pFrame->GetParent();
			if ( pParent->IsIconic() ) pParent->ShowWindow( SW_SHOWNORMAL );
			pParent->BringWindowToTop();
			pParent->SetForegroundWindow();
			// And exit
			return pFrame;
		}
		// Open an empty (blank) chat frame. This is totally unnecessary- The EDClient will open 
		// one as required, but it looks better to open one here.
		pFrame = new CPrivateChatFrame();
		// Set name (Also used to match incoming connection)
		if ( bMustPush && pServer ) // Firewalled user (Low ID)
		{
			pFrame->m_sNick.Format( _T("%lu@%s:%hu"),
			pHost->sin_addr.S_un.S_addr,
			(LPCTSTR)CString( inet_ntoa( pServer->sin_addr ) ),
			pServer->sin_port );
		}
		else	// Regular user (High ID)
		{
			pFrame->m_sNick.Format( _T("%s:%hu"), (LPCTSTR)CString( inet_ntoa( pHost->sin_addr ) ), pHost->sin_port );
		}

		// Open window
		CWnd* pParent = pFrame->GetParent();
		if ( pParent->IsIconic() ) pParent->ShowWindow( SW_SHOWNORMAL );
		pParent->BringWindowToTop();
		pParent->SetForegroundWindow();
		// Put a 'connecting' message in the window
		CString strMessage, strConnecting;
		LoadString( strConnecting, IDS_CHAT_CONNECTING_TO );
		strMessage.Format( strConnecting, pFrame->m_sNick );
		pFrame->OnStatusMessage( 0, strMessage );

		return pFrame;
	}

	if ( pGUID != NULL ) pFrame = FindPrivate( pGUID );
	if ( pFrame == NULL ) pFrame = FindPrivate( &pHost->sin_addr );
	
	if ( pFrame == NULL )
	{
		pFrame = new CPrivateChatFrame();
		pFrame->Initiate( pGUID, pHost, bMustPush );	
	}

	pFrame->PostMessage( WM_COMMAND, ID_CHAT_CONNECT );
	
	CWnd* pParent = pFrame->GetParent();
	if ( pParent->IsIconic() ) pParent->ShowWindow( SW_SHOWNORMAL );
	pParent->BringWindowToTop();
	pParent->SetForegroundWindow();

	return pFrame;
}
예제 #16
0
//Activate the Previous Instance of our Application.
HWND CInstanceChecker::ActivatePreviousInstance(LPCTSTR lpCmdLine, ULONG_PTR dwCopyDataItemData, DWORD dwTimeout)
{
  //What will be the return value from this function (assume the worst)
  HWND hWindow = NULL;

  //Try to open the previous instances MMF
  HANDLE hPrevInstance = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, GetMMFFilename());
  if (hPrevInstance)
  {
    //Open up the MMF
    int nMMFSize = sizeof(CWindowInstance);
    CWindowInstance* pInstanceData = static_cast<CWindowInstance*>(MapViewOfFile(hPrevInstance, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, nMMFSize));
    if (pInstanceData) //Opening the MMF should work
    {
      //Lock the data prior to reading from it
      CSingleLock dataLock(&m_instanceDataMutex, TRUE);

      //activate the old window
      ASSERT(pInstanceData->hMainWnd); //Something gone wrong with the MMF
      hWindow = pInstanceData->hMainWnd;
	  if (::IsWindow(hWindow))
      {
        CWnd wndPrev;
        wndPrev.Attach(hWindow);
        CWnd* pWndChild = wndPrev.GetLastActivePopup();

        //Restore the focus to the previous instance and bring it to the foreground
        if (wndPrev.IsIconic())
          wndPrev.ShowWindow(SW_RESTORE);

        if (pWndChild)
          pWndChild->SetForegroundWindow();

        if (lpCmdLine)
        {  
          //Send the current apps command line to the previous instance using WM_COPYDATA
          COPYDATASTRUCT cds;
          cds.dwData = dwCopyDataItemData;
          DWORD dwCmdLength = static_cast<DWORD>(_tcslen(lpCmdLine) + 1);
          cds.cbData = dwCmdLength * sizeof(TCHAR); 
          TCHAR* pszLocalCmdLine = new TCHAR[dwCmdLength]; //We use a local buffer so that we can specify a constant parameter
                                                           //to this function
        #if (_MSC_VER >= 1400)
          _tcscpy_s(pszLocalCmdLine, dwCmdLength, lpCmdLine);
        #else                                                 
          _tcscpy(pszLocalCmdLine, lpCmdLine);
        #endif
          cds.lpData = pszLocalCmdLine;
          CWnd* pMainWindow = AfxGetMainWnd();
          HWND hSender = NULL;
          if (pMainWindow)
            hSender = pMainWindow->GetSafeHwnd();

          //Send the message to the previous instance. Use SendMessageTimeout instead of SendMessage to ensure we 
          //do not hang if the previous instance itself is hung
          DWORD_PTR dwResult = 0;
          if (SendMessageTimeout(hWindow, WM_COPYDATA, reinterpret_cast<WPARAM>(hSender), reinterpret_cast<LPARAM>(&cds),
                                 SMTO_ABORTIFHUNG, dwTimeout, &dwResult) == 0)
          {
            //Previous instance is not responding to messages
            hWindow = NULL;
          }

          //Tidy up the heap memory we have used
          delete [] pszLocalCmdLine;
        }

        //Detach the CWnd we were using
        wndPrev.Detach();
      }

      //Unmap the MMF we were using
      UnmapViewOfFile(pInstanceData);
    }

    //Close the file handle now that we 
    CloseHandle(hPrevInstance);

    //When we have activate the previous instance, we can release the lock
    ReleaseLock();
  }

  return hWindow;
}