Пример #1
0
//更新函数
void CUserInfoView::UpdateUserInfo()
{
	UpdateControls();
	InvalidateRect(NULL);
}
Пример #2
0
// Step 4: the Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	HDC hDC;			// handle to the device context (permission to draw)
	PAINTSTRUCT Ps;		// a variable that you need
	HPEN hRectPen;		// the handle to the red pen
	HPEN hCirPen;
	HPEN hTriPen;
	static POINT triPoint[3];
	static int triBase = 100;
	triPoint[0].x = 445;
	triPoint[0].y = 225 - (triBase / 2);
	triPoint[1].x = 470 - (triBase / 2);
	triPoint[1].y = 170 + (triBase / 2);
	triPoint[2].x = 420 + (triBase / 2);
	triPoint[2].y = 170 + (triBase / 2);

	HBRUSH rectBrush;
	HBRUSH cirBrush;
	HBRUSH triBrush;

	static int rectRed = 255;
	static int rectBlue = 0;
	static int rectGreen = 0;

	static int rectBrushRed = 128;
	static int rectBrushBlue = 128;
	static int rectBrushGreen = 128;

	static int cirRed = 155;
	static int cirBlue = 0;
	static int cirGreen = 10;

	static int cirBrushRed = 108;
	static int cirBrushBlue = 228;
	static int cirBrushGreen = 024;

	static int triRed = 0;
	static int triBlue = 50;
	static int triGreen = 10;

	static int triBrushRed = 208;
	static int triBrushBlue = 155;
	static int triBrushGreen = 124;

	static int rectX = 325;
	static int rectY = 200;
	static int cirX = 225;
	static int cirY = 200;

	POINT test[1];
	test[0].x = 123;
	static int penSize = 5;

	switch (msg)
	{
	case WM_PAINT:
		hDC = BeginPaint(hwnd, &Ps);
		hRectPen = CreatePen(PS_SOLID, penSize, RGB(rectRed, rectGreen, rectBlue));
		SelectObject(hDC, hRectPen);

		rectBrush = CreateSolidBrush(RGB(rectBrushRed, rectBrushGreen, rectBrushBlue));
		SelectObject(hDC, rectBrush);
		Rectangle(hDC, rectX + 25, rectY - 25, rectX - 25, rectY + 25);

		hCirPen = CreatePen(PS_SOLID, penSize, RGB(cirRed, cirGreen, cirBlue));
		SelectObject(hDC, hCirPen);

		cirBrush = CreateSolidBrush(RGB(cirBrushRed, cirBrushGreen, cirBrushBlue));
		SelectObject(hDC, cirBrush);
		Ellipse(hDC, cirX + 25, cirY - 25, cirX - 25, cirY + 25);

		hTriPen = CreatePen(PS_SOLID, penSize, RGB(triRed, triGreen, triBlue));
		SelectObject(hDC, hTriPen);

		triBrush = CreateSolidBrush(RGB(triBrushRed, triBrushGreen, triBrushBlue));
		SelectObject(hDC, triBrush);

		Polygon(hDC, triPoint, 3);

		DeleteObject(hRectPen);
		DeleteObject(rectBrush);
		DeleteObject(hCirPen);

		DeleteObject(cirBrush);
		DeleteObject(hTriPen);
		DeleteObject(triBrush);
		EndPaint(hwnd, &Ps);
		break;
	case WM_KEYDOWN:
		if (wParam == VK_SPACE)
		{
			rectRed = rand() % 256;
			rectGreen = rand() % 256;
			rectBlue = rand() % 256;
			rectBrushRed = rand() % 256;
			rectBrushBlue = rand() % 256;
			rectBrushGreen = rand() % 256;

			cirRed = rand() % 256;
			cirGreen = rand() % 256;
			cirBlue = rand() % 256;
			cirBrushRed = rand() % 256;
			cirBrushBlue = rand() % 256;
			cirBrushGreen = rand() % 256;

			triRed = rand() % 256;
			triGreen = rand() % 256;
			triBlue = rand() % 256;
			triBrushRed = rand() % 256;
			triBrushBlue = rand() % 256;
			triBrushGreen = rand() % 256;
		}
		else if (wParam == VK_NEXT)
		{
			triBase -= 5;
		}
		else if (wParam == VK_PRIOR)
		{
			triBase += 5;
		}
		else if (wParam == VK_RIGHT)
		{
			rectX += 3;
		}
		else if (wParam == VK_LEFT)
		{
			rectX -= 3;
		}
		else if (wParam == VK_UP)
		{
			rectY -= 3;
		}
		else if (wParam == VK_DOWN)
		{
			rectY += 3;
		}

		InvalidateRect(hwnd, NULL, true);
		break;

	case WM_CLOSE:
		DestroyWindow(hwnd);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	return 0;
}
static void new_game (HWND hwnd)
{
    fill_board ();
    set_score (0);
    InvalidateRect (hwnd, &rcBoard, FALSE);
}
Пример #4
0
// Process window messages
LRESULT CALLBACK Flasher::WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) {
	// This is a static method, so we don't know which instantiation we're 
	// dealing with. We use Allen Hadden's ([email protected]) suggestion 
	// from a newsgroup to get the pseudo-this.
	Flasher *_this = (Flasher *) GetWindowLong(hwnd, GWL_USERDATA);

	switch (iMsg) {

	case WM_CREATE:
		return 0;

	case WM_SOCKEVENT:
		{
			assert(HIWORD(lParam) == 0);

			// A new socket created by accept might send messages to
			// this procedure. We can ignore them.
			if(wParam != _this->m_sock) {
				return 0;
			}

			switch(lParam) {
			case FD_ACCEPT:
				{
					SOCKET hNewSock;
					char username[256];
					hNewSock = accept(_this->m_sock, NULL, NULL);
					// make it blocking
					WSAAsyncSelect(hNewSock, hwnd, 0, 0);
					u_long blk = 0;
					int res = ioctlsocket(hNewSock, FIONBIO, &blk);
					assert(res == 0);

					CloseScreenSaver();

					// Se if the server's sending a user name
					int namelen = recv(hNewSock, username, 250, 0);
					if (namelen >= 0) 
						username[namelen] = 0;
					//vnclog.Print(2, _T("Flash for '%s'\n"), username);

					closesocket(hNewSock);


					// flash
					// Receive a DC for the root window
					HDC hrootdc = ::GetDC(NULL);

					HBRUSH holdbrush = (HBRUSH) SelectObject(hrootdc, 
						(HBRUSH) GetStockObject(BLACK_BRUSH));
					
					// Find the size.
					RECT rect;
					GetClipBox(hrootdc, &rect);
					int barwidth = (rect.right - rect.left) / 10;
					int barheight = max( 
						(rect.bottom - rect.top) / 10,
						FLASHFONTHEIGHT);
					HFONT oldfont = (HFONT) SelectObject(hrootdc, _this->m_hfont);

					// Flash the screen
					::Beep(440,50);
										
					Rectangle(hrootdc, rect.left, rect.top, 
								  rect.right, barheight);
					Rectangle(hrootdc, rect.left,  rect.bottom-barheight, 
								  rect.right, rect.bottom);
					Rectangle(hrootdc, rect.left,  rect.top+barheight, 
								  barwidth, rect.bottom-barheight);
					Rectangle(hrootdc, rect.right-barwidth, rect.top+barheight, 
								  rect.right, rect.bottom-barheight);

					RECT topbar;
					SetRect(&topbar, rect.left, rect.top, 
								  rect.right, barheight);
					int i = 0;
					if (namelen > 0) {
						int oldmode = SetBkMode(hrootdc, TRANSPARENT);
						COLORREF oldcolor = SetTextColor(hrootdc, 
							RGB(scalechar(username[0])/(i+1), scalechar(username[1])/(i+1), scalechar(username[2])/(i+1)));
						DrawText(hrootdc, username, -1, &topbar, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
						SetTextColor(hrootdc, oldcolor);
						SetBkMode(hrootdc, oldmode);
					}
					GdiFlush();
					SelectObject(hrootdc, holdbrush);
					::Sleep(1000);
						
					SelectObject(hrootdc, oldfont);
					InvalidateRect(0, &rect, TRUE);

					::ReleaseDC(NULL, hrootdc);
					break;
				}
			case FD_CLOSE:
				//vnclog.Print(2, _T("Flasher connection closed\n"));
				Log.Add(_MESSAGE_, "Flasher connection closed");
				DestroyWindow(hwnd);
				break;
			}
			
			return 0;
		}
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	
	return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
Пример #5
0
HRESULT CALLBACK ElapsedProc (HWND hElapsed, UINT msg, WPARAM wp, LPARAM lp)
{
   ElapsedInfo *pei = NULL;

   EnterCriticalSection (&csElapsed);

   if (msg == WM_CREATE)
      {
      size_t iElapsed;
      for (iElapsed = 0; iElapsed < cElapsed; ++iElapsed)
         {
         if (aElapsed[ iElapsed ].hElapsed == NULL)
            break;
         }
      if (iElapsed >= cElapsed)
         {
         if (!REALLOC (aElapsed, cElapsed, 1+iElapsed, 4))
            return FALSE;
         }

      memset (&aElapsed[ iElapsed ], 0x00, sizeof(ElapsedInfo));
      aElapsed[ iElapsed ].hElapsed = hElapsed;

      pei = &aElapsed[ iElapsed ];
      }
   else
      {
      for (size_t iElapsed = 0; !pei && iElapsed < cElapsed; ++iElapsed)
         {
         if (aElapsed[ iElapsed ].hElapsed == hElapsed)
            pei = &aElapsed[ iElapsed ];
         }
      }

   LeaveCriticalSection (&csElapsed);

   if (pei != NULL)
      {
      switch (msg)
         {
         case WM_CREATE:
            Elapsed_OnCreate (pei);
            break;

         case WM_DESTROY:
            Elapsed_OnDestroy (pei);
            break;

         case WM_RBUTTONDOWN:
         case WM_LBUTTONDOWN:
            Elapsed_OnButtonDown (pei, msg, wp, lp);
            break;

         case WM_SETFOCUS:
            PostMessage (GetParent(hElapsed), WM_NEXTDLGCTL, (WPARAM)pei->hHours, TRUE);
            break;

         case WM_ENABLE:
            EnableWindow (pei->hHours,   IsWindowEnabled (hElapsed));
            EnableWindow (pei->hSep1,    IsWindowEnabled (hElapsed));
            EnableWindow (pei->hMinutes, IsWindowEnabled (hElapsed));
            EnableWindow (pei->hSep2,    IsWindowEnabled (hElapsed));
            EnableWindow (pei->hSeconds, IsWindowEnabled (hElapsed));
            EnableWindow (pei->hSpinner, IsWindowEnabled (hElapsed));

            RECT rElapsed;
            GetRectInParent (hElapsed, &rElapsed);
            InvalidateRect (GetParent(hElapsed), &rElapsed, TRUE);
            UpdateWindow (GetParent(hElapsed));
            break;

         case WM_SYSCHAR:
         case WM_CHAR:
            switch (wp)
               {
               case VK_UP:
                  PostMessage (GetParent(pei->hSpinner), WM_VSCROLL, SB_LINEUP, (LPARAM)pei->hSpinner);
                  break;

               case VK_DOWN:
                  PostMessage (GetParent(pei->hSpinner), WM_VSCROLL, SB_LINEDOWN, (LPARAM)pei->hSpinner);
                  break;

               case VK_PRIOR:
                  PostMessage (GetParent(pei->hSpinner), WM_VSCROLL, SB_PAGEUP, (LPARAM)pei->hSpinner);
                  break;

               case VK_NEXT:
                  PostMessage (GetParent(pei->hSpinner), WM_VSCROLL, SB_PAGEDOWN, (LPARAM)pei->hSpinner);
                  break;

               case VK_HOME:
                  PostMessage (GetParent(pei->hSpinner), WM_VSCROLL, SB_TOP, (LPARAM)pei->hSpinner);
                  break;

               case VK_END:
                  PostMessage (GetParent(pei->hSpinner), WM_VSCROLL, SB_BOTTOM, (LPARAM)pei->hSpinner);
                  break;
               }
            break;

         case ELM_GETRANGE:
            return Elapsed_OnGetRange (pei, wp, lp);

         case ELM_SETRANGE:
            return Elapsed_OnSetRange (pei, wp, lp);

         case ELM_GETTIME:
            return Elapsed_OnGetTime (pei, wp, lp);

         case ELM_SETTIME:
            return Elapsed_OnSetTime (pei, wp, lp);
         }
      }

   return DefWindowProc (hElapsed, msg, wp, lp);
}
Пример #6
0
void repaint_main()
{
	InvalidateRect( mdview.hwnd, NULL, FALSE );
}
Пример #7
0
//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND	- 处理应用程序菜单
//  WM_PAINT	- 绘制主窗口
//  WM_DESTROY	- 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;
	RECT rect;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		
		// 分析菜单选择:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	//画图
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: 在此添加任意绘图代码...
		
		//MoveToEx(hdc,50,50,0);
		//LineTo(hdc,100,100);
		for (int i=1;i<nCount;i++)
		{
			MoveToEx(hdc,xPosition[i-1],yPosition[i-1],0);
			LineTo(hdc,xPosition[i],yPosition[i]);
		}

		//MoveToEx(hdc,xPosition[nCount-1],yPosition[nCount-1],0);
		//LineTo(hdc,xPosition[0],yPosition[0]);

		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_MOUSEMOVE:
		xPosition[nCount] = GET_X_LPARAM(lParam); 
		yPosition[nCount] = GET_Y_LPARAM(lParam); 
		nCount++;

		GetClientRect(hWnd,&rect);
		InvalidateRect(hWnd,&rect,TRUE);

		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Пример #8
0
LRESULT CALLBACK WorkSpaceWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  int wmId, wmEvent;
  PAINTSTRUCT ps;
  HDC hdc;

  LONG ix = GetWindowLong(hWnd, GWL_USERDATA);
  gdioutput *gdi = 0;
  if (ix < LONG(gdi_extra.size()))
    gdi = gdi_extra[ix];

  if (gdi) {
    LRESULT res = gdi->ProcessMsg(message, lParam, wParam);
    if (res)
      return res;
  }
  switch (message)
  {
    case WM_CREATE:
      break;

    case WM_SIZE:
      //SCROLLINFO si;
      //si.cbSize=sizeof(si);
      //si.fMask=SIF_PAGE|SIF_RANGE;

      int nHeight;
      nHeight = HIWORD(lParam);
      int nWidth;
      nWidth = LOWORD(lParam);
      updateScrollInfo(hWnd, *gdi, nHeight, nWidth);
      /*

      int maxx, maxy;
      gdi->clipOffset(nWidth, nHeight, maxx, maxy);

      si.nMin=0;

      if (maxy>0) {
        si.nMax=maxy+nHeight;
        si.nPos=gdi->GetOffsetY();
        si.nPage=nHeight;
      }
      else {
        si.nMax=0;
        si.nPos=0;
        si.nPage=0;
      }
      SetScrollInfo(hWnd, SB_VERT, &si, true);

      si.nMin=0;
      if (maxx>0) {
        si.nMax=maxx+nWidth;
        si.nPos=gdi->GetOffsetX();
        si.nPage=nWidth;
      }
      else {
        si.nMax=0;
        si.nPos=0;
        si.nPage=0;
      }
      SetScrollInfo(hWnd, SB_HORZ, &si, true);
      */
      InvalidateRect(hWnd, NULL, true);
      break;
    case WM_KEYDOWN:
      //gdi->keyCommand(;
      break;

    case WM_VSCROLL:
    {
      int	nScrollCode = (int) LOWORD(wParam); // scroll bar value
      //int hwndScrollBar = (HWND) lParam;      // handle to scroll bar

      int yInc;
      int yPos=gdi->GetOffsetY();
      RECT rc;
      GetClientRect(hWnd, &rc);
      int pagestep = max(50, int(0.9*rc.bottom));

      switch(nScrollCode)
      {
        // User clicked shaft left of the scroll box.
        case SB_PAGEUP:
           yInc = -pagestep;
           break;

        // User clicked shaft right of the scroll box.
        case SB_PAGEDOWN:
           yInc = pagestep;
           break;

        // User clicked the left arrow.
        case SB_LINEUP:
           yInc = -10;
           break;

        // User clicked the right arrow.
        case SB_LINEDOWN:
           yInc = 10;
           break;

        // User dragged the scroll box.
        case SB_THUMBTRACK: {
            // Initialize SCROLLINFO structure
            SCROLLINFO si;
            ZeroMemory(&si, sizeof(si));
            si.cbSize = sizeof(si);
            si.fMask = SIF_TRACKPOS;

            if (!GetScrollInfo(hWnd, SB_VERT, &si) )
                return 1; // GetScrollInfo failed

            yInc = si.nTrackPos - yPos;
          break;
        }

        default:
        yInc = 0;
      }

      scrollVertical(gdi, yInc, hWnd);
      gdi->storeAutoPos(gdi->GetOffsetY());
      break;
    }

    case WM_HSCROLL:
    {
      int	nScrollCode = (int) LOWORD(wParam); // scroll bar value
      //int hwndScrollBar = (HWND) lParam;      // handle to scroll bar

      int xInc;
      int xPos=gdi->GetOffsetX();

      switch(nScrollCode)
      {
        // User clicked shaft left of the scroll box.
        case SB_PAGEUP:
           xInc = -80;
           break;

        // User clicked shaft right of the scroll box.
        case SB_PAGEDOWN:
           xInc = 80;
           break;

        // User clicked the left arrow.
        case SB_LINEUP:
           xInc = -10;
           break;

        // User clicked the right arrow.
        case SB_LINEDOWN:
           xInc = 10;
           break;

        // User dragged the scroll box.
        case SB_THUMBTRACK:  {
            // Initialize SCROLLINFO structure
            SCROLLINFO si;
            ZeroMemory(&si, sizeof(si));
            si.cbSize = sizeof(si);
            si.fMask = SIF_TRACKPOS;

            if (!GetScrollInfo(hWnd, SB_HORZ, &si) )
                return 1; // GetScrollInfo failed

            xInc = si.nTrackPos - xPos;
          break;
        }
          //xInc = HIWORD(wParam) - xPos;
          //break;
        default:
          xInc = 0;
      }

      SCROLLINFO si;
      si.cbSize=sizeof(si);
      si.fMask=SIF_ALL;
      GetScrollInfo(hWnd, SB_HORZ, &si);

      if (si.nPage==0)
        xInc = 0;

      int a=si.nMax-signed(si.nPage-1) - xPos;

      if ((xInc = max( -xPos, min(xInc, a)))!=0) {
        xPos += xInc;
        RECT ScrollArea, ClipArea;
        GetClientRect(hWnd, &ScrollArea);
        ClipArea=ScrollArea;

        gdi->SetOffsetX(xPos);

        ScrollWindowEx (hWnd, -xInc,  0,
          0, &ClipArea,
          (HRGN) NULL, (LPRECT) NULL, SW_INVALIDATE|SW_SCROLLCHILDREN);

        si.cbSize = sizeof(si);
        si.fMask  = SIF_POS;
        si.nPos   = xPos;

        SetScrollInfo(hWnd, SB_HORZ, &si, TRUE);
        UpdateWindow (hWnd);
      }
      break;
    }

    case WM_MOUSEWHEEL: {
      int dz = GET_WHEEL_DELTA_WPARAM(wParam);
      scrollVertical(gdi, -dz, hWnd);
      gdi->storeAutoPos(gdi->GetOffsetY());
      }
      break;

    case WM_TIMER:
      if (wParam == 1001) {
        double autoScroll, pos;
        gdi->getAutoScroll(autoScroll, pos);

        SCROLLINFO si;
        si.cbSize = sizeof(si);
        si.fMask = SIF_ALL;

        GetScrollInfo(hWnd, SB_VERT, &si);
        int dir = gdi->getAutoScrollDir();
        int dy = 0;
        if ((dir<0 && si.nPos <= si.nMin) ||
            (dir>0 && (si.nPos + int(si.nPage)) >= si.nMax)) {
          autoScroll = -autoScroll;
          gdi->setAutoScroll(-1); // Mirror

          double nextPos = pos + autoScroll;
          dy = int(nextPos - si.nPos);
          gdi->storeAutoPos(nextPos);

          //gdi->setData("AutoScroll", -int(data));
        }
        else {
          double nextPos = pos + autoScroll;
          dy = int(nextPos - si.nPos);
          gdi->storeAutoPos(nextPos);
          //gdi->setData("Discrete", DWORD(nextPos*1e3));
        }

        scrollVertical(gdi, dy, hWnd);
      }
      else
        MessageBox(hWnd, "Runtime exception", 0, MB_OK);
      break;

    case WM_ACTIVATE: {
      int fActive = LOWORD(wParam);
      if (fActive != WA_INACTIVE)
        currentFocusIx = ix;

      return DefWindowProc(hWnd, message, wParam, lParam);
    }

    case WM_USER + 2:
      if (gdi)
       LoadPage(*gdi, TabType(wParam));
      break;

    case WM_COMMAND:
      wmId    = LOWORD(wParam);
      wmEvent = HIWORD(wParam);
      // Parse the menu selections:
      switch (wmId)
      {
      case 0: break;
        default:
           return DefWindowProc(hWnd, message, wParam, lParam);
      }
      break;

    case WM_PAINT:
      hdc = BeginPaint(hWnd, &ps);
      RECT rt;
      GetClientRect(hWnd, &rt);

      if (gdi && (ps.rcPaint.right|ps.rcPaint.left|ps.rcPaint.top|ps.rcPaint.bottom) != 0 )
        gdi->draw(hdc, rt, ps.rcPaint);
      /*{
      HANDLE icon = LoadImage(hInst, (LPCTSTR)IDI_MEOS, IMAGE_ICON, 64, 64, LR_SHARED);
      DrawIconEx(hdc, 0,0, (HICON)icon, 64, 64, 0, NULL, DI_NORMAL | DI_COMPAT);
      }*/
      EndPaint(hWnd, &ps);
      break;

    case WM_ERASEBKGND:
      return 0;
      break;

    case WM_DESTROY:
      if (ix > 0) {
        gdi->makeEvent("CloseWindow", "meos", 0, 0, false);
        gdi_extra[ix] = 0;
        delete gdi;

        while(!gdi_extra.empty() && gdi_extra.back() == 0)
          gdi_extra.pop_back();
      }
      break;

    default:
      return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}
Пример #9
0
static int AnimationCtrlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam)
{
    ANIMATIONINFO* anim_info = (ANIMATIONINFO*)GetWindowAdditionalData2 (hwnd);

    switch (message) {
    case MSG_CREATE:
        if (!HaveFreeTimer ()) {
            fprintf (stderr,
                     "Animation error : no free timer is available!\n");
            return -1;
        }
        anim_info = (ANIMATIONINFO*) calloc (1, sizeof (ANIMATIONINFO));
        if (anim_info == NULL)
            return -1;

        SetWindowAdditionalData2 (hwnd, (DWORD)anim_info);
        if(lParam)
            SendMessage (hwnd, ANM_SETANIMATION, 0, lParam);
        break;

    case MSG_DESTROY:
        if (anim_info->mem_dc)
                DeleteCompatibleDC (anim_info->mem_dc);
        free (anim_info);
        /* timer will be freed automatically */
        //KillTimer (hwnd, ID_TIMER);
        break;

    case MSG_TIMER:
        if(anim_info->anim == NULL)
            return 0;
        if (anim_info->status == ANIM_STATUS_PLAY) {
            int delay_time = -1;
            if(anim_info->current) {
                delay_time = anim_info->current->delay_time;
            }
            anim_info->elapsed_10ms++;
            if (delay_time > 0 && anim_info->elapsed_10ms >= delay_time) {
                next_frame (hwnd, anim_info);
                anim_info->elapsed_10ms = 0;
            }
        }
        return 0;

    case MSG_PAINT: {

        HDC hdc;
        HDC src_dc;
        RECT rc_anim;

        if (!anim_info->mem_dc)
            break;

        hdc = BeginPaint (hwnd);
        src_dc = anim_info->mem_dc;

        if (GetWindowStyle (hwnd) & ANS_SCALED) {
            GetClientRect (hwnd, &rc_anim);
        } else {
            SetRect (&rc_anim, 0, 0, anim_info->anim->width,
                     anim_info->anim->height);
        }

        if (RECTW (rc_anim) == anim_info->anim->width
            && RECTH (rc_anim) == anim_info->anim->height) {
            BitBlt (anim_info->mem_dc, 0, 0, 0, 0, hdc, 0, 0, 0);
        } else {
            StretchBlt (anim_info->mem_dc, 0, 0,
                        anim_info->anim->width, anim_info->anim->height,
                        hdc,
                        0, 0,
                        RECTW (rc_anim), RECTH (rc_anim), 0);
        }

        EndPaint (hwnd, hdc);
        return 0;
    }

    case ANM_SETANIMATION: {

          ANIMATION* old = anim_info->anim;
          anim_info->anim = (ANIMATION*)lParam;
          anim_info->current = NULL;
          if (anim_info->anim) {
              KillTimer (hwnd, ID_TIMER);
              if (GetWindowStyle (hwnd) & ANS_FITTOANI) {
                  RECT rc;
                  GetWindowRect(hwnd, &rc);
                  MoveWindow(hwnd, rc.left, rc.top,
                             anim_info->anim->width,
                             anim_info->anim->height, FALSE);
              }
              anim_info->current = NULL;
              setup_anim_mem_dc(hwnd, anim_info);
              next_frame(hwnd, anim_info);
              anim_info->elapsed_10ms = 0;
              //SetTimer (hwnd, ID_TIMER, anim_info->anim->time_unit);
              SetTimer (hwnd, ID_TIMER, 10);
          }
          return (int)old;
      }

    case ANM_GETANIMATION:
        return (int)anim_info->anim;

    case ANM_STARTPLAY: {

        if (anim_info->anim) {
            anim_info->current = NULL;
            anim_info->status = ANIM_STATUS_PLAY;
            next_frame(hwnd, anim_info);
            anim_info->elapsed_10ms = 0;
        }
        return 0;
    }
    case ANM_PAUSE_RESUME:
        if(anim_info->anim)
        {
            if (anim_info->status == ANIM_STATUS_PLAY)
                anim_info->status = ANIM_STATUS_STOP;
            else
                anim_info->status = ANIM_STATUS_PLAY;
        }
        return 0;

    case ANM_STOPPLAY:
        if(anim_info->anim)
        {
            anim_info->current = NULL;
            anim_info->status = ANIM_STATUS_STOP;
            next_frame (hwnd, anim_info); //back to the first frame
            anim_info->elapsed_10ms = 0;
            InvalidateRect (hwnd, NULL, FALSE);
            }
        return 0;

    case MSG_LBUTTONDBLCLK:
        NotifyParent (hwnd, GetDlgCtrlID (hwnd), ANNC_DBLCLK);
        break;

    case MSG_LBUTTONDOWN:
        NotifyParent (hwnd, GetDlgCtrlID (hwnd), ANNC_CLICKED);
        break;

        default:
            break;
    }

    return DefaultControlProc (hwnd, message, wParam, lParam);
}
Пример #10
0
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

  RECT rect,rectDIY;


	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);

		rectDIY.left=0;
		rectDIY.right=500;
		rectDIY.top=0;
		rectDIY.bottom=400;
		
		DrawText(hdc,text,ncount,&rectDIY,0);
		

				
		// TODO: Add any drawing code here...
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		//MessageBox(0,"SAVE?","�ב�¾",0);

		PostQuitMessage(0);
		break;
	case WM_CHAR:
		text[ncount]=wParam;
		ncount++;

		GetClientRect(hWnd,&rect);
		InvalidateRect(hWnd,&rect,TRUE);
		
		break;

	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Пример #11
0
int MHookHandler1::OnMouseMove(LONG _x, LONG _y)
{
	int position;
	bool goup=false; // Сразу отпусти клавишу
		
	// При нажатой правой кнопке мыши не передаём её движения в MHVector,
	// НО! продолжаем отслеживать last_x и last_y, не сбрасывая initialized! 
	// теперь по-новому: если есть прилипание к оси, то можно только противоположное
	// или то же. Поворачивать нельзя.
	if(initialized)
	{
		dx=(_x-last_x);
		dy=(_y-last_y);

		// Может, пятую кнопку можно нажать?
		if(MHSettings::flag_enable_speed_button) OnFastMove(dx,dy);

		position=MHVector::NewValues(dx,dy);

		// Если вбок и вниз = просто вбок, меняем позиции 3 и 5 на 4
		if((true==MHSettings::flag_downall)&&(8==MHSettings::GetNumPositions())&&((3==position)||(5==position)))
		{
			if(MHSettings::flag_up_immediately) goup=true; 
			position=4;
		}

		if(!rbutton_pressed) // известно последнее положение мыши, правая кнопка не нажата
		{
			// Новая опция - из конца в конец в два движения (только при 0==alt_offset)
			if((MHSettings::flag_2moves_mode1)&&(0==alt2_offset))
			{
				if(0<=position) // новое направление
				{
					// Это противоположное направление?
					if(IsOpposite(position_mem_opposite,position))
					{
						// 1. (при невыставленном флаге противоположного направления)
						// сбросим нажатую клавишу. Нажать противоположную сможем только после таймаута
						if(false==flag_opposite_direction)
						{
							// запомним время, отпустим кнопки, запомним направление (ниже)
							opposite_time=timeGetTime();
							MHKeypad::Reset(alt2_offset);
#ifdef _DEBUG
		OutputDebugString(L"OppDir keyup");
#endif
							flag_opposite_direction=true;
							position_mem_opposite=position;
							 
							// Почему-то Reset не включает перерисовку
							InvalidateRect(MHhwnd,NULL,TRUE);
						}
						else // при выставленном флаге противоположного направления
						{
							// 2. Как такое случилось?
							// Не дожидаясь времени, когда можно идти назад, снова пошли вперёд
							MHKeypad::Press(position,true,alt2_offset);
							flag_opposite_direction=false;
							position_mem_opposite=position;
							if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
						}
					}
					else // не противоположное (position_mem содержит всё что угодно),
					{
						if(true==flag_opposite_direction) 
						{
							// 3.
							// ждём выхода в сторону position_mem, а по дороге завернули в сторону
							// только здесь возможен поворот в сторону !!!
							// Но только если прошло время обездвиженности!!!
							if(timeGetTime()-opposite_time>100) // была пауза, можно идти в противоположном направлении
							{
								MHKeypad::Press(position,true, alt2_offset);
								flag_opposite_direction=false;
								position_mem_opposite=position;
								if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
							}
							else 
							{
								MHVector::Reset(); // Не надо больше слать -1
								opposite_time=timeGetTime(); // паузы в 50 мс неподвижности не было, перевзводим
							}
							//MHKeypad::Press(position,true);
							//flag_opposite_direction=false; // уход в сторону - сброс ожиданий
						}
						else // flag_opposite_direction=false
						{
							// не ждём выхода в сторону position_mem. 
							// Нажимаем, только если -1==position_mem (при прилипании)
							if((-1==position_mem)||(MHSettings::flag_change_direction_ontheway))
							{
								MHKeypad::Press(position,true, alt2_offset);
								position_mem_opposite=position;
								if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
							}
						}
					
					} // не противоположное направление
				}
				else if(-1==position)
				{
					// 4.
					// Обрабатываем, только если не довели до конца
					if(flag_opposite_direction)
					{
						if(timeGetTime()-opposite_time>100) // была пауза, можно идти в противоположном направлении
						{
							MHKeypad::Press(position_mem_opposite,true, alt2_offset);
							flag_opposite_direction=false;
							if(goup) MHKeypad::Press(position_mem_opposite,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
						}
						else opposite_time=timeGetTime(); // паузы в 50 мс неподвижности не было, перевзводим
					}
				}
				// else осталось только -2, игнорируем
			} //flag_2moves_mode1 и 4 позиции
			else 
			{
				// 5.
				if(0==alt2_offset)
				{
					// Почти по-старому, как было до модификации flag_2moves_mode1
					if(0<=position) // -2=мышь ваще не двигалась, -1= направление не изменилось
					{
						MHKeypad::Press(position,true,alt2_offset);
						if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
					}
				}
				else // Если это альтернативная раскладка, то взвести таймер
				{
					// 6.
					// как раньше при обработке правой кнопки мыши
					if(0<=position) // -2=мышь подвинулась на недостаточное растояние, -1= направление не изменилось
					{
						MHKeypad::Press(position,true, alt2_offset); // По движению правой кнопки нажимать альтернативные клавиши из первой раскладки
						position_mem=position;
						if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
						
					}
					// Таймер взводим заново при любом движении мыши, если было хоть что-то нажато ранее
					// то есть -1!=position_mem
					if(-1!=position_mem)
					{
						last_time=timeGetTime();
						SetTimer(MHhwnd,1,MHSettings::timeout_after_move,NULL);

					}
				}
			}
		} // правая кнопка не нажата
		else // нажата правая кнопка. Внимание!!!! Здесь может быть 8 позиций, тогда движение с правой кнопкой игнорируем !!!!
		{
			// Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
			//if(4==MHSettings::GetNumPositions())
			//{
				if(!MHSettings::flag_alt2) // Так было, пока не ввели вторую альтернативную: движения с нажатой правой вызывали нажатия c таймером
				{
					// обработка правой кнопки мыши
					if(0<=position) // -2=мышь подвинулась на недостаточное растояние, -1= направление не изменилось
					{
						//MHKeypad::Press(position,true, 6); // По движению правой кнопки нажимать альтернативные клавиши из первой раскладки
						MHKeypad::Press(position,true, alt2_offset);
						position_mem=position;
					}
					// Таймер взводим заново при любом движении мыши, если было хоть что-то нажато ранее
					// то есть -1!=position_mem
					if(-1!=position_mem)
					{
						last_time=timeGetTime();
						SetTimer(MHhwnd,1,MHSettings::timeout_after_move,NULL);
					}
				}
				else // flag_alt2 - теперь движения с нажатой правой - это выбор раскладки
				{
					// Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
					if(4==MHSettings::GetNumPositions())
					{
						switch(position)
						{
						
						case 1: // стрелка впрваво - первая альтернативная
							// Первым делом - отпустить нажатые клавиши
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 6: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 11: // Включена вторая, поменять
								alt2_offset=6;
								break;
							}
							break;

							case 3: // стрелка влево - выбор второй альтернативной
							// Первым делом - отпустить нажатые клавиши
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 11: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 6: // Включена вторая, поменять
								alt2_offset=11;
								break;
							}
							break;
							// Остальные направления (стрелки вверх и вниз) игнорируем
						}	// switch
					} // 4 позиции
					else // (8 позиций) Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
					{
						if((position>0)&&(position<4)) // правая полусфера.
						{
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 6: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 11: // Включена вторая, поменять
								alt2_offset=6;
								break;
							}
						}
						else if((position>4)) // левая полусфера
						{
							// Первым делом - отпустить нажатые клавиши
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 11: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 6: // Включена вторая, поменять
								alt2_offset=11;
								break;
							}
						}
						// Остальные направления (стрелки вверх и вниз) игнорируем
						
					} // 8 позиций
				} // выставлен флаг alt2, меняем раскладки
			// Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
			//} // 4 позиции, а в 8 позициях с правой кнопкой ничего не делаем вообще
			
		} // правая кнопка нажата
	} // if initialized
		

	if(!initialized) initialized=true;

	last_x=_x;
	last_y=_y;
	if(last_x<0) last_x=0;
	if(last_y<0) last_y=0;
	if(last_x>=screen_x_real) last_x=screen_x_real-1;
	if(last_y>=screen_y_real) last_y=screen_y_real-1;

#ifdef _DEBUG
	// Покажите абсолютные значения мвшиных сообщений
	//sprintf(debug_buf,"dx: %d  dy: %d\n", dx,dy);
	//OutputDebugString(debug_buf);
#endif

	return 0; // Новая директива ВЦСПС
}
Пример #12
0
BOOL CWallDirListItem::Invalidate(BOOL bErase/* = TRUE*/)
{
	return InvalidateRect(m_hWnd, NULL, bErase);
}
Пример #13
0
void CCheckListBox::InvalidateItem(int nIndex)
{
	CRect rect;
	GetItemRect(nIndex, rect);
	InvalidateRect(rect, FALSE);
}
Пример #14
0
void CSurfaceDlg::SetTexMods()
{
	char	sz[128];
	texdef_t *pt;
	brushprimit_texdef_t	*bpt;
	// local copy if a width=2 height=2 qtetxture_t is needed
	brushprimit_texdef_t	local_bp;
	int		i;

	if (!g_surfwin)
		return;

	m_bPatchMode = false;

	if (OnlyPatchesSelected())
	{
		pt = &g_qeglobals.d_texturewin.texdef;
		if (QE_SingleBrush())
    {
			//strcpy(g_patch_texdef.name, Patch_GetTextureName());
			g_patch_texdef.SetName(Patch_GetTextureName());
    }
		else
    {
			//strcpy(g_patch_texdef.name, pt->name);
			g_patch_texdef.SetName(pt->name);
    }
		g_patch_texdef.contents = pt->contents;
		g_patch_texdef.flags = pt->flags;
		g_patch_texdef.value = pt->value;
		pt = &g_patch_texdef;
		m_bPatchMode = true;
	}
	else
	{
		if (g_bNewFace && g_ptrSelectedFaces.GetSize() > 0)
		{
      face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
			pt = &selFace->texdef;
			if (g_qeglobals.m_bBrushPrimitMode)
			{
				// compute a texture matrix related to the default matrix width=2 height=2
				ConvertTexMatWithQTexture( &selFace->brushprimit_texdef, selFace->d_texture, &local_bp, NULL );
				bpt = &local_bp;
			}
		}
		else
		{
			pt = &g_qeglobals.d_texturewin.texdef;
			if (g_qeglobals.m_bBrushPrimitMode)
			{
				bpt = &g_qeglobals.d_texturewin.brushprimit_texdef;
			}
		}
		// brush primitive mode : compute fake shift scale rot representation
		if (g_qeglobals.m_bBrushPrimitMode)
			TexMatToFakeTexCoords( bpt->coords, m_shift, &m_rotate, m_scale );
	}

	SendMessage (WM_SETREDRAW, 0, 0);

	::SetWindowText(GetDlgItem(IDC_TEXTURE)->GetSafeHwnd(), pt->name);

	if (m_bPatchMode)
		sprintf(sz, "%4.6f", pt->shift[0]);
	else
		if (g_qeglobals.m_bBrushPrimitMode)
			sprintf(sz, "%d", (int)m_shift[0]);
		else
			sprintf(sz, "%d", (int)pt->shift[0]);
	::SetWindowText(GetDlgItem(IDC_HSHIFT)->GetSafeHwnd(), sz);

	if (m_bPatchMode)
		sprintf(sz, "%4.6f", pt->shift[1]);
	else
		if (g_qeglobals.m_bBrushPrimitMode)
			sprintf(sz, "%d", (int)m_shift[1]);
		else
			sprintf(sz, "%d", (int)pt->shift[1]);
	::SetWindowText(GetDlgItem(IDC_VSHIFT)->GetSafeHwnd(), sz);

	sprintf(sz, m_bPatchMode ? "%4.6f" : "%4.6f", g_qeglobals.m_bBrushPrimitMode ? m_scale[0] : pt->scale[0]);
	::SetWindowText(GetDlgItem(IDC_HSCALE)->GetSafeHwnd(), sz);

	sprintf(sz, m_bPatchMode ? "%4.6f" : "%4.6f", g_qeglobals.m_bBrushPrimitMode ? m_scale[1] : pt->scale[1]);
	::SetWindowText(GetDlgItem(IDC_VSCALE)->GetSafeHwnd(), sz);

	//++timo compute BProtate as int ..
	sprintf(sz, "%d", g_qeglobals.m_bBrushPrimitMode ? (int)m_rotate : (int)pt->rotate);
	::SetWindowText(GetDlgItem(IDC_ROTATE)->GetSafeHwnd(), sz);

	sprintf(sz, "%d", (int)pt->value);
	::SetWindowText(GetDlgItem(IDC_VALUE)->GetSafeHwnd(), sz);

	for (i=0 ; i<32 ; i++)
		::SendMessage(GetDlgItem(g_checkboxes[i])->GetSafeHwnd(), BM_SETCHECK, !!(pt->flags&(1<<i)), 0 );
	for (i=0 ; i<32 ; i++)
		::SendMessage(GetDlgItem(g_checkboxes[32+i])->GetSafeHwnd(), BM_SETCHECK, !!(pt->contents&(1<<i)), 0 );

	SendMessage (WM_SETREDRAW, 1, 0);
	InvalidateRect (NULL, true);
}
Пример #15
0
/// <summary>
/// Handle windows messages for the class instance
/// </summary>
/// <param name="hWnd">window message is for</param>
/// <param name="uMsg">message</param>
/// <param name="wParam">message data</param>
/// <param name="lParam">additional message data</param>
/// <returns>result of message processing</returns>
LRESULT CALLBACK CFaceBasics::DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    //UNREFERENCED_PARAMETER(wParam);
    //UNREFERENCED_PARAMETER(lParam);
	UINT wmId = LOWORD(wParam);
	UINT wmEvent = HIWORD(wParam);
	UINT lwmId = LOWORD(lParam);
	UINT lwmEvent = HIWORD(lParam);

	bool result = false;
	hMenu = GetMenu(hWnd);

	DWORD errResult;

    switch (message)
    {
    case WM_INITDIALOG:
        {
            // Bind application window handle
            m_hWnd = hWnd;

            // Init Direct2D
            D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);

            // Create and initialize a new Direct2D image renderer (take a look at ImageRenderer.h)
            // We'll use this to draw the data we receive from the Kinect to the screen
            m_pDrawDataStreams = new ImageRenderer();
            HRESULT hr = m_pDrawDataStreams->Initialize(GetDlgItem(m_hWnd, IDC_VIDEOVIEW), m_pD2DFactory, cColorWidth, cColorHeight, cColorWidth * sizeof(RGBQUAD)); 
            if (FAILED(hr))
            {
                SetStatusMessage(L"Failed to initialize the Direct2D draw device.", 10000, true);
            }

            // Get and initialize the default Kinect sensor
            InitializeDefaultSensor();
        }
        break;

	case WM_COMMAND:
		switch (wmId)
		{
		case ID_OPTIONS_SHOWFACEBOX:			
			errResult = GetMenuState(hMenu, ID_OPTIONS_SHOWFACEBOX,
				MF_BYCOMMAND);
			if (!(errResult & MF_CHECKED))
			{
				CheckMenuItem(hMenu, ID_OPTIONS_SHOWFACEBOX,
					MF_BYCOMMAND | MF_CHECKED);

				m_pDrawDataStreams->m_drawFaceBox = true;

			}
			else
			{
				CheckMenuItem(hMenu, ID_OPTIONS_SHOWFACEBOX,
					MF_BYCOMMAND | MF_UNCHECKED);

				m_pDrawDataStreams->m_drawFaceBox = false;

			}
						
			InvalidateRect(hWnd, 0, TRUE);
			break;

		case ID_OPTIONS_SHOWFACEPOINTS:
			errResult = GetMenuState(hMenu, ID_OPTIONS_SHOWFACEPOINTS,
				MF_BYCOMMAND);
			if (!(errResult & MF_CHECKED))
			{
				CheckMenuItem(hMenu, ID_OPTIONS_SHOWFACEPOINTS,
					MF_BYCOMMAND | MF_CHECKED);

				m_pDrawDataStreams->m_drawFacePoints = true;

			}
			else
			{
				CheckMenuItem(hMenu, ID_OPTIONS_SHOWFACEPOINTS,
					MF_BYCOMMAND | MF_UNCHECKED);

				m_pDrawDataStreams->m_drawFacePoints = false;

			}

			InvalidateRect(hWnd, 0, TRUE);
			break;

		case ID_OPTIONS_SHOWHDFACEPOINTS:
			errResult = GetMenuState(hMenu, ID_OPTIONS_SHOWHDFACEPOINTS,
				MF_BYCOMMAND);
			if (!(errResult & MF_CHECKED))
			{
				CheckMenuItem(hMenu, ID_OPTIONS_SHOWHDFACEPOINTS,
					MF_BYCOMMAND | MF_CHECKED);

				m_pDrawDataStreams->m_drawHDFacePoints = true;

			}
			else
			{
				CheckMenuItem(hMenu, ID_OPTIONS_SHOWHDFACEPOINTS,
					MF_BYCOMMAND | MF_UNCHECKED);

				m_pDrawDataStreams->m_drawHDFacePoints = false;

			}

			InvalidateRect(hWnd, 0, TRUE);
			break;
		}
		break;

	case WM_MOUSEMOVE:
		
		CheckHDFacePoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
		break;
        // If the titlebar X is clicked, destroy app
    case WM_CLOSE:
        DestroyWindow(hWnd);
        break;

    case WM_DESTROY:
        // Quit the main message pump
        PostQuitMessage(0);
        break;        
    }

    return FALSE;
}
Пример #16
0
void CInfoDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	if (nIDEvent == 1)
	{
		InitLanguage();
		CRect rect;
		int i =0;
		int nSample = 0;
		
		CString str1, str2,str3,str4;
		AfxGetMainWnd()->GetWindowRect(&rect);
		int width, high;
		width = rect.Width();
		high = rect.Height();
		if (prv_nWidth >0&&prv_nHieght>0)
		{
		
			m_strInfo[0].Format("%d X %d", width, high);
			m_strInfo[0]=m_strInfo[0]+"  "+m_strRect;
			
			m_strInfo[1].Format("%d X %d", prv_nWidth, prv_nHieght);
			m_strInfo[1]=m_strInfo[1]+"  "+m_strRect;

			m_strInfo[2].Format("%d", g_Lost_frame);
			m_strInfo[3].Format("%d", g_Total_frame);
			m_strInfo[4].Format("%d kbps", g_Bit_rate);
			m_strInfo[5].Format("%d f/s", g_Frame_rate);
			m_strInfo[6].Format("H.264,%d X %d",prv_nWidth,prv_nHieght);
			m_strInfo[7]=g_strUrl;
			nSample = g_Samplerate/1000;
			g_Samplerate = 0;
			m_strInfo[8].Format("AAC,%s,%dKHz",m_strVedio,nSample);
			
			for(i =0;i < 9;i++)
			{
				InvalidateRect(&m_rctext[i]);
			}		
		}
		else
		{
			width = 0;
			high = 0;
			g_Total_frame = 0;
			g_Lost_frame = 0;
			m_strInfo[0].Format("%d X %d", width, high);
			m_strInfo[0]=m_strInfo[0]+"  "+m_strRect;
			
			m_strInfo[1].Format("%d X %d", prv_nWidth, prv_nHieght);
			m_strInfo[1]=m_strInfo[1]+"  "+m_strRect;
			
			m_strInfo[2].Format("%d", g_Lost_frame);
			m_strInfo[3].Format("%d", g_Total_frame);
			m_strInfo[4].Format("%d kbps", g_Bit_rate);
			m_strInfo[5].Format("%d f/s", g_Frame_rate);
			m_strInfo[6].Format("H.264,%d X %d",prv_nWidth,prv_nHieght);
			m_strInfo[7]=g_strUrl;
			nSample = g_Samplerate/1000;
			m_strInfo[8].Format("AAC,%s,%dKHz",m_strVedio,nSample);
			for(i =0;i < 9;i++)
			{
				InvalidateRect(&m_rctext[i]);
			}
		}
		InvalidateRect(&CRect(8,5,150,25));
		for (i=0;i<8;i++)
		{
			InvalidateRect(&m_rcaption[i]);
		}
	}
	CDialog::OnTimer(nIDEvent);
}
Пример #17
0
bool vncDesktopThread::handle_display_change(HANDLE& threadHandle, rfb::Region2D& rgncache, rfb::SimpleUpdateTracker& clipped_updates, rfb::ClippedUpdateTracker& updates)
{
	if ((m_desktop->m_displaychanged ||									//WM_DISPLAYCHANGE
			!vncService::InputDesktopSelected() ||							//handle logon and screensaver desktops
			m_desktop->m_SWtoDesktop ||										//switch from SW to full desktop or visa versa
			m_desktop->m_hookswitch||										//hook change request
			m_desktop->asked_display!=m_desktop->m_buffer.GetDisplay()		//monitor change request
			) )
			{
				// We need to wait until viewer has send if he support Size changes
				if (!m_server->All_clients_initialalized())
				{
					Sleep(30);
					vnclog.Print(LL_INTERR, VNCLOG("Wait for viewer init \n"));
				}

				//logging
				if (m_desktop->m_displaychanged)								vnclog.Print(LL_INTERR, VNCLOG("++++Screensize changed \n"));
				if (m_desktop->m_SWtoDesktop)									vnclog.Print(LL_INTERR, VNCLOG("m_SWtoDesktop \n"));
				if (m_desktop->m_hookswitch)									vnclog.Print(LL_INTERR, VNCLOG("m_hookswitch \n"));
				if (m_desktop->asked_display!=m_desktop->m_buffer.GetDisplay()) vnclog.Print(LL_INTERR, VNCLOG("desktop switch %i %i \n"),m_desktop->asked_display,m_desktop->m_buffer.GetDisplay());
				if (!m_server->IsThereFileTransBusy())
				if (!vncService::InputDesktopSelected())						vnclog.Print(LL_INTERR, VNCLOG("++++InputDesktopSelected \n"));
				
				
				BOOL screensize_changed=false;
				BOOL monitor_changed=false;
				rfbServerInitMsg oldscrinfo;
				//*******************************************************
				// Lock Buffers from here
				//*******************************************************
				{
					if (XRichCursorEnabled) m_server->UpdateCursorShape();
					/// We lock all buffers,,and also back the client thread update mechanism
					omni_mutex_lock l(m_desktop->m_update_lock);
					#ifdef _DEBUG
					char			szText[256];
					sprintf(szText," ++++++ Mutex lock display changes\n");
					OutputDebugString(szText);		
			#endif
					// We remove all queue updates from the tracker
					m_server->Clear_Update_Tracker();
					// Also clear the current updates
					rgncache.clear();
					// Also clear the copy_rect updates
					clipped_updates.clear();
					// TESTTESTTEST
					// Are all updates cleared....old updates could generate bounding errors
					// any other queues to clear ? Yep cursor positions
					m_desktop->m_cursorpos.tl.x=0;
					m_desktop->m_cursorpos.tl.y=0;
					m_desktop->m_cursorpos.br.x=0;
					m_desktop->m_cursorpos.br.y=0;
					//keep a copy of the old screen size, so we can check for changes later on
					oldscrinfo = m_desktop->m_scrinfo;
						
					if (m_desktop->asked_display!=m_desktop->m_buffer.GetDisplay())
						{
							m_desktop->Checkmonitors();
							m_desktop->asked_display=m_desktop->m_buffer.GetDisplay();
							int old_monitor=m_desktop->current_monitor;	
							m_desktop->current_monitor=1;
							if (m_desktop->asked_display==2 && m_desktop->nr_monitors>1) m_desktop->current_monitor=2;
							if (m_desktop->asked_display==3 && m_desktop->nr_monitors>1) m_desktop->current_monitor=3;
							vnclog.Print(LL_INTERR, VNCLOG("OLd Current mon %i %i \n"),old_monitor,m_desktop->current_monitor);
							if ( old_monitor!=m_desktop->current_monitor) monitor_changed=true;
						}

					//*******************************************************
					// Reinitialize buffers,color, etc
					// monitor change, for non driver, use another buffer
					//*******************************************************
					if (!m_server->IsThereFileTransBusy())
					if (m_desktop->m_displaychanged || !vncService::InputDesktopSelected() || m_desktop->m_hookswitch || (monitor_changed && !m_desktop->m_videodriver))
					{
								// Attempt to close the old hooks
								// shutdown(true) driver is reinstalled without shutdown,(shutdown need a 640x480x8 switch)
								vnclog.Print(LL_INTERR, VNCLOG("m_desktop->Shutdown"));
								monitor_changed=false;
								if (!m_desktop->Shutdown())
									{
										vnclog.Print(LL_INTERR, VNCLOG("Shutdown KillAuthClients\n"));
										m_server->KillAuthClients();
										return false;
									}					
								bool fHookDriverWanted = (FALSE != m_desktop->m_hookdriver);
                                Sleep(1000);
								vnclog.Print(LL_INTERR, VNCLOG("m_desktop->Startup"));
								if (m_desktop->Startup() != 0)
									{
										vnclog.Print(LL_INTERR, VNCLOG("Startup KillAuthClients\n"));
										m_server->KillAuthClients();
										SetEvent(m_desktop->restart_event);
										return false;
									}

								if (m_desktop->m_videodriver)
									{
										if (!XRichCursorEnabled) m_desktop->m_videodriver->HardwareCursor();
										else m_desktop->m_videodriver->NoHardwareCursor();
									}
								m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);

								// sf@2003 - After a new Startup(), we check if the required video driver
								// is actually available. If not, we force hookdll
								// No need for m_hookswitch again because the driver is NOT available anyway.
								// All the following cases are now handled:
								// 1. Desktop thread starts with "Video Driver" checked and no video driver available...
								//    -> HookDll forced (handled by the first InitHookSettings() after initial Startup() call
								// 2. Desktop Thread starts without "Video Driver" checked but available driver
								//    then the user checks "Video Driver" -> Video Driver used
								// 3. Desktop thread starts with "Video Driver" and available driver used
								//    Then driver is switched off (-> hookDll) 
								//    Then the driver is switched on again (-> hook driver used again)
								// 4. Desktop thread starts without "Video Driver" checked and no driver available
								//    then the users checks "Video Driver" 
								if (fHookDriverWanted && m_desktop->m_videodriver == NULL)
									{
										vnclog.Print(LL_INTERR, VNCLOG("m_videodriver == NULL \n"));
										m_desktop->SethookMechanism(true, false); 	// InitHookSettings() would work as well;
									}
								stop_hookwatch=true;
								vnclog.Print(LL_INTERR, VNCLOG("threadHandle \n"));
								if (threadHandle)
								{
									WaitForSingleObject( threadHandle, INFINITE );
									CloseHandle(threadHandle);
									stop_hookwatch=false;
									threadHandle=NULL;
								}
								vnclog.Print(LL_INTERR, VNCLOG("threadHandle2 \n"));

					}
					//*******************************************************
					// end reinit
					//*******************************************************

					if ((m_desktop->m_scrinfo.framebufferWidth != oldscrinfo.framebufferWidth) ||
						(m_desktop->m_scrinfo.framebufferHeight != oldscrinfo.framebufferHeight ||
							m_desktop->m_SWtoDesktop==TRUE ))
							{
								screensize_changed=true;	
								vnclog.Print(LL_INTINFO, VNCLOG("SCR: new screen format %dx%dx%d\n"),
								m_desktop->m_scrinfo.framebufferWidth,
								m_desktop->m_scrinfo.framebufferHeight,
								m_desktop->m_scrinfo.format.bitsPerPixel);
							}

					m_desktop->m_displaychanged = FALSE;
					m_desktop->m_hookswitch = FALSE;
					m_desktop->Hookdll_Changed = m_desktop->On_Off_hookdll; // Set the hooks again if necessary !
					m_desktop->m_SWtoDesktop=FALSE;
					//****************************************************************************
					//************* SCREEN SIZE CHANGED 
					//****************************************************************************

					if (screensize_changed)
						{
							vnclog.Print(LL_INTERR, VNCLOG("Size changed\n"));
							POINT CursorPos;
							m_desktop->SWinit();
							m_desktop->GetQuarterSize();
							GetCursorPos(&CursorPos);
							CursorPos.x=g_dpi.UnscaleX(CursorPos.x);
							CursorPos.y=g_dpi.UnscaleY(CursorPos.y);
							CursorPos.x -= m_desktop->m_ScreenOffsetx;
							CursorPos.y -= m_desktop->m_ScreenOffsety;
							m_desktop->m_cursorpos.tl = CursorPos;
							m_desktop->m_cursorpos.br = rfb::Point(GetSystemMetrics(SM_CXCURSOR),
							GetSystemMetrics(SM_CYCURSOR)).translate(CursorPos);
							m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);
							// Adjust the UpdateTracker clip region
							updates.set_clip_region(m_desktop->m_Cliprect);
							m_desktop->m_buffer.ClearCache();
						}
					if (monitor_changed)
					{
						// we are using the driver, so a monitor change is a view change, like a special kind of single window
						// m_desktop->current_monitor is the new monitor we want to see
						// monitor size mymonitor[m_desktop->current_monitor-1]
						// m_SWOffset is used by the encoders to send the correct coordinates to the viewer
						// Cliprect, buffer coordinates
						m_desktop->m_SWOffsetx=m_desktop->mymonitor[m_desktop->current_monitor-1].offsetx-m_desktop->mymonitor[2].offsetx;
						m_desktop->m_SWOffsety=m_desktop->mymonitor[m_desktop->current_monitor-1].offsety-m_desktop->mymonitor[2].offsety;
						m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);

						m_desktop->m_Cliprect.tl.x=m_desktop->mymonitor[m_desktop->current_monitor-1].offsetx-m_desktop->mymonitor[2].offsetx;
						m_desktop->m_Cliprect.tl.y=m_desktop->mymonitor[m_desktop->current_monitor-1].offsety-m_desktop->mymonitor[2].offsety;
						m_desktop->m_Cliprect.br.x=m_desktop->mymonitor[m_desktop->current_monitor-1].offsetx+
									m_desktop->mymonitor[m_desktop->current_monitor-1].Width-m_desktop->mymonitor[2].offsetx;
						m_desktop->m_Cliprect.br.y=m_desktop->mymonitor[m_desktop->current_monitor-1].offsety+
										m_desktop->mymonitor[m_desktop->current_monitor-1].Height-m_desktop->mymonitor[2].offsety;


						vnclog.Print(LL_INTERR, VNCLOG("***********###############************ %i %i %i %i %i %i\n"),m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety
							,m_desktop->m_Cliprect.tl.x,m_desktop->m_Cliprect.tl.y,m_desktop->m_Cliprect.br.x,m_desktop->m_Cliprect.br.y);


						rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
						updates.set_clip_region(m_desktop->m_Cliprect);				
						m_desktop->m_buffer.ClearCache();
						m_desktop->m_buffer.BlackBack();


					}
					m_desktop->m_buffer.ClearCache();
					m_desktop->m_buffer.BlackBack();
					InvalidateRect(NULL,NULL,TRUE);
					rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
					
					if (memcmp(&m_desktop->m_scrinfo.format, &oldscrinfo.format, sizeof(rfbPixelFormat)) != 0)
						{
							vnclog.Print(LL_INTERR, VNCLOG("Format changed\n"));
							m_server->UpdatePalette(false); // changed no lock ok
							m_server->UpdateLocalFormat(false); // changed no lock ok
						}

					if (screensize_changed) 
						{
							screensize_changed=false;
							m_server->SetNewSWSize(m_desktop->m_scrinfo.framebufferWidth,m_desktop->m_scrinfo.framebufferHeight,FALSE);//changed no lock ok
							m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);// no lock ok
						}
					
					if (monitor_changed)
						{
								monitor_changed=false;
								m_server->SetNewSWSize(m_desktop->mymonitor[m_desktop->current_monitor-1].Width,m_desktop->mymonitor[m_desktop->current_monitor-1].Height,TRUE); //changed no lock ok
						}

		#ifdef _DEBUG
					//char			szText[256];
					sprintf(szText," ++++++ Mutex unlock display changes\n");
					OutputDebugString(szText);		
			#endif
			}// end lock


	}

	return true;
}
Пример #18
0
LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	osdmsg *ms;

	switch (message) {
	case WM_CREATE:
		logmsg("WindowProcedure::CREATE");
		SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)&defstr);
		return 0;

	case WM_DESTROY:
		logmsg("WindowProcedure::DESTROY");
		return 0;

	case WM_PAINT:
		logmsg("WindowProcedure::PAINT");

		ms = (osdmsg*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
		if (ms)
			return DrawMe(hwnd, ms->text, ms->color);

		PAINTSTRUCT ps;
		BeginPaint(hwnd, &ps);
		EndPaint(hwnd, &ps);
		return 0;

	case WM_NCRBUTTONDOWN:
		logmsg("WindowProcedure::NCRBUTTONDOWN");

		ms = (osdmsg*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
		if (ms) {
			if (ms->callback) ms->callback(ms->param);
			SendMessage(hwnd, WM_USER + 3, 0, 0);
		}
		return 0;

	case WM_TIMER:
		logmsg("WindowProcedure::TIMER");
		SendMessage(hwnd, WM_USER + 3, wParam, 0);
		return 0;

	case WM_USER + 1: //draw text ((char *)string, (int) timeout
		logmsg("WindowProcedure::USER+1");

		ms = (osdmsg*)mir_alloc(sizeof(osdmsg));
		ms->text = mir_tstrdup((TCHAR *)wParam);
		if (lParam == 0)
			lParam = db_get_dw(NULL, THIS_MODULE, "timeout", DEFAULT_TIMEOUT);
		ms->timeout = lParam;
		ms->callback = 0;
		ms->color = db_get_dw(NULL, THIS_MODULE, "clr_msg", DEFAULT_CLRMSG);
		ms->param = 0;
		SendMessage(hwnd, WM_USER + 4, (WPARAM)ms, 0);
		mir_free(ms->text);
		mir_free(ms);
		return 0;

	case WM_USER + 2: //show
		logmsg("WindowProcedure::USER+2");
		SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOACTIVATE);
		return 0;

	case WM_USER + 3: //hide
		ms = (osdmsg*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
		logmsg("WindowProcedure::USER+3");
		if (!ms)
			return 0;

		logmsg("WindowProcedure::USER+3/om");
		KillTimer(hwnd, (UINT_PTR)ms);
		mir_free(ms->text);
		mir_free(ms);
		SetWindowLongPtr(hwnd, GWLP_USERDATA, 0);
		ShowWindow(hwnd, SW_HIDE);
		return 0;

	case WM_USER + 4:
		logmsg("WindowProcedure::USER+4");

		ms = (osdmsg*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
		if (ms != 0) {
			logmsg("WindowProcedure::USER+4/old");
			KillTimer(hwnd, (UINT_PTR)ms);
			mir_free(ms->text);
			mir_free(ms);
			SetWindowLongPtr(hwnd, GWLP_USERDATA, 0);
		}

		ms = (osdmsg*)mir_alloc(sizeof(osdmsg));
		memcpy(ms, (osdmsg*)wParam, sizeof(osdmsg));
		ms->text = mir_tstrdup(ms->text);

		SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)ms);
		SetTimer(hwnd, (UINT_PTR)ms, (UINT)ms->timeout, 0);
		InvalidateRect(hwnd, 0, TRUE);
		SendMessage(hwnd, WM_USER + 2, 0, 0);
		return 0;

	case WM_NCHITTEST:
		{
			RECT rect;
			GetWindowRect(hwnd, &rect);

			logmsg("WindowProcedure::NCHITTEST");

			if (LOWORD(lParam) >= (rect.left + 5) && LOWORD(lParam) <= (rect.right - 5) &&
				HIWORD(lParam) >= (rect.top + 5) && HIWORD(lParam) <= (rect.bottom - 5))
				return HTCAPTION;
			return DefWindowProc(hwnd, message, wParam, lParam);
		}
		//here will be the doubleclick => open-message-window solution ;-)
		//case WM_NCLBUTTONDBLCLK:
		//	CallService(MS_MSG_SENDMESSAGE, wparam,(LPARAM)&odp);
		//	return 0;
	default:
		return DefWindowProc(hwnd, message, wParam, lParam);
	}
}
Пример #19
0
void *
vncDesktopThread::run_undetached(void *arg)
{
	//*******************************************************
	// INIT
	//*******************************************************
	capture=true;
	vnclog.Print(LL_INTERR, VNCLOG("Hook changed 1\n"));
	// Save the thread's "home" desktop, under NT (no effect under 9x)
	m_desktop->m_home_desktop = GetThreadDesktop(GetCurrentThreadId());
    vnclog.Print(LL_INTERR, VNCLOG("Hook changed 2\n"));
	// Attempt to initialise and return success or failure
	m_desktop->KillScreenSaver();
	{
		keybd_event(VK_CONTROL, 0, 0, 0);
        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
		Sleep(500); //Give screen some time to kill screensaver
	}
    DWORD startup_error;
	if ((startup_error = m_desktop->Startup()) != 0)
	{
		//TAG14
		vncService::SelectHDESK(m_desktop->m_home_desktop);
		if (m_desktop->m_input_desktop)
			CloseDesktop(m_desktop->m_input_desktop);
		ReturnVal(startup_error);
		return NULL;
	}
	// Succeeded to initialise ok
	ReturnVal(0);

	// sf@2003 - Done here to take into account if the driver is actually activated
	m_desktop->InitHookSettings(); 

	// We set a flag inside the desktop handler here, to indicate it's now safe
	// to handle clipboard messages
	m_desktop->SetClipboardActive(TRUE);

	// All changes in the state of the display are stored in a local
	// UpdateTracker object, and are flushed to the vncServer whenever
	// client updates are about to be triggered
	rfb::SimpleUpdateTracker clipped_updates;
	rfb::ClippedUpdateTracker updates(clipped_updates, m_desktop->m_Cliprect);
	clipped_updates.enable_copyrect(true);
	rfb::Region2D rgncache;


	// Incoming update messages are collated into a single region cache
	// The region cache areas are checked for changes before an update
	// is triggered, and the changed areas are passed to the UpdateTracker
	rgncache = m_desktop->m_Cliprect;
	m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);

	// The previous cursor position is stored, to allow us to erase the
	// old instance whenever it moves.
	rfb::Point oldcursorpos;

	// The driver gives smaller rectangles to check
	// if Accuracy is 4 you eliminate pointer updates
	if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
		m_desktop->m_buffer.SetAccuracy(4);

	//init vars
	m_desktop->m_SWSizeChanged=FALSE;
	m_desktop->m_SWtoDesktop=FALSE;
	m_desktop->m_SWmoved=FALSE;
	m_desktop->Hookdll_Changed = true;
	m_desktop->m_displaychanged=false;
	m_desktop->m_hookswitch=false;
	m_desktop->m_hookinited = FALSE;

	// Set driver cursor state
	XRichCursorEnabled= (FALSE != m_desktop->m_server->IsXRichCursorEnabled());
	if (!XRichCursorEnabled && m_desktop->m_videodriver) m_desktop->m_videodriver->HardwareCursor();
	if (XRichCursorEnabled && m_desktop->m_videodriver) m_desktop->m_videodriver->NoHardwareCursor();
	if (XRichCursorEnabled) m_server->UpdateCursorShape();

	InvalidateRect(NULL,NULL,TRUE);
	oldtick=timeGetTime();
	int fullpollcounter=0;
	//*******************************************************
	// END INIT
	//*******************************************************
	// START PROCESSING DESKTOP MESSAGES
	/////////////////////
	HANDLE threadHandle=NULL;
	stop_hookwatch=false;
	/////////////////////
	// We use a dynmiac value based on cpu usage
    //DWORD MIN_UPDATE_INTERVAL=33;
	/////////////////////
	bool looping=true;
	int waiting_update=0;
	SetEvent(m_desktop->restart_event);
	///
	Sleep(1000);
	rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
	if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
											{
												m_desktop->m_buffer.GrabRegion(rgncache,true,true);
											}
										else
											{
												m_desktop->m_buffer.GrabRegion(rgncache,false,true);
											}
	///
	while (looping && !fShutdownOrdered)
	{		
		DWORD result;
		newtick = timeGetTime();
		int waittime;
		waittime=100-(newtick-oldtick);
		if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver) 
		{
			int fastcounter=0;
			POINT cursorpos;
			while (m_desktop->m_videodriver->oldaantal==m_desktop->pchanges_buf->counter)
			{
				Sleep(5);
				fastcounter++;
				if (fastcounter>20)
				{
					#ifdef _DEBUG
										char			szText[256];
										sprintf(szText,"fastcounter\n");
										OutputDebugString(szText);		
					#endif
					break;
				}
				if (GetCursorPos(&cursorpos) && 
										((cursorpos.x != oldcursorpos.x) ||
										(cursorpos.y != oldcursorpos.y))) break;
			}
			waittime=0;
		}
		else
		{
			waittime=waittime-(waiting_update*10);
		}
		if (waittime<0) waittime=0;
		if (waittime>100) waittime=100;

		result=WaitForMultipleObjects(6,m_desktop->trigger_events,FALSE,waittime);
		{
			//#ifdef _DEBUG
			//							char			szText[256];
			//							sprintf(szText,"WaitForMultipleObjects %i\n",result );
			//							OutputDebugString(szText);		
			//#endif

			// We need to wait until restart is done
			// else wait_timeout goes in to looping while sink window is not ready
			// if no window could be started in 10 seconds something went wrong, close
			// desktop thread.
			DWORD status=WaitForSingleObject(m_desktop->restart_event,10000);
			if (status==WAIT_TIMEOUT) looping=false;
			switch(result)
			{
				case WAIT_TIMEOUT:
				case WAIT_OBJECT_0:
				{
				waiting_update=0;
				ResetEvent(m_desktop->trigger_events[0]);
							{
								//measure current cpu usage of winvnc
								cpuUsage = usage.GetUsage();
								if (cpuUsage > m_server->MaxCpu()) 
									MIN_UPDATE_INTERVAL+=10;
								else MIN_UPDATE_INTERVAL-=10;
								if (MIN_UPDATE_INTERVAL<MIN_UPDATE_INTERVAL_MIN) MIN_UPDATE_INTERVAL=MIN_UPDATE_INTERVAL_MIN;
								if (MIN_UPDATE_INTERVAL>MIN_UPDATE_INTERVAL_MAX) MIN_UPDATE_INTERVAL=MIN_UPDATE_INTERVAL_MAX;


					//			vnclog.Print(LL_INTERR, VNCLOG("!PeekMessage \n"));
								// MAX 30fps
								newtick = timeGetTime(); // Better resolution than GetTickCount ;)
								if ((newtick-oldtick)<MIN_UPDATE_INTERVAL)
								{
									Sleep(MIN_UPDATE_INTERVAL-(newtick-oldtick));
									//continue;  Verify, this can cause screen lockup
									// We need another PeekMessage, but this is only done
									// by hookdll and viewer asking for new update
									// can cause a very long wait time
								}	
								
								#ifdef _DEBUG
										char			szText[256];
										sprintf(szText," cpu2: %d %i %i\n",cpuUsage,MIN_UPDATE_INTERVAL,newtick-oldtick);
										OutputDebugString(szText);		
								#endif
								oldtick=newtick;
								if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver) handle_driver_changes(rgncache,updates);
								m_desktop->m_update_triggered = FALSE;
								g_update_triggered = FALSE;
								//if (m_desktop->m_timerid==NULL) m_desktop->m_timerid = SetTimer(m_desktop->m_hwnd, 1, 100, NULL);

								//*******************************************************
								// HOOKDLL START STOP need to be executed from the thread
								//*******************************************************
								if (m_desktop->Hookdll_Changed && !m_desktop->m_hookswitch)
								{
									vnclog.Print(LL_INTERR, VNCLOG("Hook changed \n"));
									m_desktop->StartStophookdll(m_desktop->On_Off_hookdll);
									if (m_desktop->On_Off_hookdll)
										m_desktop->m_hOldcursor = NULL; // Force mouse cursor grabbing if hookdll On
									// Todo: in case of hookdriver Off - Hoodll On -> hookdriver On - Hoodll Off
									// we must send an empty mouse cursor to the clients so they get rid of their local
									// mouse cursor bitmap
									m_desktop->Hookdll_Changed=false;
								}
								//*******************************************************
								// SCREEN DISPLAY HAS CHANGED, RESTART DRIVER (IF Used)
								//*******************************************************
								if (!m_server->IsThereFileTransBusy())
									if (!handle_display_change(threadHandle, rgncache, clipped_updates, updates))
									{
										//failed we need to quit thread
										looping=false;
										break;
									}
								//*******************************************************
								// END SCREEN DISPLAY HAS CHANGED
								//*******************************************************
					//			m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);
							
								//*******************************************************************
								// SINGLE WINDOW 
								// size SW changed
								// Position change -->change offsets
								//*******************************************************************
								bool SWSizeChanged=false;
								if (m_server->SingleWindow())
								{
									omni_mutex_lock l(m_desktop->m_update_lock);
									m_desktop->GetQuarterSize();
									m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);
									//SW size changed
									if (m_desktop->m_SWSizeChanged)
									{
										SWSizeChanged=true;
										m_desktop->m_SWSizeChanged=FALSE;
										m_desktop->GetQuarterSize();
										rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
					//					vnclog.Print(LL_INTINFO, VNCLOG("4 %i %i %i %i \n"),m_desktop->m_Cliprect.br.x,m_desktop->m_Cliprect.br.y,m_desktop->m_Cliprect.tl.x,m_desktop->m_Cliprect.tl.y);
										updates.set_clip_region(m_desktop->m_Cliprect);
										m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);				
										m_desktop->m_buffer.ClearCache();
										m_desktop->m_buffer.BlackBack();
									}
									//SW position changed
									if (m_desktop->m_SWmoved)
									{
										m_desktop->m_SWmoved=FALSE;
										updates.set_clip_region(m_desktop->m_Cliprect);
										m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);				
										rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
					//					vnclog.Print(LL_INTINFO, VNCLOG("5 %i %i %i %i \n"),m_desktop->m_Cliprect.br.x,m_desktop->m_Cliprect.br.y,m_desktop->m_Cliprect.tl.x,m_desktop->m_Cliprect.tl.y);
										m_desktop->m_buffer.ClearCache();
										m_desktop->m_buffer.BlackBack();
									}

								if (m_server->SingleWindow() && SWSizeChanged)
									{
										m_server->SetNewSWSize(m_desktop->m_SWWidth,m_desktop->m_SWHeight,FALSE);
										m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);
									}
								}// end update lock
								
								////////////////////////////////////////////////////////////////////////////////
								// END DYNAMIC CHANGES
								////////////////////////////////////////////////////////////////////////////////

								//Beep(1000,10);
								//
								// CALCULATE CHANGES
								m_desktop->m_UltraEncoder_used=m_desktop->m_server->IsThereAUltraEncodingClient();
					//			vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted B\n"));
//#ifdef _DEBUG
////										char			szText[256];
//									sprintf(szText," m_desktop->m_server->UpdateWanted check\n");
//										OutputDebugString(szText);		
//#endif
								omni_mutex_lock l(m_desktop->m_update_lock);
								if (m_desktop->m_server->UpdateWanted())
								{
					//				vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted N\n"));
									//TEST4
									// Re-render the mouse's old location if it's moved
									bool cursormoved = false;
									POINT cursorpos;
									if (GetCursorPos(&cursorpos) && 
										((cursorpos.x != oldcursorpos.x) ||
										(cursorpos.y != oldcursorpos.y)))
									{
					//					vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted M %i %i %i %i\n"),cursorpos.x, oldcursorpos.x,cursorpos.y,oldcursorpos.y);
										cursormoved = TRUE;
										oldcursorpos = rfb::Point(cursorpos);
										// nyama/marscha - PointerPos. Inform clients about mouse move.
										m_desktop->m_server->UpdateMouse();
										if (MyGetCursorInfo)
										{
											MyCURSORINFO cinfo;
											cinfo.cbSize=sizeof(MyCURSORINFO);
											MyGetCursorInfo(&cinfo);
											m_desktop->SetCursor(cinfo.hCursor);
										}
									}
								
									//****************************************************************************
									//************* Polling ---- no driver
									//****************************************************************************
									if (!m_desktop->m_hookdriver || !m_desktop->can_be_hooked)
									{
										do_polling(threadHandle, rgncache, fullpollcounter, cursormoved);
									}
									//****************************************************************************
									//************* driver  No polling
									//****************************************************************************
									else 
									{
										// long lTime = timeGetTime();
										if (cursormoved)
										{
											// if (lTime - m_desktop->m_lLastMouseUpdateTime < 200)
											// 	continue;
											m_desktop->m_buffer.SetAccuracy(m_desktop->m_server->TurboMode() ? 2 : 1);
											// m_desktop->m_lLastMouseUpdateTime = lTime;
										}
										else
											// 4 is not that bad...but not perfect (especially with tree branchs display)
											m_desktop->m_buffer.SetAccuracy(m_desktop->m_server->TurboMode() ? 4 : 2); 
									}
									
									
									// PROCESS THE MOUSE POINTER
									// Some of the hard work is done in clients, some here
									// This code fetches the desktop under the old pointer position
									// but the client is responsible for actually encoding and sending
									// it when required.
									// This code also renders the pointer and saves the rendered position
									// Clients include this when rendering updates.
									// The code is complicated in this way because we wish to avoid 
									// rendering parts of the screen the mouse moved through between
									// client updates, since in practice they will probably not have changed.
								
									if (cursormoved && !m_desktop->m_hookdriver)
										{
											if (!m_desktop->m_cursorpos.is_empty())
											{
												// Cursor position seems to be outsite the bounding
												// When you make the screen smaller
												// add extra check
												rfb::Rect rect;
												int x = m_desktop->m_cursorpos.tl.x;
												int w = m_desktop->m_cursorpos.br.x-x;
												int y = m_desktop->m_cursorpos.tl.y;
												int h = m_desktop->m_cursorpos.br.y-y;
												if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
													m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
													{
														rect.tl.x = x;
														rect.br.x = x+w;
														rect.tl.y = y;
														rect.br.y = y+h;
														rgncache.assign_union(rect);
					//									vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
					//									vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
													}
											}

										}
									

									{
										// Prevent any clients from accessing the Buffer
										omni_mutex_lock l(m_desktop->m_update_lock);
										
										// CHECK FOR COPYRECTS
										// This actually just checks where the Foreground window is
										if (!m_desktop->m_hookdriver && !m_server->SingleWindow()) 
											m_desktop->CalcCopyRects(updates);
										
										// GRAB THE DISPLAY
										// Fetch data from the display to our display cache.
										// Update the scaled rects when using server side scaling
										// something wrong inithooking again
										// We make sure no updates are in the regions
										// sf@2002 - Added "&& m_desktop->m_hookdriver"
										// Otherwise we're still getting driver updates (from shared memory buffer)
										// after a m_hookdriver switching from on to off 
										// (and m_hookdll from off to on) that causes mouse cursor garbage,
										// or missing mouse cursor.
										if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
											{
												m_desktop->m_buffer.GrabRegion(rgncache,true,capture);
											}
										else
											{
												m_desktop->m_buffer.GrabRegion(rgncache,false,capture);
											}
#ifdef _DEBUG
										char			szText[256];
										sprintf(szText," capture %i\n",capture);
										OutputDebugString(szText);		
#endif
										capture=true;
											
										// sf@2002 - v1.1.x - Mouse handling
										// If one client, send cursor shapes only when the cursor changes.
										// This is Disabled for now.
										if( !XRichCursorEnabled==m_desktop->m_server->IsXRichCursorEnabled())
											{
												XRichCursorEnabled= (FALSE != m_desktop->m_server->IsXRichCursorEnabled());
												if (m_desktop->m_videodriver)
														{
																if (!XRichCursorEnabled) m_desktop->m_videodriver->HardwareCursor();
																else m_desktop->m_videodriver->NoHardwareCursor();
														}

											}
										if (m_desktop->m_server->IsXRichCursorEnabled() && !m_desktop->m_UltraEncoder_used)
											{
												if (m_desktop->m_hcursor != m_desktop->m_hOldcursor || m_desktop->m_buffer.IsShapeCleared())
														{
																m_desktop->m_hOldcursor = m_desktop->m_hcursor;
																m_desktop->m_buffer.SetCursorPending(TRUE);
																if (!m_desktop->m_hookdriver) m_desktop->m_buffer.GrabMouse(); // Grab mouse cursor in all cases
																m_desktop->m_server->UpdateMouse();
																rfb::Rect rect;
																int x = m_desktop->m_cursorpos.tl.x;
																int w = m_desktop->m_cursorpos.br.x-x;
																int y = m_desktop->m_cursorpos.tl.y;
																int h = m_desktop->m_cursorpos.br.y-y;
																if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
																	m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
																		{
																			rect.tl.x = x;
																			rect.br.x = x+w;
																			rect.tl.y = y;
																			rect.br.y = y+h;
																			rgncache.assign_union(rect);
					//														vnclog.Print(LL_INTINFO, VNCLOG("7 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
					//														vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
																		}
																m_server->UpdateCursorShape();
																}
											}
										else if (!m_desktop->m_hookdriver)// If several clients, send them all the mouse updates
											{												
												// Render the mouse
												//if (!m_desktop->VideoBuffer())
												m_desktop->m_buffer.GrabMouse();
												
												if (cursormoved /*&& !m_desktop->m_buffer.IsCursorUpdatePending()*/) 
															{
																// Inform clients that it has moved
																m_desktop->m_server->UpdateMouse();
																// Get the buffer to fetch the pointer bitmap
																if (!m_desktop->m_cursorpos.is_empty())
																{
																	rfb::Rect rect;
																int x = m_desktop->m_cursorpos.tl.x;
																int w = m_desktop->m_cursorpos.br.x-x;
																int y = m_desktop->m_cursorpos.tl.y;
																int h = m_desktop->m_cursorpos.br.y-y;
																if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
																	m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
																		{
																			rect.tl.x = x;
																			rect.br.x = x+w;
																			rect.tl.y = y;
																			rect.br.y = y+h;
																			rgncache.assign_union(rect);
																			vnclog.Print(LL_INTINFO, VNCLOG("8 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
																			vnclog.Print(LL_INTINFO, VNCLOG("8 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
																		}
																}

															}
												}	
										
											
										// SCAN THE CHANGED REGION FOR ACTUAL CHANGES
										// The hooks return hints as to areas that may have changed.
										// We check the suggested areas, and just send the ones that
										// have actually changed.
										// Note that we deliberately don't check the copyrect destination
										// here, to reduce the overhead & the likelihood of corrupting the
										// backbuffer contents.
										rfb::Region2D checkrgn;
										rfb::Region2D changedrgn;
										rfb::Region2D cachedrgn;

											
										//Update the backbuffer for the copyrect region
										if (!clipped_updates.get_copied_region().is_empty()) 
											{
												rfb::UpdateInfo update_info;
												rfb::RectVector::const_iterator i;
												clipped_updates.get_update(update_info);
												if (!update_info.copied.empty()) 
													{
														for (i=update_info.copied.begin(); i!=update_info.copied.end(); i++) 						
															m_desktop->m_buffer.CopyRect(*i, update_info.copy_delta);
													}
											}
										//Remove the copyrect region from the other updates					
										//checkrgn = rgncache.union_(clipped_updates.get_copied_region());	
										checkrgn = rgncache.subtract(clipped_updates.get_copied_region());	
										//make sure the copyrect is checked next update
										rgncache = clipped_updates.get_copied_region();
										//Check all regions for changed and cached parts
										//This is very cpu intensive, only check once for all viewers
										if (!checkrgn.is_empty())
											m_desktop->m_buffer.CheckRegion(changedrgn,cachedrgn, checkrgn);

										updates.add_changed(changedrgn);
										updates.add_cached(cachedrgn);
												
										clipped_updates.get_update(m_server->GetUpdateTracker());
									}  // end mutex lock

									// Clear the update tracker and region cache an solid
									clipped_updates.clear();
									// screen blanking
									if (m_desktop->OldPowerOffTimeout!=0)
										{
										if (!m_server->BlackAlphaBlending() || m_desktop->VideoBuffer())
											{
												if(OSversion()!=2)
												{
												SystemParametersInfo(SPI_SETPOWEROFFACTIVE, 1, NULL, 0);
												SendMessage(m_desktop->m_hwnd,WM_SYSCOMMAND,SC_MONITORPOWER,(LPARAM)2);
												}
					// don't block input here, this is the wrong thread!
											}
										}
					#ifdef AVILOG
									if (m_desktop->AviGen) m_desktop->AviGen->AddFrame((BYTE*)m_desktop->m_DIBbits);
					#endif
								}
								newtick = timeGetTime(); 
							}
						}
					break;

				case WAIT_OBJECT_0+1:
					ResetEvent(m_desktop->trigger_events[1]);
					m_desktop->lock_region_add=true;
					rgncache.assign_union(m_desktop->rgnpump);
					m_desktop->rgnpump.clear();
					m_desktop->lock_region_add=false;
					waiting_update++;
					break;
				case WAIT_OBJECT_0+2:
					ResetEvent(m_desktop->trigger_events[2]);
					break;
				case WAIT_OBJECT_0+3:
					if (MyGetCursorInfo)
					{
						MyCURSORINFO cinfo;
						cinfo.cbSize=sizeof(MyCURSORINFO);
						MyGetCursorInfo(&cinfo);
						m_desktop->SetCursor(cinfo.hCursor);
					}
					ResetEvent(m_desktop->trigger_events[3]);
					break;
				case WAIT_OBJECT_0+4:
					rgncache.assign_union(m_desktop->m_Cliprect);
					ResetEvent(m_desktop->trigger_events[4]);
					break;
				case WAIT_OBJECT_0+5:
					//break to close
					looping=false;
					ResetEvent(m_desktop->trigger_events[5]);
					break;
			}
		}
		
	}//while

	stop_hookwatch=true;
	if (threadHandle)
	{
		WaitForSingleObject( threadHandle, 5000 );
		CloseHandle(threadHandle);
	}
	
	m_desktop->SetClipboardActive(FALSE);
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread\n"));
	
	// Clear all the hooks and close windows, etc.
    m_desktop->SetBlockInputState(false);
	m_server->SingleWindow(false);
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:SetBlockInputState\n"));
	
	// Clear the shift modifier keys, now that there are no remote clients
	vncKeymap::ClearShiftKeys();
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:ClearShiftKeys\n"));
	
	// Switch back into our home desktop, under NT (no effect under 9x)
	//TAG14
	HWND mywin=FindWindow("blackscreen",NULL);
	if (mywin)SendMessage(mywin,WM_CLOSE, 0, 0);
	g_DesktopThread_running=false;
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:g_DesktopThread_running=false\n"));
	m_desktop->Shutdown();
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:m_desktop->Shutdown\n"));
	return NULL;
}
Пример #20
0
INT_PTR CALLBACK
ProcessPageWndProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    RECT    rc;
    int        nXDifference;
    int        nYDifference;
    int        cx, cy;

    switch (message) {
    case WM_INITDIALOG:
        /*
         * Save the width and height
         */
        GetClientRect(hDlg, &rc);
        nProcessPageWidth = rc.right;
        nProcessPageHeight = rc.bottom;

        /* Update window position */
        SetWindowPos(hDlg, NULL, 15, 30, 0, 0, SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOSIZE|SWP_NOZORDER);

        /*
         * Get handles to the controls
         */
        hProcessPageListCtrl = GetDlgItem(hDlg, IDC_PROCESSLIST);
        hProcessPageHeaderCtrl = (HWND)SendMessageW(hProcessPageListCtrl, LVM_GETHEADER, 0, 0);
        hProcessPageEndProcessButton = GetDlgItem(hDlg, IDC_ENDPROCESS);
        hProcessPageShowAllProcessesButton = GetDlgItem(hDlg, IDC_SHOWALLPROCESSES);

        /* Enable manual column reordering, set full select */
        SendMessageW(hProcessPageListCtrl, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP,
            LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP);

        AddColumns();

        /*
         * Subclass the process list control so we can intercept WM_ERASEBKGND
         */
        OldProcessListWndProc = (WNDPROC)SetWindowLongPtrW(hProcessPageListCtrl, GWLP_WNDPROC, (LONG_PTR)ProcessListWndProc);

        /* Start our refresh thread */
        CloseHandle( CreateThread(NULL, 0, ProcessPageRefreshThread, NULL, 0, NULL));

        return TRUE;

    case WM_DESTROY:
        /* Close the event handle, this will make the */
        /* refresh thread exit when the wait fails */
        CloseHandle(hProcessPageEvent);

        SaveColumnSettings();

        break;

    case WM_COMMAND:
        /* Handle the button clicks */
        switch (LOWORD(wParam))
        {
                case IDC_ENDPROCESS:
                        ProcessPage_OnEndProcess();
        }
        break;

    case WM_SIZE:
        if (wParam == SIZE_MINIMIZED)
            return 0;

        cx = LOWORD(lParam);
        cy = HIWORD(lParam);
        nXDifference = cx - nProcessPageWidth;
        nYDifference = cy - nProcessPageHeight;
        nProcessPageWidth = cx;
        nProcessPageHeight = cy;

        /* Reposition the application page's controls */
        GetWindowRect(hProcessPageListCtrl, &rc);
        cx = (rc.right - rc.left) + nXDifference;
        cy = (rc.bottom - rc.top) + nYDifference;
        SetWindowPos(hProcessPageListCtrl, NULL, 0, 0, cx, cy, SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOMOVE|SWP_NOZORDER);
        InvalidateRect(hProcessPageListCtrl, NULL, TRUE);
        
        GetClientRect(hProcessPageEndProcessButton, &rc);
        MapWindowPoints(hProcessPageEndProcessButton, hDlg, (LPPOINT)(&rc), (sizeof(RECT)/sizeof(POINT)) );
           cx = rc.left + nXDifference;
        cy = rc.top + nYDifference;
        SetWindowPos(hProcessPageEndProcessButton, NULL, cx, cy, 0, 0, SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOSIZE|SWP_NOZORDER);
        InvalidateRect(hProcessPageEndProcessButton, NULL, TRUE);
        
        GetClientRect(hProcessPageShowAllProcessesButton, &rc);
        MapWindowPoints(hProcessPageShowAllProcessesButton, hDlg, (LPPOINT)(&rc), (sizeof(RECT)/sizeof(POINT)) );
           cx = rc.left;
        cy = rc.top + nYDifference;
        SetWindowPos(hProcessPageShowAllProcessesButton, NULL, cx, cy, 0, 0, SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOSIZE|SWP_NOZORDER);
        InvalidateRect(hProcessPageShowAllProcessesButton, NULL, TRUE);

        break;

    case WM_NOTIFY:
        ProcessPageOnNotify(lParam);
        break;
    }

    return 0;
}
Пример #21
0
void regen(HWND hwnd)
{
    _canvas.clearCachedBitmap();            // 需要重新构建显示
    InvalidateRect(hwnd, NULL, FALSE);      // 触发重绘消息
}
Пример #22
0
/* A new Tycon was selected */
static local VOID SetTycon(HWND hDlg, UINT currTycon, List tycons)
{
  Tycon       tc;
  Int         j;
  Type        t;
  Inst	      in;

  tc = nth(currTycon,tycons);
  numCfuns = 0;
  numSfuns = 0;

  t = tc;
  for(j=0; j<tycon(tc).arity; ++j)
    t = ap(t, mkOffset(j));

  switch(tycon(tc).what) {
   case SYNONYM:
     fprintf  (stdstr, "type ");
     printType(stdstr, t);
     fprintf  (stdstr, " = ");
     printType(stdstr, tycon(tc).defn);
     fprintf  (stdstr, "\n");

     SendDlgItemMessage(hDlg, LB_CONS ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);
     break;

   case NEWTYPE:
   case DATATYPE: {
     List cs = tycon(tc).defn;

     if (tycon(tc).what==DATATYPE)
	fprintf(stdstr, "data ");
     else
	fprintf(stdstr, "newtype ");
     printType(stdstr, t);
     fprintf  (stdstr, "\n");
     SendDlgItemMessage(hDlg, LB_DEF ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);

     SendDlgItemMessage(hDlg, LB_CONS ,LB_RESETCONTENT, 0, 0L);

     /* Clear the redraw flag */
     SendDlgItemMessage(hDlg, LB_CONS ,WM_SETREDRAW, FALSE, 0L);

     for (; nonNull(cs); cs=tl(cs)) {
	 printExp (stdstr, hd(cs));
	 fprintf  (stdstr, " :: ");
	 printType(stdstr, name(hd(cs)).type);
	 fprintf  (stdstr, "\n");
	 SendDlgItemMessage(hDlg, LB_CONS ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);
	 SendDlgItemMessage(hDlg, LB_CONS, LB_SETCURSEL, 0, 0L);
	 if (isCfun(hd(cs)))
	     numCfuns++;
	 else
	     numSfuns++;
     }

     /* Set the redraw flag and force repaint. */
     SendDlgItemMessage(hDlg, LB_CONS ,WM_SETREDRAW, TRUE, 0L);
     InvalidateRect(GetDlgItem(hDlg, LB_CONS), NULL, TRUE);

     break;
   }
   case RESTRICTSYN:
     fprintf  (stdstr, "type");
     printType(stdstr, t);
     fprintf  (stdstr, " = <restricted>\n");

     SendDlgItemMessage(hDlg, LB_CONS ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);
     break;
  }

  /* Set instances */
  SendDlgItemMessage(hDlg, LB_TYCONSINST ,LB_RESETCONTENT, 0, 0L);
  /* Clear the redraw flag */
  SendDlgItemMessage(hDlg, LB_TYCONSINST, WM_SETREDRAW, FALSE, 0L);

  if (nonNull(in=findFirstInst(tc))) {
    do {
	SendDlgItemMessage(hDlg, LB_TYCONSINST, LB_ADDSTRING, 0, (LONG)(LPSTR) in);
	SendDlgItemMessage(hDlg, LB_TYCONSINST, LB_SETCURSEL, 0, 0L);
        in = findNextInst(tc,in);
    } while (nonNull(in));
  }
  /* Set the redraw flag and force repaint. */
  SendDlgItemMessage(hDlg, LB_TYCONSINST, WM_SETREDRAW, TRUE, 0L);
  InvalidateRect(GetDlgItem(hDlg, LB_TYCONSINST), NULL, TRUE);

}
Пример #23
0
static void  MyWnd_COMMAND(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify)
{
	int comboint;
	HDC testhdc;
//	if (!zoomviewflag)
//		return;
	switch (id)
	{
	case SC_UPDATE:
//		ShowOpenGLParams(hDlg);
		InvalidateRect(hDlgOpenGL, NULL, TRUE);
		break;

	case IDC_OPENGL_ZOOM_IN:
		capowgl->ZoomIn();
		break;
	case IDC_OPENGL_ZOOM_OUT:
		capowgl->ZoomOut();
		break;

	case IDC_OPENGL_GRAPHTYPES:
		comboint = SendMessage((HWND)hwndCtl, CB_GETCURSEL, 0, 0L); 
		capowgl->Type(comboint);
		UpdateWindow(hDlg);
		break;

	case IDC_OPENGL_SURFACE:
		comboint = SendMessage((HWND)hwndCtl, CB_GETCURSEL, 0 , 0L);
		capowgl->SurfaceType(comboint);
		UpdateWindow(hDlg);
		break;
	case IDC_OPENGL_MATERIAL:
		comboint = SendMessage((HWND)hwndCtl, CB_GETCURSEL, 0, 0L); 
		capowgl->Material(comboint);
		UpdateWindow(hDlg);
		break;

	case IDC_OPENGL_RESOLUTION:
		comboint = SendMessage((HWND)hwndCtl, CB_GETCURSEL, 0, 0L);
		capowgl->Resolution(comboint);
		UpdateWindow(hDlg);
		break;

	case IDC_OPENGL_PAN_UP:
		capowgl->Pan(0);
		break;
	case IDC_OPENGL_PAN_DOWN:
		capowgl->Pan(1);
		break;
	case IDC_OPENGL_PAN_LEFT:
		capowgl->Pan(2);
		break;
	case IDC_OPENGL_PAN_RIGHT:
		capowgl->Pan(3);
		break;
	case IDC_OPENGL_MOUSE_CA:
	case IDC_OPENGL_ORIENT:
		capowgl->MouseMode(0);
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_MOUSE_LIGHT:
		capowgl->MouseMode(1);
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_MOUSE_PAN:
	case IDC_OPENGL_PAN:
		capowgl->MouseMode(2);
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_MOUSE_POINT:
		capowgl->MouseMode(3);
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_MOUSE_ZOOM:
	case IDC_OPENGL_ZOOM:
		capowgl->MouseMode(4);
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_MOUSE_HEIGHT:
	case IDC_OPENGL_HEIGHT:
		capowgl->MouseMode(5);
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_MOUSE_FLY:
	case IDC_OPENGL_FLY:
		capowgl->MouseMode(6);
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_RESET:
		capowgl->Reset();
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_FLAT:
		break;
	case IDC_OPENGL_FLIP_TYPE:  //to let clicking on the bitmap be a switch
		/* Was like this.  the three types are FLATCOLOR, SHEET, TORUS defined as 0, 1, 2.
		I changed this code so Flip works on FLATCOLOR. */
		/*===============
		if (oldtype == 0)  //flat
		{
			oldtype  = capowgl->Type();
			capowgl->Type(0);
		}
		else
		{
			capowgl->Type(oldtype);
			oldtype = 0;
		}
		==================*/
			//New RR 2007 code below.
		if (capowgl->Type() == FLATCOLOR)  //flat
			capowgl->Type(SHEET);
		else // capowgl->Type() is SHEET or TORUS
			capowgl->Type(FLATCOLOR);
		// End New RR 2007 code.
		InvalidateRect(hDlg,NULL,FALSE);
		break;
	case IDC_OPENGL_SHOW_GENERATORS:
		capowgl->ShowGenerators(!capowgl->ShowGenerators());
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_ZERO_PLANE:
		capowgl->ZeroPlane(!capowgl->ZeroPlane());
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_MAX_PLANE:
		capowgl->MaxPlane(!capowgl->MaxPlane());
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_SPIN:
		capowgl->Spin(!capowgl->Spin());
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_FLY_SHOW:
		capowgl->ShowFlyPos(!capowgl->ShowFlyPos());
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_GLASSES:
		capowgl->ThreeDGlasses(!capowgl->ThreeDGlasses());
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_ANTIALIASED:
		capowgl->AntiAliased(!capowgl->AntiAliased());
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_PAUSE:
		SendMessage(masterhwnd, WM_COMMAND, IDM_PAUSE, 0);
		/*this has the effect of calling
			calife_list->ToggleSleep();
			capowgl->FocusIsActive(calife_list->GetSleep());
		*/
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_GLSLEEP: //Rudy added this 12/2/97
		calife_list->ToggleGlSleep();
/*
		if (calife_list->GetGlSleep()) //gl_sleep on
			calife_list->SetGlSleep(0); //turn it off
		else //gl_sleep off
			calife_list->SetGlSleep(1); //TRY to turn it on (you can't if sleep is off)
*/
		ShowOpenGLParams(hDlg);
		break;
	case IDC_OPENGL_TO_VRML:
//		capowgl->CaptureToVRML();  //this one doesn't work
		capowgl->CaptureVRML();
		break;
//		case IDOK:
//		case IDCANCEL:
//		case IDIGNORE:
		EndDialog(hDlg, 0);
	}
}
Пример #24
0
static DWORD WINAPI PerformancePageRefreshThread(void *lpParameter)
{
	ULONG	CommitChargeTotal;
	ULONG	CommitChargeLimit;
	ULONG	CommitChargePeak;

	ULONG	KernelMemoryTotal;
	ULONG	KernelMemoryPaged;
	ULONG	KernelMemoryNonPaged;

	ULONG	PhysicalMemoryTotal;
	ULONG	PhysicalMemoryAvailable;
	ULONG	PhysicalMemorySystemCache;

	ULONG	TotalHandles;
	ULONG	TotalThreads;
	ULONG	TotalProcesses;

	WCHAR	Text[256];

	static const WCHAR    wszFormatDigit[] = {'%','u',0};
	WCHAR    wszMemUsage[255];

	LoadStringW(hInst, IDS_STATUS_BAR_MEMORY_USAGE, wszMemUsage, sizeof(wszMemUsage)/sizeof(WCHAR));

	/*  Create the event */
	hPerformancePageEvent = CreateEventW(NULL, TRUE, TRUE, NULL);

	/*  If we couldn't create the event then exit the thread */
	if (!hPerformancePageEvent)
		return 0;

	while (1)
	{
		DWORD	dwWaitVal;

		/*  Wait on the event */
		dwWaitVal = WaitForSingleObject(hPerformancePageEvent, INFINITE);

		/*  If the wait failed then the event object must have been */
		/*  closed and the task manager is exiting so exit this thread */
		if (dwWaitVal == WAIT_FAILED)
			return 0;

		if (dwWaitVal == WAIT_OBJECT_0)
		{
			ULONG CpuUsage;
			ULONG CpuKernelUsage;
			int nBarsUsed1, nBarsUsed2;
			DWORD_PTR args[2];

			/*  Reset our event */
			ResetEvent(hPerformancePageEvent);

			/* 
			 *  Update the commit charge info
			 */ 
			CommitChargeTotal = PerfDataGetCommitChargeTotalK();
			CommitChargeLimit = PerfDataGetCommitChargeLimitK();
			CommitChargePeak = PerfDataGetCommitChargePeakK();
			wsprintfW(Text, wszFormatDigit, CommitChargeTotal);
			SetWindowTextW(hPerformancePageCommitChargeTotalEdit, Text);
			wsprintfW(Text, wszFormatDigit, CommitChargeLimit);
			SetWindowTextW(hPerformancePageCommitChargeLimitEdit, Text);
			wsprintfW(Text, wszFormatDigit, CommitChargePeak);

			SetWindowTextW(hPerformancePageCommitChargePeakEdit, Text);

			args[0] = CommitChargeTotal;
			args[1] = CommitChargeLimit;
			FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
			               wszMemUsage, 0, 0, Text,
			               sizeof(Text)/sizeof(*Text), (__ms_va_list*)args);
			SendMessageW(hStatusWnd, SB_SETTEXTW, 2, (LPARAM)Text);

			/* 
			 *  Update the kernel memory info
			 */ 
			KernelMemoryTotal = PerfDataGetKernelMemoryTotalK();
			KernelMemoryPaged = PerfDataGetKernelMemoryPagedK();
			KernelMemoryNonPaged = PerfDataGetKernelMemoryNonPagedK();
			wsprintfW(Text, wszFormatDigit, KernelMemoryTotal);
			SetWindowTextW(hPerformancePageKernelMemoryTotalEdit, Text);
			wsprintfW(Text, wszFormatDigit, KernelMemoryPaged);
			SetWindowTextW(hPerformancePageKernelMemoryPagedEdit, Text);
			wsprintfW(Text, wszFormatDigit, KernelMemoryNonPaged);
			SetWindowTextW(hPerformancePageKernelMemoryNonPagedEdit, Text);

			/* 
			 *  Update the physical memory info
			 */ 
			PhysicalMemoryTotal = PerfDataGetPhysicalMemoryTotalK();
			PhysicalMemoryAvailable = PerfDataGetPhysicalMemoryAvailableK();
			PhysicalMemorySystemCache = PerfDataGetPhysicalMemorySystemCacheK();
			wsprintfW(Text, wszFormatDigit, PhysicalMemoryTotal);
			SetWindowTextW(hPerformancePagePhysicalMemoryTotalEdit, Text);
			wsprintfW(Text, wszFormatDigit, PhysicalMemoryAvailable);
			SetWindowTextW(hPerformancePagePhysicalMemoryAvailableEdit, Text);
			wsprintfW(Text, wszFormatDigit, PhysicalMemorySystemCache);
			SetWindowTextW(hPerformancePagePhysicalMemorySystemCacheEdit, Text);

			/* 
			 *  Update the totals info
			 */ 
			TotalHandles = PerfDataGetSystemHandleCount();
			TotalThreads = PerfDataGetTotalThreadCount();
			TotalProcesses = PerfDataGetProcessCount();
			wsprintfW(Text, wszFormatDigit, TotalHandles);
			SetWindowTextW(hPerformancePageTotalsHandleCountEdit, Text);
			wsprintfW(Text, wszFormatDigit, TotalThreads);
			SetWindowTextW(hPerformancePageTotalsThreadCountEdit, Text);
			wsprintfW(Text, wszFormatDigit, TotalProcesses);
			SetWindowTextW(hPerformancePageTotalsProcessCountEdit, Text);

			/* 
			 *  Redraw the graphs
			 */ 
			InvalidateRect(hPerformancePageCpuUsageGraph, NULL, FALSE);
			InvalidateRect(hPerformancePageMemUsageGraph, NULL, FALSE);

                        /*
                         *  Get the CPU usage
                         */
                        CpuUsage = PerfDataGetProcessorUsage();
                        CpuKernelUsage = PerfDataGetProcessorSystemUsage();

                        /*
                         *  Get the memory usage
                         */
                        CommitChargeTotal = (ULONGLONG)PerfDataGetCommitChargeTotalK();
                        CommitChargeLimit = (ULONGLONG)PerfDataGetCommitChargeLimitK();
                        nBarsUsed1 = CommitChargeLimit ? ((CommitChargeTotal * 100) / CommitChargeLimit) : 0;

                        PhysicalMemoryTotal = PerfDataGetPhysicalMemoryTotalK();
                        PhysicalMemoryAvailable = PerfDataGetPhysicalMemoryAvailableK();
                        nBarsUsed2 = PhysicalMemoryTotal ? ((PhysicalMemoryAvailable * 100) / PhysicalMemoryTotal) : 0;


                        GraphCtrl_AppendPoint(&PerformancePageCpuUsageHistoryGraph, CpuUsage, CpuKernelUsage, 0.0, 0.0);
                        GraphCtrl_AppendPoint(&PerformancePageMemUsageHistoryGraph, nBarsUsed1, nBarsUsed2, 0.0, 0.0);
                        /* PerformancePageMemUsageHistoryGraph.SetRange(0.0, 100.0, 10) ; */
                        InvalidateRect(hPerformancePageMemUsageHistoryGraph, NULL, FALSE);
                        InvalidateRect(hPerformancePageCpuUsageHistoryGraph, NULL, FALSE);
                }
	}
        return 0;
}
Пример #25
0
/* Handles browse names dialog box */
LRESULT CALLBACK BrowseNamesDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
  static              List namesList = NIL;
  List                names=NIL;
  struct strName      nm;
  Name                n;
  UINT                theName;
  WORD                NotifyCode, wId;
  RECT                aRect, DlgRect;
  HBITMAP             hBitmap;
  HBITMAP             hBmp;
  BITMAP	      bm;
  static HBITMAP      hPBm, hPSelBm, hDBm, hDSelBm, hMBm, hMSelBm, hNBm, hNSelBm,
		      hSBm, hSSelBm;
  CHAR	              Buffer[300];
  DRAWITEMSTRUCT FAR *lpdis;
  LPMEASUREITEMSTRUCT lpmis;
  BOOL                Selected = FALSE;

  NotifyCode = HIWORD (wParam);
  wId        = LOWORD (wParam);

  switch (msg) {

    case WM_INITDIALOG:
      CenterDialogInParent(hDlg);
      SetDialogFont (hDlg, hDialogFont);
      namesList = addNamesMatching((String)0, NIL);

      /* Clear the redraw flag */
      SendDlgItemMessage(hDlg, LB_NAMES ,WM_SETREDRAW, FALSE, 0L);

      for (names=namesList; nonNull(names); names=tl(names)) {
	if (nonNull(names)) {
	  nm = name(hd(names));
	  fprintf(stdstr, "%s   -- in %s\n",textToStr(nm.text),textToStr(module(nm.mod).text));
	  SendDlgItemMessage(hDlg, LB_NAMES ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);
	  SendDlgItemMessage(hDlg, LB_NAMES, LB_SETCURSEL, 0, 0L);
	}
      }

      /* Set the redraw flag and force repaint. */
      SendDlgItemMessage(hDlg, LB_NAMES ,WM_SETREDRAW, TRUE, 0L);
      InvalidateRect(GetDlgItem(hDlg, LB_NAMES), NULL, TRUE);

      theName = 0;
      SetName(hDlg, theName, namesList);

      hPBm = LoadBitmap (hThisInstance, "PRIMBMP");
      MapBitmap (hPBm, RGB(0,128,128), GetSysColor(COLOR_WINDOW));
      hPSelBm = LoadBitmap (hThisInstance, "PRIMBMP");
      MapBitmap (hPSelBm, RGB(0,128,128), GetSysColor(COLOR_HIGHLIGHT));
      hDBm = LoadBitmap (hThisInstance, "DATACONSBMP");
      MapBitmap (hDBm, RGB(0,128,128), GetSysColor(COLOR_WINDOW));
      hDSelBm = LoadBitmap (hThisInstance, "DATACONSBMP");
      MapBitmap (hDSelBm, RGB(0,128,128), GetSysColor(COLOR_HIGHLIGHT));
      hMBm = LoadBitmap (hThisInstance, "MEMBERBMP");
      MapBitmap (hMBm, RGB(0,128,128), GetSysColor(COLOR_WINDOW));
      hMSelBm = LoadBitmap (hThisInstance, "MEMBERBMP");
      MapBitmap (hMSelBm, RGB(0,128,128), GetSysColor(COLOR_HIGHLIGHT));
      hNBm = LoadBitmap (hThisInstance, "NAMEBMP");
      MapBitmap (hNBm, RGB(0,128,128), GetSysColor(COLOR_WINDOW));
      hNSelBm = LoadBitmap (hThisInstance, "NAMEBMP");
      MapBitmap (hNSelBm, RGB(0,128,128), GetSysColor(COLOR_HIGHLIGHT));
      hSBm = LoadBitmap (hThisInstance, "SELECTORBMP");
      MapBitmap (hSBm, RGB(0,128,128), GetSysColor(COLOR_WINDOW));
      hSSelBm = LoadBitmap (hThisInstance, "SELECTORBMP");
      MapBitmap (hSSelBm, RGB(0,128,128), GetSysColor(COLOR_HIGHLIGHT));

      /* set focus to search box (must return FALSE) */
      SetFocus (GetDlgItem(hDlg, IDC_SEARCHNAME));
      return FALSE;

    case WM_DESTROY:
      DeleteObject(hPBm);
      DeleteObject(hPSelBm);
      DeleteObject(hDBm);
      DeleteObject(hDSelBm);
      DeleteObject(hMBm);
      DeleteObject(hMSelBm);
      DeleteObject(hNBm);
      DeleteObject(hNSelBm);
      DeleteObject(hSBm);
      DeleteObject(hSSelBm);
      break;

    case WM_CTLCOLORBTN:
    case WM_CTLCOLORDLG:
    case WM_CTLCOLOREDIT:
    case WM_CTLCOLORLISTBOX:
    case WM_CTLCOLORMSGBOX:
    case WM_CTLCOLORSCROLLBAR:
    case WM_CTLCOLORSTATIC:
      break;

    case WM_MEASUREITEM:

      lpdis = (DRAWITEMSTRUCT FAR *) lParam;

      if (lpdis->CtlID == LB_NAMES) {

	lpmis = (LPMEASUREITEMSTRUCT) lParam;

	/* Set the height of the list box items to Bitmap height */
	hBmp = LoadBitmap(hThisInstance, "PRIMBMP");
	GetObject(hBmp, sizeof(BITMAP), &bm);
	DeleteObject(hBmp);

	lpmis->itemHeight = bm.bmHeight+1;

	return TRUE;
      }
      break;

    case WM_DRAWITEM:

      lpdis = (DRAWITEMSTRUCT FAR *) lParam;

      if (lpdis->CtlID == LB_NAMES) {

	if (lpdis->itemID == (UINT)-1) {
	  return TRUE;
	}

	switch (lpdis->itemAction) {
	  case ODA_DRAWENTIRE:
	  case ODA_SELECT:
	  case ODA_FOCUS:
	    if ((lpdis->itemState & ODS_SELECTED) /*&& (lpdis->itemState & ODS_FOCUS)*/) {
	      SetBkColor(lpdis->hDC, GetSysColor(COLOR_HIGHLIGHT));
	      SetTextColor(lpdis->hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
	      Selected = TRUE;
	    }
	    else {
	      SetBkColor(lpdis->hDC, GetSysColor(COLOR_WINDOW));
	      SetTextColor(lpdis->hDC, GetSysColor(COLOR_WINDOWTEXT));
	    }
	    break;

	  default:
	    return FALSE;
	}

	SendDlgItemMessage(hDlg, lpdis->CtlID, LB_GETTEXT, lpdis->itemID, (LPARAM) Buffer);
	ExtTextOut(lpdis->hDC, lpdis->rcItem.left+21, lpdis->rcItem.top, ETO_OPAQUE, &(lpdis->rcItem), Buffer, strlen(Buffer), NULL);

	n = nth(lpdis->itemID, namesList);

	if (isCfun(n)) 
	  hBmp = Selected ? hDSelBm : hDBm;
	else if (isMfun(n)) 
	  hBmp = Selected ? hMSelBm : hMBm;
	else if (isSfun(n)) 
	  hBmp = Selected ? hSSelBm : hSBm;
	else if (name(n).primDef) 
	  hBmp = Selected ? hPSelBm : hPBm;
	else 
	  hBmp = Selected ? hNSelBm : hNBm;
        
	DrawBitmap (lpdis->hDC, hBmp, (lpdis->rcItem.left)+4, lpdis->rcItem.top);
	/* If selected draw rectangle */
	if ((lpdis->itemState & ODS_SELECTED)&&(lpdis->itemState & ODS_FOCUS)) {
	  DrawFocusRect(lpdis->hDC, &(lpdis->rcItem));
	}

	return TRUE;
      }

    case WM_PAINT: {
      HDC 	   hDC;
      PAINTSTRUCT  Ps;

      BeginPaint(hDlg, &Ps);
      hDC = Ps.hdc;

      /* Paint classes Bitmap */
      GetWindowRect(hDlg, &DlgRect);
      GetWindowRect(GetDlgItem(hDlg, ID_PLACEBITMAP), &aRect);

      hBitmap = LoadMappedBitmap(hThisInstance, "NAMESDLGBMP");
      DrawBitmap(hDC, hBitmap,
		 aRect.left-DlgRect.left-GetSystemMetrics(SM_CXDLGFRAME),
		 aRect.top-DlgRect.top-GetSystemMetrics(SM_CYDLGFRAME)-GetSystemMetrics(SM_CYCAPTION));
      DeleteObject(hBitmap);
      EndPaint(hDlg, &Ps);
    }
    break;


    case WM_COMMAND:
      switch (wId) {
	case LB_NAMES:
	  switch(NotifyCode) {
	    case LBN_SELCHANGE:
	      /* Select a new name */
	      theName = (UINT) SendDlgItemMessage(hDlg, LB_NAMES ,LB_GETCURSEL, 0, 0L);
	      SetName(hDlg, theName, namesList);
	      break;

	    case LBN_DBLCLK: {
	      /* Open in text editor script file with name definition */
	      Name n;

	      /* Get the selected name */
	      theName = (UINT) SendDlgItemMessage(hDlg, LB_NAMES ,LB_GETCURSEL, 0, 0L);
	      n = nth(theName, namesList);      

	      if (!name(n).primDef) {
		setLastEdit(getScriptName(scriptThisName(n)), name(n).line);
		runEditor();
	      }
	      else {
		MessageBox(hDlg, "Primitive function:\nNo definition available.", appName, MB_ICONINFORMATION | MB_OK);
	      }
	  }
	  break;
	}
	break;

	case IDC_SEARCHNAME:  /* Search a name */
	  switch(HIBYTE(NotifyCode)) {
	    case HIBYTE(EN_CHANGE): {
	      CHAR    Buffer[300];

	      /* Get edit control contents */
	      SendDlgItemMessage(hDlg, IDC_SEARCHNAME, WM_GETTEXT, 300, (LPARAM) ((LPSTR) Buffer));
	      /* Search in names list box */
	      SendDlgItemMessage(hDlg, LB_NAMES, LB_SELECTSTRING, 0, (LPARAM) ((LPSTR) Buffer));
	      /* Update window contents */
	      DlgSendMessage(hDlg, WM_COMMAND, LB_NAMES, MAKELONG(0, LBN_SELCHANGE));
	    }
	    break;
	  }
	  break;

	case ID_EDITNAME: /* Pushed on Edit name button */
	  if (SendDlgItemMessage(hDlg, LB_NAMES, LB_GETCURSEL, 0, 0L) != LB_ERR)
	    DlgSendMessage(hDlg, WM_COMMAND, LB_NAMES, MAKELONG(0, LBN_DBLCLK));
	    break;

	case IDCANCEL: /* Close dialog */
	case IDOK:
	  EndDialog(hDlg, TRUE);
	  return TRUE;

	default:
	  return TRUE;
      }
  }
  return FALSE;
}
Пример #26
0
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)

{

	static POINT apt[4] ;

	HDC          hdc ;

	int          cxClient, cyClient ;

	PAINTSTRUCT  ps ;


	switch (message)

	{

	case WM_SIZE:

		cxClient = LOWORD (lParam) ;

		cyClient = HIWORD (lParam) ;



		apt[0].x = cxClient / 4 ;

		apt[0].y = cyClient / 2 ;



		apt[1].x = cxClient / 2 ;

		apt[1].y = cyClient / 4 ;



		apt[2].x = cxClient / 2 ;

		apt[2].y = 3 * cyClient / 4 ;



		apt[3].x = 3 * cxClient / 4 ;

		apt[3].y = cyClient / 2 ;



		return 0 ;


	case WM_LBUTTONDOWN:

	case WM_RBUTTONDOWN:

	case WM_MOUSEMOVE:

		if (wParam & MK_LBUTTON || wParam & MK_RBUTTON)

		{

			hdc = GetDC (hwnd) ;

			SelectObject (hdc, GetStockObject (WHITE_PEN)) ;

			DrawBezier (hdc, apt) ;



			if (wParam & MK_LBUTTON)

			{

				apt[1].x = LOWORD (lParam) ;

				apt[1].y = HIWORD (lParam) ;

			}



			if (wParam & MK_RBUTTON)

			{

				apt[2].x = LOWORD (lParam) ;

				apt[2].y = HIWORD (lParam) ;

			}



			SelectObject (hdc, GetStockObject (BLACK_PEN)) ;

			DrawBezier (hdc, apt) ;

			ReleaseDC (hwnd, hdc) ;

		}

		return 0 ;

	case   WM_PAINT:

		InvalidateRect (hwnd, NULL, TRUE) ;



		hdc = BeginPaint (hwnd, &ps) ;



		DrawBezier (hdc, apt) ;



		EndPaint (hwnd, &ps) ;

		return 0 ;



	case WM_DESTROY:

		PostQuitMessage (0) ;

		return 0 ;

	}

	return DefWindowProc (hwnd, message, wParam, lParam) ;

}
Пример #27
0
void COpenHoldemView::DrawBalanceBox(const int chair) {
	CPen		*pTempPen = NULL, oldpen;
	CBrush	*pTempBrush = NULL, oldbrush;
	RECT		textrect = {0}, drawrect = {0};
	CFont		*oldfont = NULL, cFont;
	CString	t = "";
	int			left = 0, top = 0, right = 0, bottom = 0;
	CDC			*pDC = GetDC();
	static RECT	balance_rect_last[10] = {0};
  // Background color
	pDC->SetBkColor(COLOR_GRAY);
  // Figure placement of box
	left = _client_rect.right * pc[p_tablemap->nchairs()][chair][0] - 26;
	top = _client_rect.bottom * pc[p_tablemap->nchairs()][chair][1] + 30;
	right = _client_rect.right * pc[p_tablemap->nchairs()][chair][0] + 25;
	bottom = _client_rect.bottom * pc[p_tablemap->nchairs()][chair][1] + 45;
  // Set font basics
	_logfont.lfHeight = -12;
	_logfont.lfWeight = FW_NORMAL;
	cFont.CreateFontIndirect(&_logfont);
	oldfont = pDC->SelectObject(&cFont);
	pDC->SetTextColor(COLOR_BLACK);
  if (p_scraper_access->IsPlayerSeated(chair) 
		  || p_scraper_access->IsPlayerActive(chair)) 	{
    pTempPen = (CPen*)pDC->SelectObject(&_black_pen);
		oldpen.FromHandle((HPEN)pTempPen);					// Save old pen
		pTempBrush = (CBrush*)pDC->SelectObject(&_white_brush);
		oldbrush.FromHandle((HBRUSH)pTempBrush);			// Save old brush

		// Format Text
		if (p_table_state->_players[chair]._active) 	{
			t = Number2CString(p_table_state->_players[chair]._balance);
		}	else {
			t.Format("Out (%s)", Number2CString(p_table_state->_players[chair]._balance));
		}
	}	else {
		pTempPen = (CPen*)pDC->SelectObject(&_white_dot_pen);
		oldpen.FromHandle((HPEN)pTempPen);					// Save old pen
		pTempBrush = (CBrush*)pDC->SelectObject(&_gray_brush);
		oldbrush.FromHandle((HBRUSH)pTempBrush);			// Save old brush
    t = "";
	}
  // Calc rectangle size for text
	textrect.left = 0;
	textrect.top = 0;
	textrect.right = 0;
	textrect.bottom = 0;
	pDC->DrawText(t.GetString(), t.GetLength(), &textrect, DT_CALCRECT);
  // Figure out placement of rectangle
	drawrect.left = left < (left+(right-left)/2)-textrect.right/2-3 ? left : (left+(right-left)/2)-textrect.right/2-3;
	drawrect.top = top;
	drawrect.right = right > (left+(right-left)/2)+textrect.right/2+3 ? right : (left+(right-left)/2)+textrect.right/2+3;
	drawrect.bottom = bottom;
  // Invalidate everything if the balance has decreased in width
	if (balance_rect_last[chair].right - balance_rect_last[chair].left != drawrect.right - drawrect.left) {
		InvalidateRect(NULL, true);
	}
  // Draw it
	pDC->SetBkMode(OPAQUE);
	pDC->Rectangle(drawrect.left, drawrect.top, drawrect.right, drawrect.bottom);
	pDC->SetBkMode(TRANSPARENT);
	pDC->DrawText(t.GetString(), t.GetLength(), &drawrect, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
	balance_rect_last[chair].left = drawrect.left;
	balance_rect_last[chair].top = drawrect.top;
	balance_rect_last[chair].right = drawrect.right;
	balance_rect_last[chair].bottom = drawrect.bottom;

	// Restore original pen and brush
	pDC->SelectObject(oldpen);
	pDC->SelectObject(oldbrush);
	pDC->SelectObject(oldfont);
	cFont.DeleteObject();
	ReleaseDC(pDC);
}
Пример #28
0
void debugview_info::update()
{
	RECT bounds, vscroll_bounds, hscroll_bounds;
	debug_view_xy totalsize, visiblesize, topleft;
	bool show_vscroll, show_hscroll;
	SCROLLINFO scrollinfo;

	// get the view window bounds
	GetClientRect(m_wnd, &bounds);
	visiblesize.x = (bounds.right - bounds.left) / metrics().debug_font_width();
	visiblesize.y = (bounds.bottom - bounds.top) / metrics().debug_font_height();

	// get the updated total rows/cols and left row/col
	totalsize = m_view->total_size();
	topleft = m_view->visible_position();

	// determine if we need to show the scrollbars
	show_vscroll = show_hscroll = false;
	if (totalsize.x > visiblesize.x && bounds.bottom >= metrics().hscroll_height())
	{
		bounds.bottom -= metrics().hscroll_height();
		visiblesize.y = (bounds.bottom - bounds.top) / metrics().debug_font_height();
		show_hscroll = true;
	}
	if (totalsize.y > visiblesize.y && bounds.right >= metrics().vscroll_width())
	{
		bounds.right -= metrics().vscroll_width();
		visiblesize.x = (bounds.right - bounds.left) / metrics().debug_font_width();
		show_vscroll = true;
	}
	if (!show_vscroll && totalsize.y > visiblesize.y && bounds.right >= metrics().vscroll_width())
	{
		bounds.right -= metrics().vscroll_width();
		visiblesize.x = (bounds.right - bounds.left) / metrics().debug_font_width();
		show_vscroll = true;
	}

	// compute the bounds of the scrollbars
	GetClientRect(m_wnd, &vscroll_bounds);
	vscroll_bounds.left = vscroll_bounds.right - metrics().vscroll_width();
	if (show_hscroll)
		vscroll_bounds.bottom -= metrics().hscroll_height();

	GetClientRect(m_wnd, &hscroll_bounds);
	hscroll_bounds.top = hscroll_bounds.bottom - metrics().hscroll_height();
	if (show_vscroll)
		hscroll_bounds.right -= metrics().vscroll_width();

	// if we hid the scrollbars, make sure we reset the top/left corners
	if (topleft.y + visiblesize.y > totalsize.y)
		topleft.y = std::max(totalsize.y - visiblesize.y, 0);
	if (topleft.x + visiblesize.x > totalsize.x)
		topleft.x = std::max(totalsize.x - visiblesize.x, 0);

	// fill out the scroll info struct for the vertical scrollbar
	scrollinfo.cbSize = sizeof(scrollinfo);
	scrollinfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE;
	scrollinfo.nMin = 0;
	scrollinfo.nMax = totalsize.y - 1;
	scrollinfo.nPage = visiblesize.y;
	scrollinfo.nPos = topleft.y;
	SetScrollInfo(m_vscroll, SB_CTL, &scrollinfo, TRUE);

	// fill out the scroll info struct for the horizontal scrollbar
	scrollinfo.cbSize = sizeof(scrollinfo);
	scrollinfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE;
	scrollinfo.nMin = 0;
	scrollinfo.nMax = totalsize.x - 1;
	scrollinfo.nPage = visiblesize.x;
	scrollinfo.nPos = topleft.x;
	SetScrollInfo(m_hscroll, SB_CTL, &scrollinfo, TRUE);

	// update window info
	visiblesize.y++;
	visiblesize.x++;
	m_view->set_visible_size(visiblesize);
	m_view->set_visible_position(topleft);

	// invalidate the bounds
	InvalidateRect(m_wnd, nullptr, FALSE);

	// adjust the bounds of the scrollbars and show/hide them
	if (m_vscroll)
	{
		if (show_vscroll)
			smart_set_window_bounds(m_vscroll, m_wnd, vscroll_bounds);
		smart_show_window(m_vscroll, show_vscroll);
	}
	if (m_hscroll)
	{
		if (show_hscroll)
			smart_set_window_bounds(m_hscroll, m_wnd, hscroll_bounds);
		smart_show_window(m_hscroll, show_hscroll);
	}
}
Пример #29
0
LRESULT CColorPickerBtn::OnClicked (WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL &bHandled) 
{
	//
	// Mark button as active and invalidate button to force a redraw
	//
	m_fPopupActive = TRUE;
	InvalidateRect (NULL);

	//
	// Get the parent window
	//

	HWND hWndParent = GetParent ();

	//
	// Send the drop down notification to the parent
	//

	SendNotification (CPN_DROPDOWN, m_clrCurrent, TRUE); 

	//
	// Save the current color for future reference
	//

    COLORREF clrOldColor = m_clrCurrent;

	//
	// Display the popup
	//

	BOOL fOked = Picker (true);

	//
	// Cancel the popup
	//

	m_fPopupActive = FALSE;

	//
	// If the popup was canceled without a selection
	//

	if (!fOked)
	{

		//
		// If we are tracking, restore the old selection
		//

		if (m_fTrackSelection)
		{
			if (clrOldColor != m_clrCurrent)
			{
				m_clrCurrent = clrOldColor;
				SendNotification (CPN_SELCHANGE, m_clrCurrent, TRUE); 
			}
		}
		SendNotification (CPN_CLOSEUP, m_clrCurrent, TRUE); 
		SendNotification (CPN_SELENDCANCEL, m_clrCurrent, TRUE); 
	}
	else
	{
		bSetInvisible = false;
		if (clrOldColor != m_clrCurrent)
		{
			SendNotification (CPN_SELCHANGE, m_clrCurrent, TRUE); 
		}
		SendNotification (CPN_CLOSEUP, m_clrCurrent, TRUE); 
		SendNotification (CPN_SELENDOK, m_clrCurrent, TRUE); 
	}

	//
	// Invalidate button to force repaint
	//

	InvalidateRect (NULL);
	return TRUE;
}
/* процедура обработки сообщений для главного окна */
LRESULT CALLBACK MainWinProc(HWND hw,UINT msg,WPARAM wp,LPARAM lp) {

HWND hw_mainfreq, hw_powfreq, hw_attconst, hw_powampl, hw_startspd, hw_startpos;
char G[20], A[20], W1[20], W2[20], V0[20], X0[20];

HDC hDC;
PAINTSTRUCT ps; //создаём контекст устройства


HPEN Pen1 = CreatePen( PS_SOLID, 1, RGB(0, 0, 255));
HPEN Pen2 = CreatePen( PS_SOLID, 2, RGB(0, 0, 0));
HPEN Pen3 = CreatePen( PS_SOLID, 2, RGB(255, 255, 255));
HPEN Pen4 = CreatePen( PS_SOLID, 1, RGB(0, 255, 0));
HPEN Pen5 = CreatePen( PS_SOLID, 1, RGB(255, 0, 0));
HBRUSH Brush1 = CreateSolidBrush( RGB(255, 255, 255) );


 switch (msg) {
  case WM_CREATE:
   /* при создании окна внедряем в него кнопочку */
   CreateWindow("button","START",WS_CHILD|BS_PUSHBUTTON|WS_VISIBLE,
    520,420,200,20,hw,(HMENU)ID_MYBUTTON,NULL,NULL);
   /* стиль WS_CHILD означает, что это дочернее окно и для него
    вместо дескриптора меню будет передан целочисленный идентификатор,
    который будет использоваться дочерним окном для оповещения
    родительского окна через WM_COMMAND */

   hw_mainfreq = CreateWindow("EDIT","0",WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE,
        560,340,160,20,hw,(HMENU)ID_MAINFREQ,NULL,NULL);
   hw_attconst = CreateWindow("EDIT","0",WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE,
        560,360,160,20,hw,(HMENU)ID_ATTCONST,NULL,NULL);
   hw_powampl = CreateWindow("EDIT","0",WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE,
        560,380,160,20,hw,(HMENU)ID_PWAMPLIT,NULL,NULL);
   hw_powfreq = CreateWindow("EDIT","0",WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE,
        560,400,160,20,hw,(HMENU)ID_PWFREQUE,NULL,NULL);
   hw_startpos = CreateWindow("EDIT","0",WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE,
        560,320,160,20,hw,(HMENU)ID_STARTPOS,NULL,NULL);
   hw_startspd = CreateWindow("EDIT","0",WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE,
        560,300,160,20,hw,(HMENU)ID_STARTSPD,NULL,NULL);

   CreateWindow("STATIC", "X'' + GX'+W1^2X = Acos(W2t)", WS_BORDER|WS_VISIBLE|WS_CHILD, 520, 280, 200, 20, hw, (HMENU)ID_EQUASION, NULL, NULL);
   CreateWindow("STATIC", "W1 = ", WS_BORDER|WS_VISIBLE|WS_CHILD, 520, 340, 40, 20, hw, (HMENU)ID_FIRSTNAM, NULL, NULL);
   CreateWindow("STATIC", "G = ", WS_BORDER|WS_VISIBLE|WS_CHILD, 520, 360, 40, 20, hw, (HMENU)ID_SECONDNM, NULL, NULL);
   CreateWindow("STATIC", "A = ", WS_BORDER|WS_VISIBLE|WS_CHILD, 520, 380, 40, 20, hw, (HMENU)ID_THIRDNAM, NULL, NULL);
   CreateWindow("STATIC", "W2 = ", WS_BORDER|WS_VISIBLE|WS_CHILD, 520, 400, 40, 20, hw, (HMENU)ID_FOURTHNM, NULL, NULL);
   CreateWindow("STATIC", "X0 = ", WS_BORDER|WS_VISIBLE|WS_CHILD, 520, 320, 40, 20, hw, (HMENU)ID_FITHNAME, NULL, NULL);
   CreateWindow("STATIC", "V0 = ", WS_BORDER|WS_VISIBLE|WS_CHILD, 520, 300, 40, 20, hw, (HMENU)ID_SIXTHNAM, NULL, NULL);
   CreateWindow("STATIC", "Эйлер\nh=0,1", WS_BORDER|WS_VISIBLE|WS_CHILD, 370, 300, 60, 40, hw, (HMENU)ID_LINEINF1, NULL, NULL );
   CreateWindow("STATIC", "Эйлер\nh=0,0001", WS_BORDER|WS_VISIBLE|WS_CHILD, 370, 340, 60, 40, hw, (HMENU)ID_LINEINF2, NULL, NULL );
   CreateWindow("STATIC", "Рунге\nКутт\nh=0,1", WS_BORDER|WS_VISIBLE|WS_CHILD, 370, 380, 60, 60, hw, (HMENU)ID_LINEINF3, NULL, NULL );
   CreateWindow("STATIC", "V(T)", WS_BORDER|WS_VISIBLE|WS_CHILD, 0, 0, 30, 20, hw, (HMENU)ID_GRAFINF1, NULL, NULL );
   CreateWindow("STATIC", "X(T)", WS_BORDER|WS_VISIBLE|WS_CHILD, 0, 240, 30, 20, hw, (HMENU)ID_GRAFINF2, NULL, NULL );
   CreateWindow("STATIC", "V(X)", WS_BORDER|WS_VISIBLE|WS_CHILD, 370, 0, 30, 20, hw, (HMENU)ID_GRAFINF3, NULL, NULL );

break;

        case WM_PAINT:
hDC = BeginPaint(hw, &ps);

SelectObject( hDC, Pen3);
SelectObject( hDC, Brush1);

Rectangle( hDC, 0, 0, 739, 479);

SelectObject( hDC, Pen2);

MoveToEx( hDC, 0, 240,NULL );
LineTo( hDC, 739, 240 );
MoveToEx( hDC, 370, 0,NULL );
LineTo( hDC, 370, 489 );

MoveToEx( hDC, 0, 120, NULL ); //30, 120 середина
LineTo( hDC, 739, 120 );
MoveToEx( hDC, 30, 0, NULL );
LineTo( hDC, 30, 489 );

MoveToEx( hDC, 555, 0, NULL ); //555, 120 середина
LineTo( hDC, 555, 240 );

MoveToEx( hDC, 0, 360, NULL); //30, 360 cередина
LineTo( hDC, 370, 360);

SelectObject(hDC, Pen4);

MoveToEx( hDC, 435, 320, NULL);
LineTo( hDC, 475, 320 );

SelectObject(hDC, Pen5);

MoveToEx( hDC, 435, 410, NULL);
LineTo( hDC, 475, 410 );

SelectObject(hDC, Pen1);

MoveToEx( hDC, 435, 360, NULL);
LineTo( hDC, 475, 360 );

//v = 1;

if((x0 != 0) || (v0 != 0)){
        x = x0;
        v = v0;

for(t = -6.0; t <= 11; t = t + 0.0001 ){
    v = v + 0.0001*(a*cos(w2*t)-g*v-w1*w1*x) ;
	x = x+0.0001*v;
	vn = v + 0.0001*(a*cos(w2*t)-g*v-w1*w1*x);
    xn = x+0.0001*v;

if(((20*t+150)<370) && ((-20*x+360)>240) && ((20*(t+0.0001)+150)<370) && ((-20*xn+360)>240)){
	MoveToEx( hDC, 20*t+150, -20*x+360, NULL );
	LineTo( hDC, 20*(t+0.0001)+150, -20*xn+360 );
	}

if(((20*t+150)<370) && ((-20*v+120)<240) && ((20*(t+0.0001)+150)<370) && ((-20*vn+120)<240)){
	MoveToEx( hDC, 20*t+150, -20*v+120, NULL );
	LineTo( hDC, 20*(t+0.0001)+150, -20*vn+120);
}

if(((20*x+555)>370) && ((-20*v+120)<240) && ((20*xn+555)>370) && ((-20*vn+120)<240)){
	MoveToEx( hDC, 20*x+555, -20*v+120, NULL );
	LineTo( hDC, 20*xn+555, -20*vn+120);
	}
}

v = v0;
x = x0;
SelectObject(hDC, Pen4);

for(t = -6.0; t <= 11; t = t + 0.1 ){

    v = v + 0.1*(a*cos(w2*t)-g*v-w1*w1*x) ;
	x = x+0.1*v;

	vn = v + 0.1*(a*cos(w2*t)-g*v-w1*w1*x);
    xn = x+0.1*v;

if(((20*t+150)<370) && ((-20*x+360)>240) && ((20*(t+0.1)+150)<370) && ((-20*xn+360)>240)){
	MoveToEx( hDC, 20*t+150, -20*x+360, NULL );
	LineTo( hDC, 20*(t+0.1)+150, -20*xn+360 );
	}

if(((20*t+150)<370) && ((-20*v+120)<240) && ((20*(t+0.1)+150)<370) && ((-20*vn+120)<240)){
	MoveToEx( hDC, 20*t+150, -20*v+120, NULL );
	LineTo( hDC, 20*(t+0.1)+150, -20*vn+120);
}

if(((20*x+555)>370) && ((-20*v+120)<240) && ((20*xn+555)>370) && ((-20*vn+120)<240)){
	MoveToEx( hDC, 20*x+555, -20*v+120, NULL );
	LineTo( hDC, 20*xn+555, -20*vn+120);
	}
}

v = v0;
x = x0;

SelectObject(hDC, Pen5);

for(t = -6.0; t <= 11; t = t + 0.1 ){
    k1=-(g*v +w1*w1*x)+a*cos(w2*t);
	k2=-(g*(v+k1/2)+w1*w1*x) + a*cos(w2*(t+0.05));
	k3=-(g*(v+k2/2)+w1*w1*x) + a*cos(w2*(t+0.05));
	k4=-(g*(v+k3)+w1*w1*x) + a*cos(w2*(t+0.1));

	v=v+(k1+2*k2+2*k3+k4)/60;
	x=x+0.1*v;

	k1n=-(g*v +w1*w1*x)+a*cos(w2*t);
	k2n=-(g*(v+k1/2)+w1*w1*x) + a*cos(w2*(t+0.05));
	k3n=-(g*(v+k2/2)+w1*w1*x) + a*cos(w2*(t+0.05));
	k4n=-(g*(v+k3)+w1*w1*x) + a*cos(w2*(t+0.1));

	vn=v+(k1n+2*k2n+2*k3n+k4n)/60;
	xn=x+0.1*v;

if(((20*t+150)<370) && ((-20*x+360)>240) && ((20*(t+0.1)+150)<370) && ((-20*xn+360)>240)){
	MoveToEx( hDC, 20*t+150, -20*x+360, NULL );
	LineTo( hDC, 20*(t+0.1)+150, -20*xn+360 );
	}

if(((20*t+150)<370) && ((-20*v+120)<240) && ((20*(t+0.1)+150)<370) && ((-20*vn+120)<240)){
	MoveToEx( hDC, 20*t+150, -20*v+120, NULL );
	LineTo( hDC, 20*(t+0.1)+150, -20*vn+120);
}

if(((20*x+555)>370) && ((-20*v+120)<240) && ((20*xn+555)>370) && ((-20*vn+120)<240)){
	MoveToEx( hDC, 20*x+555, -20*v+120, NULL );
	LineTo( hDC, 20*xn+555, -20*vn+120);
	}
}

}

EndPaint(hw, &ps);
return 0;
break;

  case WM_COMMAND:
   /* нажата наша кнопочка? */
   if ((HIWORD(wp)==0) && (LOWORD(wp)==ID_MYBUTTON)){
   // MessageBox(hw,"You pressed my button","MessageBox",MB_OK|MB_ICONWARNING);

      GetDlgItemText(hw, ID_STARTSPD, LPSTR(V0), 80 );
      GetDlgItemText(hw, ID_STARTPOS, LPSTR(X0), 80 );
      GetDlgItemText(hw, ID_MAINFREQ, LPSTR(W1), 80 );
      GetDlgItemText(hw, ID_ATTCONST, LPSTR(G), 80 );
      GetDlgItemText(hw, ID_PWFREQUE, LPSTR(W2), 80 );
      GetDlgItemText(hw, ID_PWAMPLIT, LPSTR(A), 80 );

      if(V0[0] == 0){
         MessageBox(hw,"Input start speed","ERROR",MB_OK|MB_ICONERROR);
      }
      if(X0[0] == 0){
         MessageBox(hw,"Input start position","ERROR",MB_OK|MB_ICONERROR);
      }
      if(W1[0] == 0){
         MessageBox(hw,"Input main frequency","ERROR",MB_OK|MB_ICONERROR);
      }
      if(G[0] == 0){
         MessageBox(hw,"Input attenuation constant","ERROR",MB_OK|MB_ICONERROR);
      }
      if(W2[0] == 0){
         MessageBox(hw,"Input driving force's frequency","ERROR",MB_OK|MB_ICONERROR);
      }
      if(A[0] == 0){
         MessageBox(hw,"Input driving force's amplitude","ERROR",MB_OK|MB_ICONERROR);
      }

      v0 = atof(V0);
      x0 = atof(X0);
      w1 = atof(W1);
      g = atof(G);
      w2 = atof(W2);
      a = atof(A);

      v = v0;
      x = x0;

        InvalidateRect(hw, NULL, FALSE);
    //  UpdateWindow(hw);
    //MoveWindow(hw, 0, 0, 740, 480, true);
   }
return 0;
  case WM_DESTROY:
   /* пользователь закрыл окно, программа может завершаться */
   PostQuitMessage(0);
   return 0;
 }
 return DefWindowProc(hw,msg,wp,lp);
}