示例#1
0
文件: qlmav.cpp 项目: freesta/ql-mav
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  int wmId, wmEvent;
  PAINTSTRUCT ps;
  HDC hdc;
  HRESULT hResult;

  switch (message)
  {

  case WM_CREATE:
  {
    // Todo: 
    // 1. Put this in an actual panel and make program resizeable (maybe)
    // 2. All those edit boxes should probably be classes...

    int panel_pos_x = 420;
    int panel_pos_y = 10;
    int edit_width = 45;
    int edit_caption_height = 17;
    int caption_width = 47;
    int caption_panel_pos_x = panel_pos_x + edit_width + 10;
    int y_space = 24;

    sens_box = CreateWindow(L"EDIT",
      L"4",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 0, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(sens_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    //SetWindowSubclass(sens_box,ButtonProc,0,0); // 

    accel_box = CreateWindow(L"EDIT",
      L"0",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 1, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(accel_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    offset_box = CreateWindow(L"EDIT",
      L"0",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 2, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(offset_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    senscap_box = CreateWindow(L"EDIT",
      L"0",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 3, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(senscap_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    power_box = CreateWindow(L"EDIT",
      L"2",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 4, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(power_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    m_cpi_box = CreateWindow(L"EDIT",
      L"0",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 5, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(m_cpi_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    fps_box = CreateWindow(L"EDIT",
      L"125",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 6, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(fps_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    x_scale_box = CreateWindow(L"EDIT",
      L"8",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 7, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(x_scale_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    y_scale_box = CreateWindow(L"EDIT",
      L"8",
      WS_BORDER | WS_CHILD | WS_VISIBLE | WS_TABSTOP,
      panel_pos_x, panel_pos_y + y_space * 8, edit_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(y_scale_box, WM_SETFONT, (WPARAM)standard_font, TRUE);

    caption_box = CreateWindow(L"STATIC",
      L"sens",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 0, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"cl_sensitivity");
    CreateToolTipForRect(sens_box, hInst, L"cl_sensitivity");

    caption_box = CreateWindow(L"STATIC",
      L"accel",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 1, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"cl_mouseAccel");
    CreateToolTipForRect(accel_box, hInst, L"cl_mouseAccel");

    caption_box = CreateWindow(L"STATIC",
      L"offset",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 2, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"cl_mouseAccelOffset");
    CreateToolTipForRect(offset_box, hInst, L"cl_mouseAccelOffset");

    caption_box = CreateWindow(L"STATIC",
      L"cap",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 3, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"cl_mouseSensCap");
    CreateToolTipForRect(senscap_box, hInst, L"cl_mouseSensCap");

    caption_box = CreateWindow(L"STATIC",
      L"power",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 4, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"cl_mouseAccelPower");
    CreateToolTipForRect(power_box, hInst, L"cl_mouseAccelPower");

    caption_box = CreateWindow(L"STATIC",
      L"m_cpi",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 5, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"m_cpi");
    CreateToolTipForRect(m_cpi_box, hInst, L"m_cpi");

    caption_box = CreateWindow(L"STATIC",
      L"fps",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 6, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"com_maxfps");
    CreateToolTipForRect(fps_box, hInst, L"com_maxfps");

    caption_box = CreateWindow(L"STATIC",
      L"x-scale",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 7, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"scale for x-axis");
    CreateToolTipForRect(x_scale_box, hInst, L"scale for x-axis");

    caption_box = CreateWindow(L"STATIC",
      L"y-scale",
      WS_CHILD | WS_VISIBLE | SS_NOTIFY,
      caption_panel_pos_x, panel_pos_y + y_space * 8, caption_width, edit_caption_height,
      hWnd, NULL, NULL, NULL);
    SendMessage(caption_box, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(caption_box, hInst, L"scale for y-axis");
    CreateToolTipForRect(y_scale_box, hInst, L"scale for y-axis");


    text_box = CreateWindow(L"STATIC",
      L"If you can see this something is not working.",
      WS_CHILD | WS_VISIBLE,
      10, 220, 400, 30,
      hWnd, NULL, NULL, NULL);

    convert_button = CreateWindow(L"BUTTON",
      L"convert",
      WS_CHILD | WS_VISIBLE | BS_FLAT,
      432, 222, 55, 23,
      hWnd, (HMENU)IDC_CONVERT_BUTTON, NULL, NULL);
    SendMessage(convert_button, WM_SETFONT, (WPARAM)standard_font, TRUE);
    CreateToolTipForRect(convert_button, hInst, L"If m_cpi is set to 0, convert all settings to m_cpi system. Otherwise, convert all settings back.");

    SetWindowLongPtr(text_box, -4, (LONG_PTR)&TextBoxProc);
    break;
  }

  case WM_COMMAND:
    wmId = LOWORD(wParam);
    wmEvent = HIWORD(wParam);
    if (wmEvent == EN_CHANGE) {
      GetWindowText(sens_box, global_temp_string, 10);
      cvar_sens = wcstod(global_temp_string, NULL);
      GetWindowText(offset_box, global_temp_string, 10);
      cvar_offset = wcstod(global_temp_string, NULL);
      GetWindowText(accel_box, global_temp_string, 10);
      cvar_accel = wcstod(global_temp_string, NULL);
      GetWindowText(senscap_box, global_temp_string, 10);
      cvar_senscap = wcstod(global_temp_string, NULL);
      GetWindowText(power_box, global_temp_string, 10);
      cvar_power = wcstod(global_temp_string, NULL) - 1;
      if (cvar_power < 0) cvar_power = 0;
      GetWindowText(m_cpi_box, global_temp_string, 10);
      cvar_m_cpi = wcstod(global_temp_string, NULL);
      GetWindowText(fps_box, global_temp_string, 10);
      max_fps = wcstod(global_temp_string, NULL);
      GetWindowText(x_scale_box, global_temp_string, 10);
      graph_max_x = wcstod(global_temp_string, NULL);
      GetWindowText(y_scale_box, global_temp_string, 10);
      graph_max_y = wcstod(global_temp_string, NULL);
      InvalidateRect(hWnd, &invalidate_rect, false);
    }
    switch (wmId)
    {
    case ID_HELP_ABOUT:
      DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, AboutProc);
      break;
    case ID_FILE_EXIT:
      DestroyWindow(hWnd);
      break;
    case IDC_CONVERT_BUTTON:
      if (cvar_power != 1){
        MessageBeep(1);
        DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG3), hWnd, ErrorProc);
      }
      else {
        if (cvar_m_cpi == 0) {
          DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG2), hWnd, ConvertProc);
        }
        else ConvertFromMcpi();
      }
      break;

    default:
      return DefWindowProc(hWnd, message, wParam, lParam);
    }
    break;

  case WM_INPUT: {

    UINT dwSize;
    GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize,
      sizeof(RAWINPUTHEADER));
    LPBYTE lpb = new BYTE[dwSize];
    if (lpb == NULL)
    {
      return 0;
    }

    if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize,
      sizeof(RAWINPUTHEADER)) != dwSize)
      OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));

    RAWINPUT* raw = (RAWINPUT*)lpb;


    if (raw->header.dwType == RIM_TYPEMOUSE)
    {
      mouse_x_buffer += raw->data.mouse.lLastX;
      mouse_y_buffer += raw->data.mouse.lLastY;

      auto t_end = std::chrono::high_resolution_clock::now();
      double frame_duration = (std::chrono::duration<double, std::micro>(t_end - t_start_frame).count());
      double mouse_input_duration = (std::chrono::duration<double, std::micro>(t_end - t_start_mouse).count());
      double cur_mouse_poll_rate = 1000 * 1000 / mouse_input_duration;

      if ((double)frame_duration + 1000 > 1000 * 1000 / (max_fps)){
        cur_fps = 1 * 1000 * 1000 / frame_duration;
        double mcpi2 = cvar_m_cpi / 2.54;
        double mx = mouse_x_buffer;
        double my = mouse_y_buffer;
        if (mcpi2 > 0) {
          mx = mouse_x_buffer / mcpi2;
          my = mouse_y_buffer / mcpi2;
        }
        speed = sqrt((double)mx*mx + my*my);

        speed = 1000 * speed / frame_duration;
        if (mcpi2 > 0) {
          speed = speed * 1000;
          speed_unit_str = speed_unit_str_cmps;
          move_unit_str = move_unit_str_cmps;
        }
        else {
          speed_unit_str = speed_unit_str_cpms;
          move_unit_str = move_unit_str_cpms;
        }
        hResult = StringCchPrintf(info_string_left, STRSAFE_MAX_CCH, TEXT("mouse speed: %.3f %s\r\nmultiplier: %.3f %s\r\n"),
          speed, speed_unit_str,
          multi, move_unit_str);
        hResult = StringCchPrintf(info_string_right, STRSAFE_MAX_CCH, TEXT("mouse poll rate: %04.0f Hz\r\n%.0f fps"),
          cur_mouse_poll_rate, cur_fps);

        InvalidateRect(text_box, &invalidate_rect_2, false);
        InvalidateRect(hWnd, &invalidate_rect, false);

        if (FAILED(hResult))
        {
          // TODO: write error handler
        }
        // OutputDebugString(info_string_left);
        // Static_SetText(text_box, info_string_left);
        

        t_start_frame = t_end;
        mouse_x_buffer = 0;
        mouse_y_buffer = 0;
      }
      t_start_mouse = t_end;

    }
    delete[] lpb;

    return 0;
  }



  case WM_PAINT:

    hdc = BeginPaint(hWnd, &ps);

    hdc_backbuffer = CreateCompatibleDC(hdc);
    hbm_backbuffer = CreateCompatibleBitmap(hdc, graph_width, graph_height);

    h_old = SelectObject(hdc_backbuffer, hbm_backbuffer);

    FillRect(hdc_backbuffer, &invalidate_rect, black_brush);
    hResult = StringCchPrintf(global_temp_string, STRSAFE_MAX_CCH, TEXT("%.1f [%s]"), graph_max_y, move_unit_str);
    SetTextColor(hdc_backbuffer, 0x00DDDDDD);
    SetBkColor(hdc_backbuffer, 0x00000000);
    SelectObject(hdc_backbuffer, standard_font);
    TextOut(hdc_backbuffer, 3, 0, global_temp_string, wcslen(global_temp_string));
    TextOut(hdc_backbuffer, 3, invalidate_rect.bottom - 27, L"0", 1);

    hResult = StringCchPrintf(global_temp_string, STRSAFE_MAX_CCH, TEXT("[%s] %.1f"), speed_unit_str, graph_max_x);
    SetTextAlign(hdc_backbuffer, TA_RIGHT);
    TextOut(hdc_backbuffer, invalidate_rect.right - 13, invalidate_rect.bottom - 27, global_temp_string, wcslen(global_temp_string));


    //OutputDebugString(global_temp_string);


    for (int i = 0; i<graph_width; i++){
      double x = i*graph_max_x / graph_width;

      double y = cvar_sens + pow((cvar_accel*(x - cvar_offset)), cvar_power);

      if (cvar_offset>x) y = cvar_sens;
      if (y > cvar_senscap && cvar_senscap > 0) y = cvar_senscap;
      int j = graph_height - y*graph_height / graph_max_y;
      SetPixel(hdc_backbuffer, i, j, 0x00BBBBBB);
    }

    multi = cvar_sens + pow((cvar_accel*(speed - cvar_offset)), cvar_power);

    if (cvar_offset > speed) multi = cvar_sens;
    if (multi > cvar_senscap && cvar_senscap > 0) multi = cvar_senscap;
    red_rectangle.top = graph_height - multi*graph_height / graph_max_y - 2;
    red_rectangle.left = speed*graph_width / graph_max_x - 2;
    red_rectangle.right = speed*graph_width / graph_max_x + 3;
    red_rectangle.bottom = graph_height - multi*graph_height / graph_max_y + 3;

    FillRect(hdc_backbuffer, &red_rectangle, red_brush);

    BitBlt(hdc, 10, 10, graph_width, graph_height, hdc_backbuffer, 0, 0, SRCCOPY);


    SelectObject(hdc_backbuffer, h_old);
    DeleteObject(hbm_backbuffer);
    DeleteDC(hdc_backbuffer);


    EndPaint(hWnd, &ps);

    break;
  case WM_CTLCOLORSTATIC:
  {
    HDC hdcStatic = (HDC)wParam;
    SetTextColor(hdcStatic, text_color);
    SetBkColor(hdcStatic, background_color);

    return (INT_PTR)background_brush;
  }
  case WM_DESTROY:
    PostQuitMessage(0);
    break;
  default:
    return DefWindowProc(hWnd, message, wParam, lParam);
  }
  return 0;
}
示例#2
0
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------//
LRESULT CCtlPanel::OnDrawItem (UINT /*uMsg*/, WPARAM wParam,
							   LPARAM lParam, BOOL &bHandled)
{
	UINT idCtl = wParam;
	LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) lParam;

	if (idCtl == IDC_COLOR)
	{
		CAGDC dc (lpdis->hDC);
		HBRUSH hbr = (HBRUSH) GetStockObject (WHITE_BRUSH);
		FillRect (lpdis->hDC, &lpdis->rcItem, hbr);

		if ((int) lpdis->itemID != -1)
		{
			COLORREF clr = (COLORREF) ::SendMessage (lpdis->hwndItem,
			  CB_GETITEMDATA, lpdis->itemID, 0);

			RECT rect = lpdis->rcItem;
			InflateRect (&rect, -4, -2);
			hbr = CreateSolidBrush (clr | PALETTERGB_FLAG);
			FillRect (lpdis->hDC, &rect, hbr);
			DeleteObject (hbr);
			hbr = (HBRUSH) GetStockObject (BLACK_BRUSH);
			FrameRect (lpdis->hDC, &rect, hbr);
		}

		if (lpdis->itemState & ODS_FOCUS || lpdis->itemState & ODS_SELECTED)
		{
			hbr = (HBRUSH) GetStockObject (BLACK_BRUSH);
			FrameRect (lpdis->hDC, &lpdis->rcItem, hbr);
		}
	}
	else if (idCtl == IDC_FONT)
	{
		if ((int) lpdis->itemID != -1)
		{
			int nFont = ::SendMessage (lpdis->hwndItem, CB_GETITEMDATA, lpdis->itemID, 0);

			FONTARRAY &FontArray = GetFontArray ();
			LOGFONT NewFont = FontArray[nFont].lf;
			NewFont.lfHeight = m_nFontHeight;
			NewFont.lfWidth = 0;
			if (NewFont.lfCharSet == SYMBOL_CHARSET)
			{
				lstrcpy (NewFont.lfFaceName, "Arial");
				NewFont.lfCharSet = ANSI_CHARSET;
				NewFont.lfPitchAndFamily = FF_SWISS;
			}

			SaveDC (lpdis->hDC);
			SetTextAlign (lpdis->hDC, TA_LEFT | TA_TOP | TA_NOUPDATECP);

			if (lpdis->itemState & ODS_SELECTED)
				SetTextColor (lpdis->hDC, GetSysColor (COLOR_HIGHLIGHTTEXT));
			else
				SetTextColor (lpdis->hDC, GetSysColor (COLOR_WINDOWTEXT));

			if (lpdis->itemState & ODS_SELECTED)
				SetBkColor (lpdis->hDC, GetSysColor (COLOR_HIGHLIGHT));
			else
				SetBkColor (lpdis->hDC, GetSysColor (COLOR_WINDOW));

			HFONT hFont = CreateFontIndirect (&NewFont);
			HFONT hOldFont = (HFONT) SelectObject (lpdis->hDC, hFont);
			ExtTextOut (lpdis->hDC, lpdis->rcItem.left, lpdis->rcItem.top,
				ETO_CLIPPED | ETO_OPAQUE, &lpdis->rcItem,
				FontArray[nFont].szFullName,
				lstrlen (FontArray[nFont].szFullName), NULL);
  
			if (lpdis->itemState & ODS_FOCUS)
				DrawFocusRect (lpdis->hDC, &lpdis->rcItem);

			SelectObject (lpdis->hDC, hOldFont);
			DeleteObject (hFont);
			RestoreDC (lpdis->hDC, -1);
		}
	}

	bHandled = TRUE;
	return (TRUE);
}
示例#3
0
void map_text(MapGC *mgc, MapSettings *settings,
	      int x, int y, const char *text, int style)
{
  if (FALSE);
#ifdef HAVE_CAIRO
  else if (mgc->cairo_cr)
    {
      int xpos = x;
      int ypos = y;
      cairo_text_extents_t extents;

      cairo_select_font_face(mgc->cairo_cr, "Sans",
			     CAIRO_FONT_SLANT_NORMAL,
			     CAIRO_FONT_WEIGHT_NORMAL);

      if (style & 0x800)
	{
	  if (settings->pdamode)
	    cairo_set_font_size(mgc->cairo_cr, 9);
	  else
	    cairo_set_font_size(mgc->cairo_cr, 14);
	}
      else
	{
	  if (settings->pdamode)
	    cairo_set_font_size(mgc->cairo_cr, 8);
	  else
	    cairo_set_font_size(mgc->cairo_cr, 11);
	}

      cairo_text_extents(mgc->cairo_cr, text, &extents);

      if ((style & 0x300) == 0x100)
	{
	  xpos -= extents.width;
	}
      else if ((style & 0x300) == 0x200)
	{
	  xpos -= extents.width / 2;
	}
      else if ((style & 0x300) == 0x300)
	{
	  xpos -= extents.width / 2;
	  ypos -= extents.height / 2;
	}

      if (style & 0x400)
	map_bkg_rectangle(mgc, settings,
			  xpos, ypos, extents.width, extents.height);

      if (style & 1)
	cairo_set_source_rgb(mgc->cairo_cr, 0, 0, 1);
      else
	cairo_set_source_rgb(mgc->cairo_cr, 0, 0, 0);

      cairo_move_to(mgc->cairo_cr, xpos, ypos + extents.height);
      cairo_show_text(mgc->cairo_cr, text);
    }
#endif
#ifdef HAVE_GTK
  else if (mgc->gtk_drawable)
    {
      int xpos = x;
      int ypos = y;
      int width;
      int height;

      PangoFontDescription *fd;
      PangoLayout *layout =
	gtk_widget_create_pango_layout(mgc->gtk_widget, text);

      if (style & 0x800)
	{
	  if (settings->pdamode)
	    fd = pango_font_description_from_string("Sans 9");
	  else
	    fd = pango_font_description_from_string("Sans 14");
	}
      else
	{
	  if (settings->pdamode)
	    fd = pango_font_description_from_string("Sans 8");
	  else
	    fd = pango_font_description_from_string("Sans 11");
	}

      pango_layout_set_font_description(layout, fd);

      pango_layout_get_pixel_size(layout, &width, &height);

      if ((style & 0x300) == 0x100)
	{
	  xpos -= width;
	}
      else if ((style & 0x300) == 0x200)
	{
	  xpos -= width / 2;
	}
      else if ((style & 0x300) == 0x300)
	{
	  xpos -= width / 2;
	  ypos -= height / 2;
	}

      if (style & 0x400)
	map_bkg_rectangle(mgc, settings,
			  xpos, ypos, width, height);

      if (style & 1)
	gdk_draw_layout_with_colors(mgc->gtk_drawable, mgc->gtk_gc, xpos, ypos,
				    layout, &settings->blue, NULL);
      else
	gdk_draw_layout_with_colors(mgc->gtk_drawable, mgc->gtk_gc, xpos, ypos,
				    layout, &settings->black, NULL);

      if (layout != NULL)
	g_object_unref(G_OBJECT(layout));

      pango_font_description_free(fd);
    }
#endif
#ifdef HAVE_QT
  else if (mgc->qt_painter)
    {
      qt_text(mgc->qt_painter, settings,
	      x, y, text, style);
    }
#endif
#ifdef HAVE_QUARTZ
  else if (mgc->quartz_gc)
    {
      int xpos = x;
      int ypos = y;
      int width;
      int height;

      CGContextSelectFont(mgc->quartz_gc, "Verdana",
			  8, kCGEncodingMacRoman);

      if (style & 0x800)
	{
	  if (settings->pdamode)
	    CGContextSetFontSize(mgc->quartz_gc, 9);
	  else
	    CGContextSetFontSize(mgc->quartz_gc, 14);
	}
      else
	{
	  if (settings->pdamode)
	    CGContextSetFontSize(mgc->quartz_gc, 8);
	  else
	    CGContextSetFontSize(mgc->quartz_gc, 11);
	}

      {
	CGPoint oldPos = CGContextGetTextPosition(mgc->quartz_gc);
	CGContextSetTextDrawingMode(mgc->quartz_gc, kCGTextInvisible);
	CGContextShowText(mgc->quartz_gc, text, strlen(text));
	CGPoint newPos = CGContextGetTextPosition(mgc->quartz_gc);
	CGContextSetTextDrawingMode(mgc->quartz_gc, kCGTextFill);
	CGContextSetTextPosition(mgc->quartz_gc, oldPos.x, oldPos.y);
	width = newPos.x - oldPos.x;
      }

      if ((style & 0x300) == 0x100)
	{
	  xpos -= width;
	}
      else if ((style & 0x300) == 0x200)
	{
	  xpos -= width / 2;
	}
      else if ((style & 0x300) == 0x300)
	{
	  xpos -= width / 2;
	  ypos -= height / 2;
	}

      if (style & 0x400)
	map_bkg_rectangle(mgc, settings,
			  xpos, ypos, width, height);

      if (style & 1)
	CGContextSetRGBStrokeColor(mgc->quartz_gc, 0, 0, 1, 1);
      else
	CGContextSetRGBStrokeColor(mgc->quartz_gc, 0, 0, 0, 1);

      CGContextSetTextPosition(mgc->quartz_gc, xpos, ypos);
      CGContextShowText(mgc->quartz_gc, text, strlen(text));
    }
#endif
#ifdef WIN32
  else if (mgc->win_dc)
    {
      int xpos = x;
      int ypos = y;
      int fontSize;
      HFONT oldFont;
      HFONT font;
      SIZE textSize;

      if (style & 0x800)
	{
	  if (settings->pdamode)
	    fontSize = 9;
	  else
	    fontSize = 14;
	}
      else
	{
	  if (settings->pdamode)
	    fontSize = 8;
	  else
	    fontSize = 11;
	}

      fontSize = fontSize * 3 / 2;

      font = CreateFont(fontSize, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "MSSansSerif");
      oldFont = SelectObject(mgc->win_dc, font);

      GetTextExtentPoint32(mgc->win_dc, text, strlen(text), &textSize);

      if ((style & 0x300) == 0x100)
	{
	  xpos -= textSize.cx;
	}
      else if ((style & 0x300) == 0x200)
	{
	  xpos -= textSize.cx / 2;
	}
      else if ((style & 0x300) == 0x300)
	{
	  xpos -= textSize.cx / 2;
	  ypos -= textSize.cy / 2;
	}

      if (style & 0x400)
	map_bkg_rectangle(mgc, settings,
			  xpos, ypos, textSize.cx, textSize.cy);

      if (style & 1)
	SetTextColor(mgc->win_dc, RGB(0x00, 0x00, 0xff));
      else
	SetTextColor(mgc->win_dc, RGB(0x00, 0x00, 0x00));

      SetBkMode(mgc->win_dc, TRANSPARENT);
      TextOut(mgc->win_dc, xpos, ypos, text, strlen(text));
      SelectObject(mgc->win_dc, oldFont);
      DeleteObject(font);
    }
#endif
}
示例#4
0
static void drawGDIGlyphs(GraphicsContext* graphicsContext, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, 
                      int from, int numGlyphs, const FloatPoint& point)
{
    Color fillColor = graphicsContext->fillColor();

    bool drawIntoBitmap = false;
    int drawingMode = graphicsContext->textDrawingMode();
    if (drawingMode == cTextFill) {
        if (!fillColor.alpha())
            return;

        drawIntoBitmap = fillColor.alpha() != 255 || graphicsContext->inTransparencyLayer();
        if (!drawIntoBitmap) {
            IntSize size;
            int blur;
            Color color;
            graphicsContext->getShadow(size, blur, color);
            drawIntoBitmap = !size.isEmpty() || blur;
        }
    }

    // We have to convert CG's two-dimensional floating point advances to just horizontal integer advances.
    Vector<int, 2048> gdiAdvances;
    int totalWidth = 0;
    for (int i = 0; i < numGlyphs; i++) {
        gdiAdvances.append(lroundf(glyphBuffer.advanceAt(from + i)));
        totalWidth += gdiAdvances[i];
    }

    HDC hdc = 0;
    OwnPtr<GraphicsContext::WindowsBitmap> bitmap;
    IntRect textRect;
    if (!drawIntoBitmap)
        hdc = graphicsContext->getWindowsContext(textRect, true, false);
    if (!hdc) {
        drawIntoBitmap = true;
        // We put slop into this rect, since glyphs can overflow the ascent/descent bounds and the left/right edges.
        // FIXME: Can get glyphs' optical bounds (even from CG) to get this right.
        int lineGap = font->lineGap();
        textRect = IntRect(point.x() - (font->ascent() + font->descent()) / 2, point.y() - font->ascent() - lineGap, totalWidth + font->ascent() + font->descent(), font->lineSpacing());
        bitmap.set(graphicsContext->createWindowsBitmap(textRect.size()));
        memset(bitmap->buffer(), 255, bitmap->bufferLength());
        hdc = bitmap->hdc();

        XFORM xform;
        xform.eM11 = 1.0f;
        xform.eM12 = 0.0f;
        xform.eM21 = 0.0f;
        xform.eM22 = 1.0f;
        xform.eDx = -textRect.x();
        xform.eDy = -textRect.y();
        SetWorldTransform(hdc, &xform);
    }

    SelectObject(hdc, font->m_font.hfont());

    // Set the correct color.
    if (drawIntoBitmap)
        SetTextColor(hdc, RGB(0, 0, 0));
    else
        SetTextColor(hdc, RGB(fillColor.red(), fillColor.green(), fillColor.blue()));

    SetBkMode(hdc, TRANSPARENT);
    SetTextAlign(hdc, TA_LEFT | TA_BASELINE);

    // Uniscribe gives us offsets to help refine the positioning of combining glyphs.
    FloatSize translation = glyphBuffer.offsetAt(from);
    if (translation.width() || translation.height()) {
        XFORM xform;
        xform.eM11 = 1.0;
        xform.eM12 = 0;
        xform.eM21 = 0;
        xform.eM22 = 1.0;
        xform.eDx = translation.width();
        xform.eDy = translation.height();
        ModifyWorldTransform(hdc, &xform, MWT_LEFTMULTIPLY);
    }

    if (drawingMode == cTextFill) {
        XFORM xform;
        xform.eM11 = 1.0;
        xform.eM12 = 0;
        xform.eM21 = font->platformData().syntheticOblique() ? -tanf(syntheticObliqueAngle * piFloat / 180.0f) : 0;
        xform.eM22 = 1.0;
        xform.eDx = point.x();
        xform.eDy = point.y();
        ModifyWorldTransform(hdc, &xform, MWT_LEFTMULTIPLY);
        ExtTextOut(hdc, 0, 0, ETO_GLYPH_INDEX, 0, reinterpret_cast<const WCHAR*>(glyphBuffer.glyphs(from)), numGlyphs, gdiAdvances.data());
        if (font->m_syntheticBoldOffset) {
            xform.eM21 = 0;
            xform.eDx = font->m_syntheticBoldOffset;
            xform.eDy = 0;
            ModifyWorldTransform(hdc, &xform, MWT_LEFTMULTIPLY);
            ExtTextOut(hdc, 0, 0, ETO_GLYPH_INDEX, 0, reinterpret_cast<const WCHAR*>(glyphBuffer.glyphs(from)), numGlyphs, gdiAdvances.data());
        }
    } else {
        RetainPtr<CGMutablePathRef> path(AdoptCF, CGPathCreateMutable());

        XFORM xform;
        GetWorldTransform(hdc, &xform);
        TransformationMatrix hdcTransform(xform.eM11, xform.eM21, xform.eM12, xform.eM22, xform.eDx, xform.eDy);
        CGAffineTransform initialGlyphTransform = hdcTransform.isInvertible() ? hdcTransform.inverse() : CGAffineTransformIdentity;
        if (font->platformData().syntheticOblique())
            initialGlyphTransform = CGAffineTransformConcat(initialGlyphTransform, CGAffineTransformMake(1, 0, tanf(syntheticObliqueAngle * piFloat / 180.0f), 1, 0, 0));
        initialGlyphTransform.tx = 0;
        initialGlyphTransform.ty = 0;
        CGAffineTransform glyphTranslation = CGAffineTransformIdentity;

        for (unsigned i = 0; i < numGlyphs; ++i) {
            RetainPtr<CGPathRef> glyphPath(AdoptCF, createPathForGlyph(hdc, glyphBuffer.glyphAt(from + i)));
            CGAffineTransform glyphTransform = CGAffineTransformConcat(initialGlyphTransform, glyphTranslation);
            CGPathAddPath(path.get(), &glyphTransform, glyphPath.get());
            glyphTranslation = CGAffineTransformTranslate(glyphTranslation, gdiAdvances[i], 0);
        }

        CGContextRef cgContext = graphicsContext->platformContext();
        CGContextSaveGState(cgContext);

        BOOL fontSmoothingEnabled = false;
        SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &fontSmoothingEnabled, 0);
        CGContextSetShouldAntialias(cgContext, fontSmoothingEnabled);

        CGContextScaleCTM(cgContext, 1.0, -1.0);
        CGContextTranslateCTM(cgContext, point.x() + glyphBuffer.offsetAt(from).width(), -(point.y() + glyphBuffer.offsetAt(from).height()));

        if (drawingMode & cTextFill) {
            CGContextAddPath(cgContext, path.get());
            CGContextFillPath(cgContext);
            if (font->m_syntheticBoldOffset) {
                CGContextTranslateCTM(cgContext, font->m_syntheticBoldOffset, 0);
                CGContextAddPath(cgContext, path.get());
                CGContextFillPath(cgContext);
                CGContextTranslateCTM(cgContext, -font->m_syntheticBoldOffset, 0);
            }
        }
        if (drawingMode & cTextStroke) {
            CGContextAddPath(cgContext, path.get());
            CGContextStrokePath(cgContext);
            if (font->m_syntheticBoldOffset) {
                CGContextTranslateCTM(cgContext, font->m_syntheticBoldOffset, 0);
                CGContextAddPath(cgContext, path.get());
                CGContextStrokePath(cgContext);
                CGContextTranslateCTM(cgContext, -font->m_syntheticBoldOffset, 0);
            }
        }
        CGContextRestoreGState(cgContext);
    }

    if (drawIntoBitmap) {
        UInt8* buffer = bitmap->buffer();
        unsigned bufferLength = bitmap->bufferLength();
        for (unsigned i = 0; i < bufferLength; i += 4) {
            // Use green, which is always in the middle.
            UInt8 alpha = (255 - buffer[i + 1]) * fillColor.alpha() / 255;
            buffer[i] = fillColor.blue();
            buffer[i + 1] = fillColor.green();
            buffer[i + 2] = fillColor.red();
            buffer[i + 3] = alpha;
        }
        graphicsContext->drawWindowsBitmap(bitmap.get(), textRect.topLeft());
    } else
        graphicsContext->releaseWindowsContext(hdc, textRect, true, false);
}
示例#5
0
文件: app.c 项目: RorschachUK/Trakr
void DrawMenu()
{
	ClearScreen();
	switch(mode) {
		case 1: { //Step Programming menu
			//Status
			SetTextColor(green);
			DrawText(6, 5, "BigTrakr! Steps: %d", steps);
			//Menu options
			SetTextColor(white);
			DrawText(15, 22, "Forward");
			DrawText(15, 37, "Back");
			DrawText(15, 52, "Right");
			DrawText(15, 67, "Left");
			DrawText(15, 82, "Fire");
			//Menu pointer
			DrawImage(markerImage,5,10+15*menuItem,white);
			//Number (lengths, degrees, lasers)
			SetTextColor(white);
			if(menuItem<3 || menuItem==5) {
				DrawText(90, 7 + 15*menuItem,"%d",menuNum);
			} else if (menuItem < 5) {
				DrawText(90, 7 + 15*menuItem,"%d",menuNum * 15);
			}
			//Number arrows prompting right stick adjustments
			SetTextColor(red);
			//DrawText(90, 13 + 15*(menuItem-1),"^");
			//DrawText(90, 2 + 15*(menuItem+1),"v");
			DrawImage(upImage, 92, 17+15*(menuItem-1), white);
			DrawImage(downImage, 92, 8 + 15*(menuItem+1), white);
			//Button identifiers
			SetTextColor(blue);
			DrawText(6, 100, "Clear");
			DrawText(100,100, "Select");
		}
		break;
		case 2: { //Additional menu
			//Status
			SetTextColor(green);
			DrawText(5, 5, "BigTrakr! Steps: %d", steps);
			//Menu options
			SetTextColor(white);
			DrawText(15, 22, "Free Roam");
			DrawText(15, 37, "Load Route");
			DrawText(15, 52, "Save Route");
			DrawText(15, 67, "Recalibrate");
			DrawText(15, 82, "About");
			//Menu pointer
			DrawImage(markerImage,5,10+15*menuItem,white);
			//Button identifiers
			SetTextColor(blue);
			DrawText(6, 100, "Back");
			DrawText(100,100, "Select");
		}
		break;
		case 3: { //Recalibration mode
			switch(menuNum) {
				case 1: { //Ready
					SetTextColor(white);
					DrawText(6, 7, "To recalibrate");
					DrawText(6, 22, "rotation, press");
					DrawText(6, 37, "Button B to start");
					DrawText(6, 52, "then press again");
					DrawText(6, 67, "to stop when the");
					DrawText(6, 82, "Trakr spins fully");
					SetTextColor(blue);
					DrawText(6, 100, "Cancel");
					DrawText(100,100, "Start");
				}
				break;
				case 2: {
					SetTextColor(white);
					DrawText(6, 22, "Started...");
					DrawText(6, 37, "Let the Trakr");
					DrawText(6, 52, "spin 360 degrees");
					DrawText(6, 67, "then press again");
					SetTextColor(blue);
					DrawText(6, 100, "Cancel");
					DrawText(100,100, "Stop");
				}
				break;
			}
		}
		break;
		case 4: { //Free roam
			SetTextColor(white);
			DrawText(5, 5, "Free Roam");
			SetTextColor(blue);
			if (IRState)
				DrawText(6, 100, "Light off");
			else
				DrawText(6, 100, "Light on");

			DrawText(100,100, "Close");
		}
		break;
		case 5: { //About
			Splash();
			SetTextColor(blue);
			if (IRState)
				DrawText(6, 100, "Light off");
			else
				DrawText(6, 100, "Light on");
			DrawText(100,100, "Close");
		}
	}
	Show();
}
示例#6
0
文件: monslctl.c 项目: GYGit/reactos
static VOID
MonSelPaint(IN OUT PMONITORSELWND infoPtr,
            IN HDC hDC,
            IN const RECT *prcUpdate)
{
    COLORREF crPrevText;
    HBRUSH hbBk, hbOldBk;
    HPEN hpFg, hpOldFg;
    DWORD Index;
    RECT rc, rctmp;
    INT iPrevBkMode;
    BOOL bHideNumber;

    bHideNumber = (infoPtr->ControlExStyle & MSLM_EX_HIDENUMBERS) ||
        ((infoPtr->MonitorsCount == 1) && (infoPtr->ControlExStyle & MSLM_EX_HIDENUMBERONSINGLE));

    hbBk = GetSysColorBrush(COLOR_BACKGROUND);
    hpFg = CreatePen(PS_SOLID,
                     0,
                     GetSysColor(COLOR_HIGHLIGHTTEXT));

    hbOldBk = SelectObject(hDC,
                           hbBk);
    hpOldFg = SelectObject(hDC,
                           hpFg);
    iPrevBkMode = SetBkMode(hDC,
                            TRANSPARENT);
    crPrevText = SetTextColor(hDC,
                              GetSysColor(COLOR_HIGHLIGHTTEXT));

    for (Index = 0; Index < infoPtr->MonitorsCount; Index++)
    {
        if (infoPtr->IsDraggingMonitor &&
            (DWORD)infoPtr->DraggingMonitor == Index)
        {
            continue;
        }

        MonSelRectToScreen(infoPtr,
                           &infoPtr->Monitors[Index].rc,
                           &rc);

        if (IntersectRect(&rctmp,
                          &rc,
                          prcUpdate))
        {
            MonSelPaintMonitor(infoPtr,
                               hDC,
                               Index,
                               &rc,
                               crPrevText,
                               bHideNumber);
        }
    }

    /* Paint the dragging monitor last */
    if (infoPtr->IsDraggingMonitor &&
        infoPtr->DraggingMonitor >= 0)
    {
        MonSelRectToScreen(infoPtr,
                           &infoPtr->rcDragging,
                           &rc);

        if (IntersectRect(&rctmp,
                          &rc,
                          prcUpdate))
        {
            MonSelPaintMonitor(infoPtr,
                               hDC,
                               (DWORD)infoPtr->DraggingMonitor,
                               &rc,
                               crPrevText,
                               bHideNumber);
        }
    }

    SetTextColor(hDC,
                 crPrevText);
    SetBkMode(hDC,
              iPrevBkMode);
    SelectObject(hDC,
                 hpOldFg);
    SelectObject(hDC,
                 hbOldBk);

    DeleteObject(hpFg);
}
示例#7
0
文件: mhtext.c 项目: Agyar/NetHack
LRESULT CALLBACK TextWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	HWND control;
	HDC hdc;
	PNHTextWindow data;
	
	data = (PNHTextWindow)GetWindowLong(hWnd, GWL_USERDATA);
	switch (message) 
	{
	case WM_INITDIALOG:
	    /* set text control font */
		control = GetDlgItem(hWnd, IDC_TEXT_CONTROL);
		if( !control ) {
			panic("cannot get text view window");
		}

		hdc = GetDC(control);
		SendMessage(control, WM_SETFONT, (WPARAM)mswin_get_font(NHW_TEXT, ATR_NONE, hdc, FALSE), 0);
		ReleaseDC(control, hdc);

#if defined(WIN_CE_SMARTPHONE)
		/* special initialization for SmartPhone dialogs */ 
		NHSPhoneDialogSetup(hWnd, FALSE, GetNHApp()->bFullScreen);
#endif
		/* subclass edit control */
		editControlWndProc = (WNDPROC)GetWindowLong(control, GWL_WNDPROC);
		SetWindowLong(control, GWL_WNDPROC, (LONG)NHTextControlWndProc);

		if( !program_state.gameover && GetNHApp()->bWrapText ) {
			DWORD styles;
			styles = GetWindowLong(control, GWL_STYLE);
			if( styles ) {
				SetWindowLong(control, GWL_STYLE, styles & (~WS_HSCROLL));
				SetWindowPos(control, NULL, 0, 0, 0, 0, 
							  SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE );
			}
		}

		SetFocus(control);
	return FALSE;

	case WM_MSNH_COMMAND:
		onMSNHCommand(hWnd, wParam, lParam);
	break;

	case WM_SIZE:
		LayoutText(hWnd);
	return FALSE;

	case WM_COMMAND:
		switch (LOWORD(wParam)) 
        { 
          case IDOK: 
		  case IDCANCEL:
			data->done = 1;
			return TRUE;
		}
	break;

	case WM_CTLCOLORBTN:
	case WM_CTLCOLOREDIT:
	case WM_CTLCOLORSTATIC: { /* sent by edit control before it is drawn */
		HDC hdcEdit = (HDC) wParam; 
		HWND hwndEdit = (HWND) lParam;
		if( hwndEdit == GetDlgItem(hWnd, IDC_TEXT_CONTROL) ) {
			SetBkColor(hdcEdit, mswin_get_color(NHW_TEXT, MSWIN_COLOR_BG));
			SetTextColor(hdcEdit, mswin_get_color(NHW_TEXT, MSWIN_COLOR_FG)); 
			return (BOOL)mswin_get_brush(NHW_TEXT, MSWIN_COLOR_BG);
		}
	} return FALSE;

	case WM_DESTROY:
		if( data ) {
			mswin_free_text_buffer(data->window_text);
			free(data);
			SetWindowLong(hWnd, GWL_USERDATA, (LONG)0);
		}
	break;

	}
	return FALSE;
}
BOOL CALLBACK FunctionListPanel::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
		// Make edit field red if not found
		case WM_CTLCOLOREDIT :
		{
			// if the text not found modify the background color of the editor
			static HBRUSH hBrushBackground = CreateSolidBrush(BCKGRD_COLOR);
			TCHAR text2search[MAX_PATH] ;
			::SendMessage(_hSearchEdit, WM_GETTEXT, MAX_PATH, (LPARAM)text2search);
			if (text2search[0] == '\0')
			{
				return FALSE; // no text, use the default color
			}

			HTREEITEM searchViewRoot = _treeViewSearchResult.getRoot();
			if (searchViewRoot)
			{
				if (_treeViewSearchResult.getChildFrom(searchViewRoot))
					return FALSE; // children on root found, use the default color
			}
			else
				return FALSE; // no root (no parser), use the default color
			// text not found
			SetTextColor((HDC)wParam, TXT_COLOR);
			SetBkColor((HDC)wParam, BCKGRD_COLOR);
			return (LRESULT)hBrushBackground;
		}

        case WM_INITDIALOG :
        {
			int editWidth = 100;
			int editHeight = 20;
			// Create toolbar menu
			//int style = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | TBSTYLE_TOOLTIPS |TBSTYLE_FLAT | CCS_TOP | BTNS_AUTOSIZE | CCS_NOPARENTALIGN | CCS_NORESIZE | CCS_NODIVIDER;
			int style = WS_CHILD | WS_VISIBLE | CCS_ADJUSTABLE | TBSTYLE_AUTOSIZE | TBSTYLE_FLAT | TBSTYLE_LIST | TBSTYLE_TRANSPARENT | BTNS_AUTOSIZE | BTNS_SEP | TBSTYLE_TOOLTIPS;
			_hToolbarMenu = CreateWindowEx(0,TOOLBARCLASSNAME,NULL, style,
								   0,0,0,0,_hSelf,(HMENU)0, _hInst, NULL);
			
			//::GetWindowLongPtr(_hToolbarMenu, GWL_WNDPROC);
			oldFunclstToolbarProc = (WNDPROC)::SetWindowLongPtr(_hToolbarMenu, GWLP_WNDPROC, (LONG_PTR)funclstToolbarProc);
			TBBUTTON tbButtons[3];

			// Add the bmap image into toolbar's imagelist 
			TBADDBITMAP addbmp = {_hInst, 0};
			addbmp.nID = IDI_FUNCLIST_SORTBUTTON;
			::SendMessage(_hToolbarMenu, TB_ADDBITMAP, 1, (LPARAM)&addbmp);
			addbmp.nID = IDI_FUNCLIST_RELOADBUTTON;
			::SendMessage(_hToolbarMenu, TB_ADDBITMAP, 1, (LPARAM)&addbmp);

			// Place holder of search text field
			tbButtons[0].idCommand = 0;
			tbButtons[0].iBitmap = editWidth + 10;
			tbButtons[0].fsState = TBSTATE_ENABLED;
			tbButtons[0].fsStyle = BTNS_SEP;
			tbButtons[0].iString = 0;
			
			tbButtons[1].idCommand = IDC_SORTBUTTON_FUNCLIST;
			tbButtons[1].iBitmap = 0;
			tbButtons[1].fsState =  TBSTATE_ENABLED;
			tbButtons[1].fsStyle = BTNS_CHECK | BTNS_AUTOSIZE;
			tbButtons[1].iString = (INT_PTR)TEXT("");

			tbButtons[2].idCommand = IDC_RELOADBUTTON_FUNCLIST;
			tbButtons[2].iBitmap = 1;
			tbButtons[2].fsState = TBSTATE_ENABLED;
			tbButtons[2].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE;
			tbButtons[2].iString = (INT_PTR)TEXT("");

			::SendMessage(_hToolbarMenu, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
			::SendMessage(_hToolbarMenu, TB_SETBUTTONSIZE , (WPARAM)0, (LPARAM)MAKELONG (16, 16));
			::SendMessage(_hToolbarMenu, TB_ADDBUTTONS,       (WPARAM)sizeof(tbButtons) / sizeof(TBBUTTON),       (LPARAM)&tbButtons);
			::SendMessage(_hToolbarMenu, TB_AUTOSIZE, 0, 0);

			ShowWindow(_hToolbarMenu, SW_SHOW);

			// tips text for toolbar buttons
			NativeLangSpeaker *pNativeSpeaker = (NppParameters::getInstance())->getNativeLangSpeaker();
			_sortTipStr = pNativeSpeaker->getAttrNameStr(_sortTipStr.c_str(), FL_FUCTIONLISTROOTNODE, FL_SORTLOCALNODENAME);
			_reloadTipStr = pNativeSpeaker->getAttrNameStr(_reloadTipStr.c_str(), FL_FUCTIONLISTROOTNODE, FL_RELOADLOCALNODENAME);
			
			_hSearchEdit = CreateWindowEx(0L, L"Edit", NULL, 
                                   WS_CHILD | WS_BORDER | WS_VISIBLE | ES_AUTOVSCROLL, 
                                   2, 2, editWidth, editHeight, 
                                   _hToolbarMenu, (HMENU) IDC_SEARCHFIELD_FUNCLIST, _hInst, 0 );

			HFONT hf = (HFONT)::GetStockObject(DEFAULT_GUI_FONT);

			if (hf)
				::SendMessage(_hSearchEdit, WM_SETFONT, (WPARAM)hf, MAKELPARAM(TRUE, 0));

			_treeViewSearchResult.init(_hInst, _hSelf, IDC_LIST_FUNCLIST_AUX);
			_treeView.init(_hInst, _hSelf, IDC_LIST_FUNCLIST);
			setTreeViewImageList(IDI_FUNCLIST_ROOT, IDI_FUNCLIST_NODE, IDI_FUNCLIST_LEAF);
			
			_treeView.display();
            return TRUE;
        }
		
		case WM_DESTROY:
			_treeView.destroy();
			_treeViewSearchResult.destroy();
			::DestroyWindow(_hToolbarMenu);
			break;

		case WM_COMMAND : 
		{
			if (HIWORD(wParam) == EN_CHANGE)
			{
				switch (LOWORD(wParam))
				{
					case  IDC_SEARCHFIELD_FUNCLIST:
					{
						searchFuncAndSwitchView();
						return TRUE;
					}
				}
			}

			switch (LOWORD(wParam))
            {
				case IDC_SORTBUTTON_FUNCLIST:
				{
					sortOrUnsort();
				}
				return TRUE;

				case IDC_RELOADBUTTON_FUNCLIST:
				{
					reload();
				}
				return TRUE;
			}
		}
		break;
		
		case WM_NOTIFY:
		{
			notified((LPNMHDR)lParam);
		}
		return TRUE;

        case WM_SIZE:
        {
            int width = LOWORD(lParam);
            int height = HIWORD(lParam);
			RECT toolbarMenuRect;
            ::GetClientRect(_hToolbarMenu, &toolbarMenuRect);

            ::MoveWindow(_hToolbarMenu, 0, 0, width, toolbarMenuRect.bottom, TRUE);
			
			HWND hwnd = _treeView.getHSelf();
			if (hwnd)
				::MoveWindow(hwnd, 0, toolbarMenuRect.bottom + 2, width, height - toolbarMenuRect.bottom - 2, TRUE);

			HWND hwnd_aux = _treeViewSearchResult.getHSelf();
			if (hwnd_aux)
				::MoveWindow(hwnd_aux, 0, toolbarMenuRect.bottom + 2, width, height - toolbarMenuRect.bottom - 2, TRUE);
			
            break;
        }

        default :
            return DockingDlgInterface::run_dlgProc(message, wParam, lParam);
    }
	return DockingDlgInterface::run_dlgProc(message, wParam, lParam);
}
示例#9
0
	void CLabelUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
	{
		if( _tcscmp(pstrName, _T("align")) == 0 ) {
			if( _tcsstr(pstrValue, _T("left")) != NULL ) {
				m_uTextStyle &= ~(DT_CENTER | DT_RIGHT | DT_SINGLELINE);
				m_uTextStyle |= DT_LEFT;
			}
			if( _tcsstr(pstrValue, _T("center")) != NULL ) {
				m_uTextStyle &= ~(DT_LEFT | DT_RIGHT );
				m_uTextStyle |= DT_CENTER;
			}
			if( _tcsstr(pstrValue, _T("right")) != NULL ) {
				m_uTextStyle &= ~(DT_LEFT | DT_CENTER | DT_SINGLELINE);
				m_uTextStyle |= DT_RIGHT;
			}
		}
		else if (_tcscmp(pstrName, _T("valign")) == 0)
		{
		    if (_tcsstr(pstrValue, _T("top")) != NULL) {
		        m_uTextStyle &= ~(DT_BOTTOM | DT_VCENTER);
		        m_uTextStyle |= (DT_TOP | DT_SINGLELINE);
		    }
		    if (_tcsstr(pstrValue, _T("vcenter")) != NULL) {
		        m_uTextStyle &= ~(DT_TOP | DT_BOTTOM);
		        m_uTextStyle |= (DT_VCENTER | DT_SINGLELINE);
		    }
		    if (_tcsstr(pstrValue, _T("bottom")) != NULL) {
		        m_uTextStyle &= ~(DT_TOP | DT_VCENTER);
		        m_uTextStyle |= (DT_BOTTOM | DT_SINGLELINE);
		    }
		}
		else if( _tcscmp(pstrName, _T("endellipsis")) == 0 ) {
			if( _tcscmp(pstrValue, _T("true")) == 0 ) m_uTextStyle |= DT_END_ELLIPSIS;
			else m_uTextStyle &= ~DT_END_ELLIPSIS;
		}    
		else if( _tcscmp(pstrName, _T("font")) == 0 ) SetFont(_ttoi(pstrValue));
		else if( _tcscmp(pstrName, _T("textcolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextColor(clrColor);
		}
		else if( _tcscmp(pstrName, _T("disabledtextcolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetDisabledTextColor(clrColor);
		}
		else if( _tcscmp(pstrName, _T("textpadding")) == 0 ) {
			RECT rcTextPadding = { 0 };
			LPTSTR pstr = NULL;
			rcTextPadding.left = _tcstol(pstrValue, &pstr, 10);  ASSERT(pstr);    
			rcTextPadding.top = _tcstol(pstr + 1, &pstr, 10);    ASSERT(pstr);    
			rcTextPadding.right = _tcstol(pstr + 1, &pstr, 10);  ASSERT(pstr);    
			rcTextPadding.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);    
			SetTextPadding(rcTextPadding);
		}
		else if( _tcscmp(pstrName, _T("showhtml")) == 0 ) SetShowHtml(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("enabledeffect")) == 0 ) SetEnabledEffect(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("enabledluminous")) == 0 ) SetEnabledLuminous(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("luminousfuzzy")) == 0 ) SetLuminousFuzzy((float)_tstof(pstrValue));
		else if( _tcscmp(pstrName, _T("gradientangle")) == 0 ) SetGradientAngle(_ttoi(pstrValue));
		else if( _tcscmp(pstrName, _T("enabledstroke")) == 0 ) SetEnabledStroke(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("enabledshadow")) == 0 ) SetEnabledShadow(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("gradientlength")) == 0 ) SetGradientLength(_ttoi(pstrValue));
		else if( _tcscmp(pstrName, _T("shadowoffset")) == 0 ){
			LPTSTR pstr = NULL;
			int offsetx = _tcstol(pstrValue, &pstr, 10);	ASSERT(pstr);    
			int offsety = _tcstol(pstr + 1, &pstr, 10);		ASSERT(pstr);
			SetShadowOffset(offsetx,offsety);
		}
		else if( _tcscmp(pstrName, _T("textcolor1")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextColor1(clrColor);
		}
		else if( _tcscmp(pstrName, _T("textshadowcolora")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextShadowColorA(clrColor);
		}
		else if( _tcscmp(pstrName, _T("textshadowcolorb")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextShadowColorB(clrColor);
		}
		else if( _tcscmp(pstrName, _T("strokecolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetStrokeColor(clrColor);
		}
		else CControlUI::SetAttribute(pstrName, pstrValue);
	}
示例#10
0
/**
* Responsible for drawing each list item.
*/
void ToggleListView::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) {

	CListCtrl& ListCtrl=GetListCtrl();
	int nItem = lpDrawItemStruct->itemID;
	
	// get item data
	LV_ITEM lvi;
	_TCHAR szBuff[MAX_PATH];
	
	memset(&lvi, 0, sizeof(LV_ITEM));
	lvi.mask = LVIF_TEXT;
	lvi.iItem = nItem;
	lvi.pszText = szBuff;
	lvi.cchTextMax = sizeof(szBuff);
	ListCtrl.GetItem(&lvi);

	RECT rDraw;
	
	
	CopyRect ( &rDraw, &lpDrawItemStruct->rcItem );
	rDraw.right = rDraw.left + TOGGLELIST_ITEMHEIGHT;
	rDraw.top ++;

	rDraw.right ++;
	FrameRect ( lpDrawItemStruct->hDC, &rDraw, (HBRUSH)GetStockObject ( BLACK_BRUSH ) );
	rDraw.right --;

	FillRect ( lpDrawItemStruct->hDC, &rDraw, GetSysColorBrush ( COLOR_3DFACE ) );

	Draw3dRect ( lpDrawItemStruct->hDC, &rDraw, GetSysColorBrush ( COLOR_3DHILIGHT ), GetSysColorBrush ( COLOR_3DSHADOW ) );

	InflateRect ( &rDraw, -3, -3 );
	Draw3dRect ( lpDrawItemStruct->hDC, &rDraw, GetSysColorBrush ( COLOR_3DSHADOW ), GetSysColorBrush ( COLOR_3DHILIGHT ) );

	switch(GetToggleState(lvi.iItem)) {
		case TOGGLE_STATE_DISABLED:
			if(disabledIcon) {
				DrawIconEx ( lpDrawItemStruct->hDC, rDraw.left, rDraw.top, disabledIcon, 16, 16,0, NULL, DI_NORMAL );
			}
			break;
		case TOGGLE_STATE_ON:
			if(onIcon) {
				DrawIconEx ( lpDrawItemStruct->hDC, rDraw.left, rDraw.top, onIcon, 16, 16,0, NULL, DI_NORMAL );
			}
			break;
		case TOGGLE_STATE_OFF:
			if(offIcon) {
				DrawIconEx ( lpDrawItemStruct->hDC, rDraw.left, rDraw.top, offIcon, 16, 16,0, NULL, DI_NORMAL );
			}
			break;
	};
	
	CopyRect ( &rDraw, &lpDrawItemStruct->rcItem );
	rDraw.left += TOGGLELIST_ITEMHEIGHT;
	rDraw.left += 1;

	if ( lpDrawItemStruct->itemState & ODS_SELECTED ) {
		FillRect ( lpDrawItemStruct->hDC, &rDraw, GetSysColorBrush ( COLOR_HIGHLIGHT ) );			
	} else {
		FillRect ( lpDrawItemStruct->hDC, &rDraw, GetSysColorBrush ( COLOR_WINDOW ) ); 
	}

	rDraw.left += TEXT_OFFSET;

	int colorIndex = ( (lpDrawItemStruct->itemState & ODS_SELECTED ) ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT );
	SetTextColor ( lpDrawItemStruct->hDC, GetSysColor ( colorIndex ) );
	DrawText ( lpDrawItemStruct->hDC, szBuff, strlen(szBuff), &rDraw, DT_LEFT|DT_VCENTER|DT_SINGLELINE );

}
示例#11
0
JNIEXPORT jlong JNICALL
Java_sun_font_FileFontStrike__1getGlyphImageFromWindows
(JNIEnv *env, jobject unused,
 jstring fontFamily, jint style, jint size, jint glyphCode, jboolean fm) {

    GLYPHMETRICS glyphMetrics;
    LOGFONTW lf;
    BITMAPINFO bmi;
    TEXTMETRIC textMetric;
    RECT rect;
    int bytesWidth, dibBytesWidth, extra, imageSize, dibImageSize;
    unsigned char* dibImage = NULL, *rowPtr, *pixelPtr, *dibPixPtr, *dibRowPtr;
    unsigned char r,g,b;
    unsigned char* igTable;
    GlyphInfo* glyphInfo = NULL;
    int nameLen;
    LPWSTR name;
    HFONT oldFont, hFont;
    MAT2 mat2;

    unsigned short width;
    unsigned short height;
    short advanceX;
    short advanceY;
    int topLeftX;
    int topLeftY;
    int err;
    int bmWidth, bmHeight;
    int x, y;
    HBITMAP hBitmap = NULL, hOrigBM;
    int gamma, orient;

    HWND hWnd = NULL;
    HDC hDesktopDC = NULL;
    HDC hMemoryDC = NULL;

    hWnd = GetDesktopWindow();
    hDesktopDC = GetWindowDC(hWnd);
    if (hDesktopDC == NULL) {
        return (jlong)0;
    }
    if (GetDeviceCaps(hDesktopDC, BITSPIXEL) < 15) {
        FREE_AND_RETURN;
    }

    hMemoryDC = CreateCompatibleDC(hDesktopDC);
    if (hMemoryDC == NULL || fontFamily == NULL) {
        FREE_AND_RETURN;
    }
    err = SetMapMode(hMemoryDC, MM_TEXT);
    if (err == 0) {
        FREE_AND_RETURN;
    }

    memset(&lf, 0, sizeof(LOGFONTW));
    lf.lfHeight = -size;
    lf.lfWeight = (style & 1) ? FW_BOLD : FW_NORMAL;
    lf.lfItalic = (style & 2) ? 0xff : 0;
    lf.lfCharSet = DEFAULT_CHARSET;
    lf.lfQuality = CLEARTYPE_QUALITY;
    lf.lfOutPrecision = OUT_TT_PRECIS;
    lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
    lf.lfPitchAndFamily = DEFAULT_PITCH;

    nameLen = (*env)->GetStringLength(env, fontFamily);
    name = (LPWSTR)alloca((nameLen+1)*2);
    if (name == NULL) {
       FREE_AND_RETURN;
    }
    (*env)->GetStringRegion(env, fontFamily, 0, nameLen, name);
    name[nameLen] = '\0';

    if (nameLen < (sizeof(lf.lfFaceName) / sizeof(lf.lfFaceName[0]))) {
        wcscpy(lf.lfFaceName, name);
    } else {
        FREE_AND_RETURN;
    }

    hFont = CreateFontIndirectW(&lf);
    if (hFont == NULL) {
        FREE_AND_RETURN;
    }
    oldFont = SelectObject(hMemoryDC, hFont);

    memset(&textMetric, 0, sizeof(TEXTMETRIC));
    err = GetTextMetrics(hMemoryDC, &textMetric);
    if (err == 0) {
        FREE_AND_RETURN;
    }
    memset(&glyphMetrics, 0, sizeof(GLYPHMETRICS));
    memset(&mat2, 0, sizeof(MAT2));
    mat2.eM11.value = 1; mat2.eM22.value = 1;
    err = GetGlyphOutline(hMemoryDC, glyphCode,
                          GGO_METRICS|GGO_GLYPH_INDEX,
                          &glyphMetrics,
                          0, NULL, &mat2);
    if (err == GDI_ERROR) {
        /* Probably no such glyph - ie the font wasn't the one we expected. */
        FREE_AND_RETURN;
    }

    width  = (unsigned short)glyphMetrics.gmBlackBoxX;
    height = (unsigned short)glyphMetrics.gmBlackBoxY;

    /* Don't handle "invisible" glyphs in this code */
    if (width <= 0 || height == 0) {
       FREE_AND_RETURN;
    }

    advanceX = glyphMetrics.gmCellIncX;
    advanceY = glyphMetrics.gmCellIncY;
    topLeftX = glyphMetrics.gmptGlyphOrigin.x;
    topLeftY = glyphMetrics.gmptGlyphOrigin.y;

    /* GetGlyphOutline pre-dates cleartype and I'm not sure that it will
     * account for all pixels touched by the rendering. Need to widen,
     * and also adjust by one the x position at which it is rendered.
     * The extra pixels of width are used as follows :
     * One extra pixel at the left and the right will be needed to absorb
     * the pixels that will be touched by filtering by GDI to compensate
     * for colour fringing.
     * However there seem to be some cases where GDI renders two extra
     * pixels to the right, so we add one additional pixel to the right,
     * and in the code that copies this to the image cache we test for
     * the (rare) cases when this is touched, and if its not reduce the
     * stated image width for the blitting loops.
     * For fractional metrics :
     * One extra pixel at each end to account for sub-pixel positioning used
     * when fractional metrics is on in LCD mode.
     * The pixel at the left is needed so the blitting loop can index into
     * that a byte at a time to more accurately position the glyph.
     * The pixel at the right is needed so that when such indexing happens,
     * the blitting still can use the same width.
     * Consequently the width that is specified for the glyph is one less
     * than that of the actual image.
     * Note that in the FM case as a consequence we need to adjust the
     * position at which GDI renders, and the declared width of the glyph
     * See the if (fm) {} cases in the code.
     * For the non-FM case, we not only save 3 bytes per row, but this
     * prevents apparent glyph overlapping which affects the rendering
     * performance of accelerated pipelines since it adds additional
     * read-back requirements.
     */
    width+=3;
    if (fm) {
        width+=1;
    }
    /* DIB scanline must end on a DWORD boundary. We specify 3 bytes per pixel,
     * so must round up as needed to a multiple of 4 bytes.
     */
    dibBytesWidth = bytesWidth = width*3;
    extra = dibBytesWidth % 4;
    if (extra != 0) {
        dibBytesWidth += (4-extra);
    }
    /* The glyph cache image must be a multiple of 3 bytes wide. */
    extra = bytesWidth % 3;
    if (extra != 0) {
        bytesWidth += (3-extra);
    }
    bmWidth = width;
    bmHeight = height;

    /* Must use desktop DC to create a bitmap of that depth */
    hBitmap = CreateCompatibleBitmap(hDesktopDC, bmWidth, bmHeight);
    if (hBitmap == NULL) {
        FREE_AND_RETURN;
    }
    hOrigBM = (HBITMAP)SelectObject(hMemoryDC, hBitmap);

    /* Fill in black */
    rect.left = 0;
    rect.top = 0;
    rect.right = bmWidth;
    rect.bottom = bmHeight;
    FillRect(hMemoryDC, (LPRECT)&rect, GetStockObject(BLACK_BRUSH));

    /* Set text color to white, background to black. */
    SetBkColor(hMemoryDC, RGB(0,0,0));
    SetTextColor(hMemoryDC, RGB(255,255,255));

    /* adjust rendering position */
    x = -topLeftX+1;
    if (fm) {
        x += 1;
    }
    y = topLeftY - textMetric.tmAscent;
    err = ExtTextOutW(hMemoryDC, x, y, ETO_GLYPH_INDEX|ETO_OPAQUE,
                (LPRECT)&rect, (LPCWSTR)&glyphCode, 1, NULL);
    if (err == 0) {
        FREE_AND_RETURN;
    }

    /* Now get the image into a DIB.
     * MS docs for GetDIBits says the compatible bitmap must not be
     * selected into a DC, so restore the original first.
     */
    SelectObject(hMemoryDC, hOrigBM);
    SelectObject(hMemoryDC, oldFont);
    DeleteObject(hFont);

    memset(&bmi, 0, sizeof(BITMAPINFO));
    bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
    bmi.bmiHeader.biWidth = width;
    bmi.bmiHeader.biHeight = -height;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 24;
    bmi.bmiHeader.biCompression = BI_RGB;

    dibImageSize = dibBytesWidth*height;
    dibImage = malloc(dibImageSize);
    if (dibImage == NULL) {
        FREE_AND_RETURN;
    }
    memset(dibImage, 0, dibImageSize);

    err = GetDIBits(hMemoryDC, hBitmap, 0, height, dibImage,
                    &bmi, DIB_RGB_COLORS);

    if (err == 0) {        /* GetDIBits failed. */
        FREE_AND_RETURN;
    }

    err = SystemParametersInfo(SPI_GETFONTSMOOTHINGORIENTATION, 0, &orient, 0);
    if (err == 0) {
        FREE_AND_RETURN;
    }
    err = SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &gamma, 0);
    if (err == 0) {
        FREE_AND_RETURN;
    }
    igTable = getIGTable(gamma/10);
    if (igTable == NULL) {
        FREE_AND_RETURN;
    }

    /* Now copy glyph image into a GlyphInfo structure and return it.
     * NB the xadvance calculated here may be overwritten by the caller.
     * 1 is subtracted from the bitmap width to get the glyph width, since
     * that extra "1" was added as padding, so the sub-pixel positioning of
     * fractional metrics could index into it.
     */
    imageSize = bytesWidth*height;
    glyphInfo = (GlyphInfo*)malloc(sizeof(GlyphInfo)+imageSize);
    if (glyphInfo == NULL) {
        FREE_AND_RETURN;
    }
    glyphInfo->cellInfo = NULL;
    glyphInfo->rowBytes = bytesWidth;
    glyphInfo->width = width;
    if (fm) {
        glyphInfo->width -= 1; // must subtract 1
    }
    glyphInfo->height = height;
    glyphInfo->advanceX = advanceX;
    glyphInfo->advanceY = advanceY;
    glyphInfo->topLeftX = (float)(topLeftX-1);
    if (fm) {
        glyphInfo->topLeftX -= 1;
    }
    glyphInfo->topLeftY = (float)-topLeftY;
    glyphInfo->image = (unsigned char*)glyphInfo+sizeof(GlyphInfo);
    memset(glyphInfo->image, 0, imageSize);

    /* DIB 24bpp data is always stored in BGR order, but we usually
     * need this in RGB, so we can't just memcpy and need to swap B and R.
     * Also need to apply inverse gamma adjustment here.
     * We re-use the variable "extra" to see if the last pixel is touched
     * at all. If its not we can reduce the glyph image width. This comes
     * into play in some cases where GDI touches more pixels than accounted
     * for by increasing width by two pixels over the B&W image. Whilst
     * the bytes are in the cache, it doesn't affect rendering performance
     * of the hardware pipelines.
     */
    extra = 0;
    if (fm) {
        extra = 1; // always need it.
    }
    dibRowPtr = dibImage;
    rowPtr = glyphInfo->image;
    for (y=0;y<height;y++) {
        pixelPtr = rowPtr;
        dibPixPtr = dibRowPtr;
        for (x=0;x<width;x++) {
            if (orient == FE_FONTSMOOTHINGORIENTATIONRGB) {
                b = *dibPixPtr++;
                g = *dibPixPtr++;
                r = *dibPixPtr++;
            } else {
                r = *dibPixPtr++;
                g = *dibPixPtr++;
                b = *dibPixPtr++;
            }
            *pixelPtr++ = igTable[r];
            *pixelPtr++ = igTable[g];
            *pixelPtr++ = igTable[b];
            if (!fm && (x==(width-1)) && (r|g|b)) {
                extra = 1;
            }
        }
        dibRowPtr += dibBytesWidth;
        rowPtr  += bytesWidth;
    }
    if (!extra) {
        glyphInfo->width -= 1;
    }

    free(dibImage);
    ReleaseDC(hWnd, hDesktopDC);
    DeleteObject(hMemoryDC);
    DeleteObject(hBitmap);

    return ptr_to_jlong(glyphInfo);
}
示例#12
0
文件: ui.c 项目: fwqcuc/samples
void GamePaint(HWND hwnd)
{
	/*******************************************************************************
	* ##########   关于 GDI    ##########
	*
	* GDI的全称是Graphics Device Interface,图形设备接口。
	* GDI是Windows系统中最基础的图形图像接口,我们在这里演示的是GDI中最基础的部分,
	* 但是对于编写贪吃蛇这样的小游戏已经足够用了。
	*
	* 来看GDI最基础的三个概念:
	* 1、DC:DC的全称是Device Context,绘制操作在此进行。可以类比理解为一块画布,对应屏幕的一个区域。
	*      GDI的绘制操作必须在一个DC上进行,因此第一步就是得到DC的句柄,BeginPaint或者GetDC函数。
	* 2、GDI对象:包括PEN、BRUSH、FONT等,每一种绘制操作都会使用到一个或者多个GDI对象,
	*      所以,在绘制操作之前必须的一个操作是将绘制所用的GDI对象放入DC中,使用SelectObject函数完成。
	* 3、绘制操作:即在DC上使用被选择如DC中的GDI对象绘制图形、线条、文字等。
	*      如LineTo画出线条、Ellipse画出(椭)圆、Rectangle画出矩形、TextOut输出文字
	*
	* 使用GDI输出各类图像有其特定的流程,如下:
	*******************************************************************************/

	HPEN hpen;
	//HBRUSH hbrush;
	HDC hdc, hdcmem;
	HBITMAP hbmMem;

	HPEN hPenBoundary;
	HPEN hOldPen;

	HBRUSH hbrushFood;
	HBRUSH hBrushSnake;
	HBRUSH hOldBrush;

	HFONT hFont, hOldFont;

	RECT rect;

	PGAME_COORD pSnakeBody;
	PGAME_COORD lpFood;
	int i, snake_size;

	GetClientRect(hwnd, &rect);

	hdc = GetDC(hwnd);

	// 注意 CreateCompatibleDC 中的这一段话:
	// Before an application can use a memory DC for drawing operations, 
	// it must select a bitmap of the correct width and height into the DC. 
	// To select a bitmap into a DC, use the CreateCompatibleBitmap function
	// 注意:
	// http://msdn.microsoft.com/en-us/library/windows/desktop/dd183488(v=vs.85).aspx
	hdcmem = CreateCompatibleDC(hdc);
	hbmMem = CreateCompatibleBitmap(hdc,
		rect.right - rect.left, rect.bottom - rect.top);

	SelectObject(hdcmem, hbmMem);

	// 创建需要用到的PEN和BRUSH
	hbrushFood = CreateSolidBrush(COLOR_FOOD); // RGB颜色,实心BRUSH
	hpen = CreatePen(PS_NULL, 0, RGB(0, 0, 0));  // PEN, PS_NULL表示不可见
	hBrushSnake = CreateSolidBrush(COLOR_SNAKE);
	hPenBoundary = CreatePen(0, 3, COLOR_BOUNDARY);


	/*******************************************************************************
	* #############  画背景  ################
	*
	*******************************************************************************/
	FillRect(hdcmem, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));

	/*******************************************************************************
	* #############  画食物  ################
	*
	*******************************************************************************/

	// 将画图需要用的PEN和BRUSH选择到DC中
	hOldBrush = (HBRUSH)SelectObject(hdcmem, hbrushFood);
	hOldPen = (HPEN)SelectObject(hdcmem, hpen);

	lpFood = GetFood();

	// (椭)圆形,使用上面选择的PEN勾勒边框,BRUSH填充
	Rectangle(hdcmem,
		lpFood->x * CELL_PIXEL + rectBoundary.left,
		lpFood->y * CELL_PIXEL + rectBoundary.top,
		(lpFood->x + 1)*CELL_PIXEL + rectBoundary.left,
		(lpFood->y + 1)*CELL_PIXEL + rectBoundary.top);

	/*******************************************************************************
	* #############  画蛇  ################
	*
	*******************************************************************************/

	SelectObject(hdcmem, hBrushSnake);

	snake_size = GetSnakeSize();

	for (i = 0; i < snake_size; i++)
	{
		pSnakeBody = (PGAME_COORD)GetSnakeAt(i);
		Rectangle(hdcmem,
			pSnakeBody->x * CELL_PIXEL + rectBoundary.left,
			pSnakeBody->y * CELL_PIXEL + rectBoundary.top,
			(pSnakeBody->x + 1)*CELL_PIXEL + rectBoundary.left,
			(pSnakeBody->y + 1)*CELL_PIXEL + rectBoundary.top);
	}

	/*******************************************************************************
	* #############  画墙  ################
	*
	*******************************************************************************/

	SelectObject(hdcmem, hPenBoundary);

	// 将PEN移动到需要绘制的方框的左上角
	MoveToEx(hdcmem, rectBoundary.left, rectBoundary.top, NULL);
	// 画了一个方框。演示LineTo函数
	LineTo(hdcmem, rectBoundary.left, rectBoundary.bottom);
	LineTo(hdcmem, rectBoundary.right, rectBoundary.bottom);
	LineTo(hdcmem, rectBoundary.right, rectBoundary.top);
	LineTo(hdcmem, rectBoundary.left, rectBoundary.top);

	/*******************************************************************************
	* #############  写一行字  ################
	*
	*******************************************************************************/

	// 创建了一个字体对象
	hFont = CreateFont(48, 0, 0, 0, FW_DONTCARE, 0, 1, 0, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS,
		CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Consolas"));

	// 将这个FONT对象放入DC中
	if (hOldFont = (HFONT)SelectObject(hdcmem, hFont))
	{
		CHAR szSourceInfo[1024];
		wsprintf(szSourceInfo, "score %d level %d", GetScore(), GetLevel());
		// 设置输出颜色
		SetTextColor(hdcmem, COLOR_TEXT);
		// 输出字符串。
		TextOut(hdcmem, rectBoundary.left + 3, rectBoundary.bottom + 3,
			szSourceInfo, lstrlen(szSourceInfo));
		// 输出完成,将原来的字体对象放回DC中
		SelectObject(hdcmem, hOldFont);
	}

	// 在内存DC中画完,一次输出的窗口DC上。
	BitBlt(hdc,
		0, 0, rect.right - rect.left, rect.bottom - rect.top,
		hdcmem, 0, 0, SRCCOPY);

	/*******************************************************************************
	* #############  回收和释放资源  ################
	*
	*******************************************************************************/
	// 回收资源
	// DeleteObject 释放GDI对象
	DeleteObject(hbmMem);
	DeleteObject(hdcmem);
	DeleteObject(hbrushFood);
	DeleteObject(hBrushSnake);
	DeleteObject(hpen);
	DeleteObject(hPenBoundary);
	DeleteObject(hFont);
	/*******************************************************************************
	* #############  ReleaseDC 函数  ################
	* 释放占用的DC等系统资源。
	*******************************************************************************/
	ReleaseDC(hwnd, hdc);
}
示例#13
0
void CTetrisDlg::UpdateWindow()
{
    CDC wndMemDC;
    wndMemDC.CreateCompatibleDC(&m_memDC);
    wndMemDC.SelectObject(m_window);
    BLENDFUNCTION bf;
    bf.BlendOp = AC_SRC_OVER;
    bf.BlendFlags = 0;
    bf.SourceConstantAlpha = 255;
    bf.AlphaFormat = AC_SRC_ALPHA;
    ::AlphaBlend(m_memDC, 328, 10, 308, 629, wndMemDC, 0, 0, 308, 629, bf);
    wndMemDC.DeleteDC();

    SetFontSize(30);
    CString str;
    DrawText(360, 32, 600, 64, str = "NEXT TETROMINO:", DT_LEFT);
    CDC blockMemDC;
    blockMemDC.CreateCompatibleDC(&m_memDC);
    blockMemDC.SelectObject(m_block);
    BYTE x = (m_nextColor - 1) << 5;
    switch((m_gameParam & 0xE0) >> 5)
    {
    case 1:
        m_memDC.StretchBlt(414, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(446, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(478, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(510, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        break;
    case 2:
        m_memDC.StretchBlt(430, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(462, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(494, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(494, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        break;
    case 3:
        m_memDC.StretchBlt(430, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(462, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(494, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(430, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        break;
    case 4:
        m_memDC.StretchBlt(446, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(478, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(446, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(478, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        break;
    case 5:
        m_memDC.StretchBlt(462, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(494, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(430, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(462, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        break;
    case 6:
        m_memDC.StretchBlt(430, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(462, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(494, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(462, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        break;
    case 7:
        m_memDC.StretchBlt(430, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(462, 96, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(462, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
        m_memDC.StretchBlt(494, 128, 32, 32, &blockMemDC, x, 0, 32, 32, SRCCOPY);
    }
    blockMemDC.DeleteDC();
    DrawText(360, 192, 600, 224, str = "LEVEL:", DT_LEFT);
    str.Format(_T("%d"), m_level + 1);
    DrawText(360, 192, 600, 224, str, DT_RIGHT);
    DrawText(360, 256, 600, 288, str = "SCORE:", DT_LEFT);
    str.Format(_T("%d"), m_score);
    DrawText(360, 256, 600, 288, str, DT_RIGHT);
    DrawText(360, 320, 600, 352, str = "LINES:", DT_LEFT);
    str.Format(_T("%d"), m_lines);
    DrawText(360, 320, 600, 352, str, DT_RIGHT);
    SetFontSize(m_mouseOver == 0x01 ? 36 : 30);
    DrawText(360, 384, 600, 416, str = "NEW", DT_CENTER);
    if(!(m_gameParam & 0x01) || (m_gameParam & 0x04))
    {
        SetFontSize(30);
        DrawText(400, 448, 560, 480, str = "PAUSE", DT_LEFT, 0xA0A0A0);
        DrawText(400, 448, 560, 480, str = "STOP", DT_RIGHT, 0xA0A0A0);
    }
    else
    {
        SetFontSize(m_mouseOver == 0x02 ? 36 : 30);
        DrawText(400, 448, 560, 480, str = "PAUSE", DT_LEFT, m_gameParam & 0x02 ? 0x0000FF : 0xFFFFFF);
        SetFontSize(m_mouseOver == 0x04 ? 36 : 30);
        DrawText(400, 448, 560, 480, str = "STOP", DT_RIGHT, 0xFFFFFF);
    }
    SetFontSize(m_mouseOver == 0x08 ? 36 : 30);
    SetTextColor(m_memDC, 0xFFFFFF);
    DrawText(360, 512, 600, 544, str = "SOUND", DT_CENTER, m_gameParam & 0x08 ? 0x0000FF : 0xFFFFFF);
    SetFontSize(m_mouseOver == 0x10 ? 36 : 30);
    DrawText(360, 576, 600, 608, str = "EXIT", DT_CENTER);
}
示例#14
0
文件: mhmenu.c 项目: yzh/yzhack
LRESULT CALLBACK MenuWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PNHMenuWindow data;
	
	CheckInputDialog(hWnd, message, wParam, lParam);	

	data = (PNHMenuWindow)GetWindowLong(hWnd, GWL_USERDATA);
	switch (message) 
	{
	case WM_INITDIALOG: {
		HWND text_control;
		HDC hDC;

		text_control = GetDlgItem(hWnd, IDC_MENU_TEXT);

		data = (PNHMenuWindow)malloc(sizeof(NHMenuWindow));
		ZeroMemory(data, sizeof(NHMenuWindow));
		data->type = MENU_TYPE_TEXT;
		data->how = PICK_NONE;
		data->result = 0;
		data->done = 0;
		data->bmpChecked = LoadBitmap(GetNHApp()->hApp, MAKEINTRESOURCE(IDB_MENU_SEL));
		data->bmpCheckedCount = LoadBitmap(GetNHApp()->hApp, MAKEINTRESOURCE(IDB_MENU_SEL_COUNT));
		data->bmpNotChecked = LoadBitmap(GetNHApp()->hApp, MAKEINTRESOURCE(IDB_MENU_UNSEL));
		SetWindowLong(hWnd, GWL_USERDATA, (LONG)data);

		/* subclass edit control */
		editControlWndProc = (WNDPROC)GetWindowLong(text_control, GWL_WNDPROC);
		SetWindowLong(text_control, GWL_WNDPROC, (LONG)NHMenuTextWndProc);

		/* set text window font */
		hDC = GetDC(text_control);
		SendMessage(
			text_control, 
			WM_SETFONT, 
			(WPARAM)mswin_get_font(NHW_TEXT, ATR_NONE, hDC, FALSE),
			(LPARAM)0
		);
		ReleaseDC(text_control, hDC);

#if defined(WIN_CE_SMARTPHONE)
		/* special initialization for SmartPhone dialogs */ 
		NHSPhoneDialogSetup(hWnd, FALSE, GetNHApp()->bFullScreen);
#endif
	} break;

	case WM_MSNH_COMMAND:
		onMSNHCommand(hWnd, wParam, lParam);
	break;

	case WM_SIZE:
		LayoutMenu(hWnd);
	return FALSE;

	case WM_COMMAND: 
	{
		switch (LOWORD(wParam)) 
        { 
		case IDCANCEL:
			if( data->type == MENU_TYPE_MENU && 
			    (data->how==PICK_ONE || data->how==PICK_ANY) &&
			    data->menu.counting) {
				HWND list;
				int i;

				/* reset counter if counting is in progress */
				list = GetMenuControl(hWnd);
				i = ListView_GetNextItem(list, -1,	LVNI_FOCUSED);
				if( i>=0 ) {
					SelectMenuItem(list, data, i,  0);
				}
				return FALSE;
			} else {
				data->result = -1;
				data->done = 1;
			}
		return FALSE;

		case IDOK:
			data->done = 1;
			data->result = 0;
		return FALSE;
		}
	} break;

	case WM_NOTIFY:
	{
		LPNMHDR	lpnmhdr = (LPNMHDR)lParam;
		switch (LOWORD(wParam)) {
		case IDC_MENU_LIST:
		{
			if( !data || data->type!=MENU_TYPE_MENU ) break;

			switch(lpnmhdr->code) {
			case LVN_ITEMACTIVATE: 
			{
				LPNMLISTVIEW lpnmlv = (LPNMLISTVIEW)lParam;
				if(data->how==PICK_ONE) {
					if( lpnmlv->iItem>=0 &&
						lpnmlv->iItem<data->menu.size &&
						NHMENU_IS_SELECTABLE(data->menu.items[lpnmlv->iItem]) ) {
						SelectMenuItem(
							lpnmlv->hdr.hwndFrom, 
							data, 
							lpnmlv->iItem, 
							-1
						);
						data->done = 1;
						data->result = 0;
						return TRUE;
					}
				} else if( data->how==PICK_ANY ) {
					if( lpnmlv->iItem>=0 &&
						lpnmlv->iItem<data->menu.size &&
						NHMENU_IS_SELECTABLE(data->menu.items[lpnmlv->iItem]) ) {
						SelectMenuItem(
							lpnmlv->hdr.hwndFrom, 
							data, 
							lpnmlv->iItem, 
							NHMENU_IS_SELECTED(data->menu.items[lpnmlv->iItem])? 0 : -1
						);
					}
				}
			} break;

			case NM_CLICK: {
				LPNMLISTVIEW lpnmlv = (LPNMLISTVIEW) lParam;
				if( lpnmlv->iItem==-1 ) return 0;
				if( data->how==PICK_ANY ) {
					SelectMenuItem(
						lpnmlv->hdr.hwndFrom, 
						data, 
						lpnmlv->iItem, 
						NHMENU_IS_SELECTED(data->menu.items[lpnmlv->iItem])? 0 : -1
					);
				}
			} break;

			case LVN_ITEMCHANGED: 
			{
				LPNMLISTVIEW lpnmlv = (LPNMLISTVIEW)lParam;
				if( lpnmlv->iItem==-1 ) return 0;
				if( !(lpnmlv->uChanged & LVIF_STATE) ) return 0;

				/* update item that has the focus */
				data->menu.items[lpnmlv->iItem].has_focus = !!(lpnmlv->uNewState & LVIS_FOCUSED);
				ListView_RedrawItems(lpnmlv->hdr.hwndFrom, lpnmlv->iItem, lpnmlv->iItem);

				/* update count for single-selection menu (follow the listview selection) */
				if( data->how==PICK_ONE ) {
					if( lpnmlv->uNewState & LVIS_SELECTED ) {
						SelectMenuItem(
							lpnmlv->hdr.hwndFrom, 
							data, 
							lpnmlv->iItem, 
							-1
						);
					}
				}

				/* check item focus */
				data->menu.items[lpnmlv->iItem].has_focus = !!(lpnmlv->uNewState & LVIS_FOCUSED);
				ListView_RedrawItems(lpnmlv->hdr.hwndFrom, lpnmlv->iItem, lpnmlv->iItem);
			} break;

			case NM_KILLFOCUS:
				reset_menu_count(lpnmhdr->hwndFrom, data);
			break;

			}
		} break;
		}
	} break;

	case WM_SETFOCUS:
		if( hWnd!=GetNHApp()->hPopupWnd ) {
			SetFocus(GetNHApp()->hPopupWnd );
			return 0;
		}
	break;
	
    case WM_MEASUREITEM: 
		if( wParam==IDC_MENU_LIST )
			return onMeasureItem(hWnd, wParam, lParam);
		else
			return FALSE;

    case WM_DRAWITEM:
		if( wParam==IDC_MENU_LIST )
			return onDrawItem(hWnd, wParam, lParam);
		else
			return FALSE;

	case WM_CTLCOLORBTN:
	case WM_CTLCOLOREDIT:
	case WM_CTLCOLORSTATIC: { /* sent by edit control before it is drawn */
		HDC hdcEdit = (HDC) wParam; 
		HWND hwndEdit = (HWND) lParam;
		if( hwndEdit == GetDlgItem(hWnd, IDC_MENU_TEXT) ) {
			SetBkColor(hdcEdit, mswin_get_color(NHW_TEXT, MSWIN_COLOR_BG));
			SetTextColor(hdcEdit, mswin_get_color(NHW_TEXT, MSWIN_COLOR_FG)); 
			return (BOOL)mswin_get_brush(NHW_TEXT, MSWIN_COLOR_BG);
		}
	} return FALSE;

	case WM_DESTROY:
		if( data ) {
			DeleteObject(data->bmpChecked);
			DeleteObject(data->bmpCheckedCount);
			DeleteObject(data->bmpNotChecked);
			if( data->type == MENU_TYPE_TEXT ) {
				if( data->text.text ) {
					mswin_free_text_buffer(data->text.text);
					data->text.text = NULL;
				}
			}
			free(data);
			SetWindowLong(hWnd, GWL_USERDATA, (LONG)0);
		}
		return TRUE;
	}
	return FALSE;
}
示例#15
0
INT_PTR SettingsPublish::ProcMessage(UINT message, WPARAM wParam, LPARAM lParam)
{
    HWND hwndTemp;

    switch(message)
    {
        case WM_INITDIALOG:
            {
                LocalizeWindow(hwnd);

                data = new PublishDialogData;

                RECT serviceRect, saveToFileRect;
                GetWindowRect(GetDlgItem(hwnd, IDC_SERVICE), &serviceRect);
                GetWindowRect(GetDlgItem(hwnd, IDC_SAVEPATH), &saveToFileRect);

                data->fileControlOffset = saveToFileRect.top-serviceRect.top;

                //--------------------------------------------

                hwndTemp = GetDlgItem(hwnd, IDC_MODE);
                SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Publish.Mode.LiveStream"));
                SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Publish.Mode.FileOnly"));

                int mode = LoadSettingComboInt(hwndTemp, TEXT("Publish"), TEXT("Mode"), 0, 2);
                data->mode = mode;

                //--------------------------------------------

                hwndTemp = GetDlgItem(hwnd, IDC_SERVICE);
                int itemId = (int)SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("Custom"));
                SendMessage(hwndTemp, CB_SETITEMDATA, itemId, 0);

                UINT numServices = 0;

                XConfig serverData;
                if(serverData.Open(TEXT("services.xconfig")))
                {
                    XElement *services = serverData.GetElement(TEXT("services"));
                    if(services)
                    {
                        numServices = services->NumElements();

                        for(UINT i=0; i<numServices; i++)
                        {
                            XElement *service = services->GetElementByID(i);
                            itemId = (int)SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)service->GetName());
                            SendMessage(hwndTemp, CB_SETITEMDATA, itemId, service->GetInt(TEXT("id")));
                        }
                    }
                }

                int serviceID = AppConfig->GetInt(TEXT("Publish"), TEXT("Service"), 0);

                if(mode != 0) ShowWindow(hwndTemp, SW_HIDE);

                //--------------------------------------------

                hwndTemp = GetDlgItem(hwnd, IDC_PLAYPATH);
                LoadSettingEditString(hwndTemp, TEXT("Publish"), TEXT("PlayPath"), NULL);
                if(mode != 0) ShowWindow(hwndTemp, SW_HIDE);

                if(serviceID == 0) //custom
                {
                    ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), SW_HIDE);
                    hwndTemp = GetDlgItem(hwnd, IDC_URL);
                    LoadSettingEditString(hwndTemp, TEXT("Publish"), TEXT("URL"), NULL);
                    SendDlgItemMessage(hwnd, IDC_SERVICE, CB_SETCURSEL, 0, 0);
                }
                else
                {
                    ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_HIDE);
                    hwndTemp = GetDlgItem(hwnd, IDC_SERVERLIST);

                    XElement *services = serverData.GetElement(TEXT("services"));
                    if(services)
                    {
                        XElement *service = NULL;
                        numServices = services->NumElements();
                        for(UINT i=0; i<numServices; i++)
                        {
                            XElement *curService = services->GetElementByID(i);
                            if(curService->GetInt(TEXT("id")) == serviceID)
                            {
                                SendDlgItemMessage(hwnd, IDC_SERVICE, CB_SETCURSEL, i+1, 0);
                                service = curService;
                                break;
                            }
                        }

                        if(service)
                        {
                            XElement *servers = service->GetElement(TEXT("servers"));
                            if(servers)
                            {
                                UINT numServers = servers->NumDataItems();
                                for(UINT i=0; i<numServers; i++)
                                {
                                    XDataItem *server = servers->GetDataItemByID(i);
                                    SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)server->GetName());
                                }
                            }
                        }
                    }

                    LoadSettingComboString(hwndTemp, TEXT("Publish"), TEXT("URL"), NULL);
                }

                if(mode != 0) ShowWindow(hwndTemp, SW_HIDE);

                //--------------------------------------------

                hwndTemp = GetDlgItem(hwnd, IDC_LOWLATENCYMODE);

                BOOL bLowLatencyMode = AppConfig->GetInt(TEXT("Publish"), TEXT("LowLatencyMode"), 0);
                SendMessage(hwndTemp, BM_SETCHECK, bLowLatencyMode ? BST_CHECKED : BST_UNCHECKED, 0);

                //--------------------------------------------

                hwndTemp = GetDlgItem(hwnd, IDC_AUTORECONNECT);

                BOOL bAutoReconnect = AppConfig->GetInt(TEXT("Publish"), TEXT("AutoReconnect"), 1);
                SendMessage(hwndTemp, BM_SETCHECK, bAutoReconnect ? BST_CHECKED : BST_UNCHECKED, 0);

                if(mode != 0) ShowWindow(hwndTemp, SW_HIDE);

                hwndTemp = GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT);
                EnableWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT), bAutoReconnect);
                EnableWindow(hwndTemp, bAutoReconnect);

                int retryTime = AppConfig->GetInt(TEXT("Publish"), TEXT("AutoReconnectTimeout"), 10);
                if(retryTime > 60)      retryTime = 60;
                else if(retryTime < 5)  retryTime = 5;

                SendMessage(hwndTemp, UDM_SETRANGE32, 5, 60);
                SendMessage(hwndTemp, UDM_SETPOS32, 0, retryTime);

                if(mode != 0) ShowWindow(hwndTemp, SW_HIDE);

                //--------------------------------------------

                hwndTemp = GetDlgItem(hwnd, IDC_DELAY);

                int delayTime = AppConfig->GetInt(TEXT("Publish"), TEXT("Delay"), 0);

                SendMessage(hwndTemp, UDM_SETRANGE32, 0, 900);
                SendMessage(hwndTemp, UDM_SETPOS32, 0, delayTime);

                //--------------------------------------------

                if(mode != 0)
                {
                    ShowWindow(GetDlgItem(hwnd, IDC_SERVICE_STATIC), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_PLAYPATH_STATIC), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_URL_STATIC), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_SERVER_STATIC), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_LOWLATENCYMODE), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_STATIC), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_DELAY_STATIC), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_DELAY_EDIT), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_DELAY), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), SW_HIDE);
                    //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK), SW_HIDE);
                    //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK_STATIC), SW_HIDE);
                    ShowWindow(GetDlgItem(hwnd, IDC_SAVETOFILE), SW_HIDE);

                    AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH_STATIC), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_BROWSE), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY_STATIC), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY_STATIC), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTSTREAM), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY_STATIC), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY_STATIC), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTRECORDING), 0, -data->fileControlOffset);
                    AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STOPRECORDING), 0, -data->fileControlOffset);
                }

                //--------------------------------------------

                DWORD startHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StartStreamHotkey"));
                SendMessage(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), HKM_SETHOTKEY, startHotkey, 0);

                //--------------------------------------------

                DWORD stopHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StopStreamHotkey"));
                SendMessage(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), HKM_SETHOTKEY, stopHotkey, 0);

                //--------------------------------------------

                startHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StartRecordingHotkey"));
                SendMessage(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), HKM_SETHOTKEY, startHotkey, 0);

                //--------------------------------------------

                stopHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StopRecordingHotkey"));
                SendMessage(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), HKM_SETHOTKEY, stopHotkey, 0);

                //--------------------------------------------

                BOOL bKeepRecording = AppConfig->GetInt(TEXT("Publish"), TEXT("KeepRecording"));
                SendMessage(GetDlgItem(hwnd, IDC_KEEPRECORDING), BM_SETCHECK, bKeepRecording ? BST_CHECKED : BST_UNCHECKED, 0);

                BOOL bSaveToFile = AppConfig->GetInt(TEXT("Publish"), TEXT("SaveToFile"));
                SendMessage(GetDlgItem(hwnd, IDC_SAVETOFILE), BM_SETCHECK, bSaveToFile ? BST_CHECKED : BST_UNCHECKED, 0);

                CTSTR lpSavePath = AppConfig->GetStringPtr(TEXT("Publish"), TEXT("SavePath"));
                SetWindowText(GetDlgItem(hwnd, IDC_SAVEPATH), lpSavePath);

                EnableWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), bSaveToFile || (mode != 0));

                EnableWindow(GetDlgItem(hwnd, IDC_SAVEPATH), bSaveToFile || (mode != 0));
                EnableWindow(GetDlgItem(hwnd, IDC_BROWSE),   bSaveToFile || (mode != 0));

                //--------------------------------------------

                //SetWindowText(GetDlgItem(hwnd, IDC_DASHBOARDLINK), App->strDashboard);

                //--------------------------------------------

                SetWarningInfo();

                ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_HIDE);
                SetChangedSettings(false);

                return TRUE;
            }

        case WM_CTLCOLORSTATIC:
            {
                switch (GetDlgCtrlID((HWND)lParam))
                {
                    case IDC_WARNINGS:
                        SetTextColor((HDC)wParam, RGB(255, 0, 0));
                        SetBkColor((HDC)wParam, COLORREF(GetSysColor(COLOR_3DFACE)));
                        return (INT_PTR)GetSysColorBrush(COLOR_BTNFACE);
                }
            }
            break;

        case WM_DESTROY:
            {
                delete data;
                data = NULL;
            }
            break;

        case WM_NOTIFY:
            {
                NMHDR *nmHdr = (NMHDR*)lParam;

                if(nmHdr->idFrom == IDC_AUTORECONNECT_TIMEOUT)
                {
                    if(nmHdr->code == UDN_DELTAPOS)
                        SetChangedSettings(true);
                }

                break;
            }

        case WM_COMMAND:
            {
                bool bDataChanged = false;

                switch(LOWORD(wParam))
                {
                    case IDC_MODE:
                        {
                            if(HIWORD(wParam) != CBN_SELCHANGE)
                                break;

                            int mode = (int)SendMessage((HWND)lParam, CB_GETCURSEL, 0, 0);
                            int swShowControls = (mode == 0) ? SW_SHOW : SW_HIDE;

                            ShowWindow(GetDlgItem(hwnd, IDC_SERVICE), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_PLAYPATH), swShowControls);

                            int serviceID = (int)SendMessage(GetDlgItem(hwnd, IDC_SERVICE), CB_GETCURSEL, 0, 0);
                            if(serviceID == 0)
                            {
                                ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), SW_HIDE);
                                ShowWindow(GetDlgItem(hwnd, IDC_URL), swShowControls);
                            }
                            else
                            {
                                ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), swShowControls);
                                ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_HIDE);
                            }

                            BOOL bSaveToFile = SendMessage(GetDlgItem(hwnd, IDC_SAVETOFILE), BM_GETCHECK, 0, 0) != BST_UNCHECKED;
                            EnableWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), bSaveToFile || (mode != 0));
                            EnableWindow(GetDlgItem(hwnd, IDC_SAVEPATH), bSaveToFile || (mode != 0));
                            EnableWindow(GetDlgItem(hwnd, IDC_BROWSE),   bSaveToFile || (mode != 0));

                            if(mode == 0 && data->mode == 1)
                            {
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH_STATIC), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_BROWSE), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY_STATIC), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY_STATIC), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTSTREAM), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY_STATIC), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY_STATIC), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTRECORDING), 0, data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STOPRECORDING), 0, data->fileControlOffset);

                            }
                            else if(mode == 1 && data->mode == 0)
                            {
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH_STATIC), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_BROWSE), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY_STATIC), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY_STATIC), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTSTREAM), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY_STATIC), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY_STATIC), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTRECORDING), 0, -data->fileControlOffset);
                                AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STOPRECORDING), 0, -data->fileControlOffset);
                            }

                            data->mode = mode;

                            ShowWindow(GetDlgItem(hwnd, IDC_SERVICE_STATIC), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_PLAYPATH_STATIC), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_URL_STATIC), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_SERVER_STATIC), swShowControls);
                            //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK), swShowControls);
                            //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK_STATIC), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_LOWLATENCYMODE), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_STATIC), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_DELAY_STATIC), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_DELAY_EDIT), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_DELAY), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_SAVETOFILE), swShowControls);
                            ShowWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), swShowControls);

                            SetWarningInfo();

                            bDataChanged = true;
                            break;
                        }

                    case IDC_SERVICE:
                        if(HIWORD(wParam) == CBN_SELCHANGE)
                        {
                            int serviceID = (int)SendMessage((HWND)lParam, CB_GETCURSEL, 0, 0);

                            if(serviceID == 0)
                            {
                                ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), SW_HIDE);
                                ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_SHOW);

                                SetWindowText(GetDlgItem(hwnd, IDC_URL), NULL);
                                //SetWindowText(GetDlgItem(hwnd, IDC_DASHBOARDLINK), NULL);
                            }
                            else
                            {
                                ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_HIDE);

                                hwndTemp = GetDlgItem(hwnd, IDC_SERVERLIST);
                                ShowWindow(hwndTemp, SW_SHOW);
                                SendMessage(hwndTemp, CB_RESETCONTENT, 0, 0);

                                XConfig serverData;
                                if(serverData.Open(TEXT("services.xconfig")))
                                {
                                    XElement *services = serverData.GetElement(TEXT("services"));
                                    if(services)
                                    {
                                        XElement *service = services->GetElementByID(serviceID-1);
                                        if(service)
                                        {
                                            XElement *servers = service->GetElement(TEXT("servers"));
                                            if(servers)
                                            {
                                                UINT numServers = servers->NumDataItems();
                                                for(UINT i=0; i<numServers; i++)
                                                {
                                                    XDataItem *server = servers->GetDataItemByID(i);
                                                    SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)server->GetName());
                                                }
                                            }
                                        }
                                    }
                                }

                                SendMessage(hwndTemp, CB_SETCURSEL, 0, 0);
                            }

                            SetWindowText(GetDlgItem(hwnd, IDC_PLAYPATH), NULL);

                            bDataChanged = true;
                        }

                        SetWarningInfo();

                        break;

                    case IDC_AUTORECONNECT:
                        if(HIWORD(wParam) == BN_CLICKED)
                        {
                            BOOL bAutoReconnect = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED;

                            EnableWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT),       bAutoReconnect);
                            EnableWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT),  bAutoReconnect);

                            SetChangedSettings(true);
                        }
                        break;

                    case IDC_AUTORECONNECT_TIMEOUT_EDIT:
                        if(HIWORD(wParam) == EN_CHANGE)
                            SetChangedSettings(true);
                        break;

                    case IDC_DELAY_EDIT:
                        if(HIWORD(wParam) == EN_CHANGE)
                            bDataChanged = true;
                        break;

                    case IDC_SAVETOFILE:
                        if(HIWORD(wParam) == BN_CLICKED)
                        {
                            BOOL bSaveToFile = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED;

                            EnableWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), bSaveToFile);

                            EnableWindow(GetDlgItem(hwnd, IDC_SAVEPATH), bSaveToFile);
                            EnableWindow(GetDlgItem(hwnd, IDC_BROWSE),   bSaveToFile);

                            bDataChanged = true;
                        }
                        break;

                    case IDC_KEEPRECORDING:
                        if(HIWORD(wParam) == BN_CLICKED)
                        {
                            BOOL bKeepRecording = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED;
                            App->bKeepRecording = bKeepRecording != 0;

                            bDataChanged = true;
                        }
                        break;

                    case IDC_BROWSE:
                        {
                            TCHAR lpFile[512];
                            OPENFILENAME ofn;
                            zero(&ofn, sizeof(ofn));
                            ofn.lStructSize = sizeof(ofn);
                            ofn.hwndOwner = hwnd;
                            ofn.lpstrFile = lpFile;
                            ofn.nMaxFile = 511;
                            ofn.lpstrFile[0] = 0;
                            ofn.lpstrFilter = TEXT("MP4 File (*.mp4)\0*.mp4\0Flash Video File (*.flv)\0*.flv\0");
                            ofn.lpstrFileTitle = NULL;
                            ofn.nMaxFileTitle = 0;
                            ofn.nFilterIndex = 1;
                            ofn.lpstrInitialDir = AppConfig->GetStringPtr(TEXT("Publish"), TEXT("LastSaveDir"));

                            ofn.Flags = OFN_PATHMUSTEXIST;

                            TCHAR curDirectory[512];
                            GetCurrentDirectory(511, curDirectory);

                            BOOL bChoseFile = GetSaveFileName(&ofn);
                            SetCurrentDirectory(curDirectory);

                            if(*lpFile && bChoseFile)
                            {
                                String strFile = lpFile;
                                strFile.FindReplace(TEXT("\\"), TEXT("/"));

                                String strExtension = GetPathExtension(strFile);
                                if(strExtension.IsEmpty() || (!strExtension.CompareI(TEXT("flv")) && /*!strExtension.CompareI(TEXT("avi")) &&*/ !strExtension.CompareI(TEXT("mp4"))))
                                {
                                    switch(ofn.nFilterIndex)
                                    {
                                        case 1:
                                            strFile << TEXT(".mp4"); break;
                                        case 2:
                                            strFile << TEXT(".flv"); break;
                                        /*case 3:
                                            strFile << TEXT(".avi"); break;*/
                                    }
                                }

                                String strFilePath = GetPathDirectory(strFile).FindReplace(TEXT("/"), TEXT("\\")) << TEXT("\\");
                                AppConfig->SetString(TEXT("Publish"), TEXT("LastSaveDir"), strFilePath);

                                strFile.FindReplace(TEXT("/"), TEXT("\\"));
                                SetWindowText(GetDlgItem(hwnd, IDC_SAVEPATH), strFile);
                                bDataChanged = true;
                            }

                            break;
                        }

                    case IDC_LOWLATENCYMODE:
                        if(HIWORD(wParam) == BN_CLICKED)
                            bDataChanged = true;
                        break;

                    case IDC_STARTSTREAMHOTKEY:
                    case IDC_STOPSTREAMHOTKEY:
                    //case IDC_DASHBOARDLINK:
                    case IDC_STARTRECORDINGHOTKEY:
                    case IDC_STOPRECORDINGHOTKEY:
                        if(HIWORD(wParam) == EN_CHANGE)
                            SetChangedSettings(true);
                        break;

                    case IDC_PLAYPATH:
                    case IDC_URL:
                    case IDC_SAVEPATH:
                        if(HIWORD(wParam) == EN_CHANGE)
                            bDataChanged = true;
                        break;

                    case IDC_CLEARHOTKEY_STARTSTREAM:
                        if(HIWORD(wParam) == BN_CLICKED)
                        {
                            if(SendMessage(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), HKM_GETHOTKEY, 0, 0))
                            {
                                SendMessage(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), HKM_SETHOTKEY, 0, 0);
                                SetChangedSettings(true);
                            }
                        }
                        break;

                    case IDC_CLEARHOTKEY:
                        if(HIWORD(wParam) == BN_CLICKED)
                        {
                            if(SendMessage(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), HKM_GETHOTKEY, 0, 0))
                            {
                                SendMessage(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), HKM_SETHOTKEY, 0, 0);
                                SetChangedSettings(true);
                            }
                        }
                        break;

                    case IDC_CLEARHOTKEY_STARTRECORDING:
                        if (HIWORD(wParam) == BN_CLICKED)
                        {
                            if (SendMessage(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), HKM_GETHOTKEY, 0, 0))
                            {
                                SendMessage(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), HKM_SETHOTKEY, 0, 0);
                                SetChangedSettings(true);
                            }
                        }
                        break;

                    case IDC_CLEARHOTKEY_STOPRECORDING:
                        if (HIWORD(wParam) == BN_CLICKED)
                        {
                            if (SendMessage(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), HKM_GETHOTKEY, 0, 0))
                            {
                                SendMessage(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), HKM_SETHOTKEY, 0, 0);
                                SetChangedSettings(true);
                            }
                        }
                        break;

                    case IDC_SERVERLIST:
                        if(HIWORD(wParam) == CBN_EDITCHANGE || HIWORD(wParam) == CBN_SELCHANGE)
                            bDataChanged = true;
                        break;
                }

                if(bDataChanged)
                {
                    ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW);
                    SetChangedSettings(true);
                }
                break;
            }
    }
    return FALSE;
}
示例#16
0
//-----------------------------------------------------------------------------
// The font class constructor
//-----------------------------------------------------------------------------
Font::Font( char *name, short size, unsigned long bold, bool italic )
{
	HBITMAP bitmap = NULL;
	HGDIOBJ oldBitmap = NULL;
	HFONT oldFont = NULL;
	BYTE *dstRow = NULL;
	unsigned long x, y;

	HDC hDC = CreateCompatibleDC( NULL );
	SetMapMode( hDC, MM_TEXT );

	// Create the font.
	char height = -MulDiv( size, GetDeviceCaps( hDC, LOGPIXELSY ), 72 );
	HFONT font = CreateFont( height, 0, 0, 0, bold, italic, false, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, name );
	if( font == NULL )
		goto End;

	oldFont = (HFONT)SelectObject( hDC, font );

	// Find the dimensions of the smallest texture to hold the characters.
	m_textureWidth = m_textureHeight = 128;
	while( !PrepareFont( hDC, true ) )
	{
		m_textureWidth *= 2;
		m_textureHeight *= 2;
	}

	// Create a new texture for the font
	if( FAILED( g_engine->GetDevice()->CreateTexture( m_textureWidth, m_textureHeight, 1, 0, D3DFMT_A4R4G4B4, D3DPOOL_MANAGED, &m_texture, NULL ) ) )
		goto End;

	// Prepare the bitmap.
	unsigned long *bitmapBits;
	BITMAPINFO bmi;
	ZeroMemory( &bmi.bmiHeader, sizeof( BITMAPINFOHEADER ) );
	bmi.bmiHeader.biSize = sizeof( BITMAPINFOHEADER );
	bmi.bmiHeader.biWidth = (int)m_textureWidth;
	bmi.bmiHeader.biHeight = -(int)m_textureHeight;
	bmi.bmiHeader.biPlanes = 1;
	bmi.bmiHeader.biCompression = BI_RGB;
	bmi.bmiHeader.biBitCount = 32;

	// Create a bitmap for the font.
	bitmap = CreateDIBSection( hDC, &bmi, DIB_RGB_COLORS, (void**)&bitmapBits, NULL, 0 );

	oldBitmap = SelectObject( hDC, bitmap );

	// Set the text properties.
	SetTextColor( hDC, RGB( 255,255,255 ) );
	SetBkColor( hDC, 0x00000000 );
	SetTextAlign( hDC, TA_TOP );

	// Prepare the font by drawing the characters onto the bitmap.
	if( !PrepareFont( hDC ) )
		goto End;

	// Lock the surface and write the alpha values for the set pixels.
	D3DLOCKED_RECT d3dlr;
	m_texture->LockRect( 0, &d3dlr, 0, 0 );
	dstRow = (BYTE*)d3dlr.pBits;
	WORD *dst16;
	BYTE alpha;

	for( y = 0; y < m_textureHeight; y++ )
	{
		dst16 = (WORD*)dstRow;
		for( x = 0; x < m_textureWidth; x++ )
		{
			alpha = (BYTE)( ( bitmapBits[m_textureWidth*y + x] & 0xff ) >> 4 );
			if( alpha > 0 )
				*dst16++ = (WORD)( ( alpha << 12 ) | 0x0fff );
			else
				*dst16++ = 0x0000;
		}
		dstRow += d3dlr.Pitch;
	}

	// Create the vertex buffer for the characters.
	g_engine->GetDevice()->CreateVertexBuffer( 1020 * sizeof( TLVertex ), D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, 0, D3DPOOL_DEFAULT, &m_vb, NULL );

	// Prepare the alpha testing for rendering the characters.
	g_engine->GetDevice()->SetRenderState( D3DRS_ALPHAREF, 0x08 );
	g_engine->GetDevice()->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );

	// Create a state block for capturing the volatile render states.
	g_engine->GetDevice()->BeginStateBlock();
	g_engine->GetDevice()->SetRenderState( D3DRS_LIGHTING, false );
	g_engine->GetDevice()->SetRenderState( D3DRS_ALPHATESTENABLE, false );
	g_engine->GetDevice()->SetRenderState( D3DRS_FOGENABLE, false );
	g_engine->GetDevice()->EndStateBlock( &m_states );

	// Clean up and return.
End:
	if( m_texture )
		m_texture->UnlockRect( 0 );

	SelectObject( hDC, oldBitmap );
	SelectObject( hDC, oldFont );
	DeleteObject( bitmap );
	DeleteObject( font );
	DeleteDC( hDC );
}
示例#17
0
/*
** This is cribbed from FX/fxwgl.c, and seems to implement support
** for bitmap fonts where the wglUseFontBitmapsA() code implements
** support for outline fonts.  In combination they hopefully give
** fairly generic support for fonts.
*/
static BOOL wglUseFontBitmaps_FX(HDC fontDevice, DWORD firstChar,
                                 DWORD numChars, DWORD listBase)
{
#define VERIFY(a) a
    
    TEXTMETRIC metric;
    BITMAPINFO *dibInfo;
    HDC bitDevice;
    COLORREF tempColor;
    int i;
    
    VERIFY(GetTextMetrics(fontDevice, &metric));
    
    dibInfo = (BITMAPINFO *) calloc(sizeof(BITMAPINFO) + sizeof(RGBQUAD), 1);
    dibInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    dibInfo->bmiHeader.biPlanes = 1;
    dibInfo->bmiHeader.biBitCount = 1;
    dibInfo->bmiHeader.biCompression = BI_RGB;
    
    bitDevice = CreateCompatibleDC(fontDevice);
    
    // Swap fore and back colors so the bitmap has the right polarity
    tempColor = GetBkColor(bitDevice);
    SetBkColor(bitDevice, GetTextColor(bitDevice));
    SetTextColor(bitDevice, tempColor);
    
    // Place chars based on base line
    VERIFY(SetTextAlign(bitDevice, TA_BASELINE) != GDI_ERROR ? 1 : 0);
    
    for(i = 0; i < (int)numChars; i++) {
	SIZE size;
	char curChar;
	int charWidth,charHeight,bmapWidth,bmapHeight,numBytes,res;
	HBITMAP bitObject;
	HGDIOBJ origBmap;
	unsigned char *bmap;
	
	curChar = (char)(i + firstChar);
	
	// Find how high/wide this character is
	VERIFY(GetTextExtentPoint32(bitDevice, &curChar, 1, &size));
	
	// Create the output bitmap
	charWidth = size.cx;
	charHeight = size.cy;
	// Round up to the next multiple of 32 bits
	bmapWidth = ((charWidth + 31) / 32) * 32;   
	bmapHeight = charHeight;
	bitObject = CreateCompatibleBitmap(bitDevice,
					   bmapWidth,
					   bmapHeight);
	//VERIFY(bitObject);
	
	// Assign the output bitmap to the device
	origBmap = SelectObject(bitDevice, bitObject);
	(void) VERIFY(origBmap);
	
	VERIFY( PatBlt( bitDevice, 0, 0, bmapWidth, bmapHeight,BLACKNESS ) );
	
	// Use our source font on the device
	VERIFY(SelectObject(bitDevice, GetCurrentObject(fontDevice,OBJ_FONT)));
	
	// Draw the character
	VERIFY(TextOut(bitDevice, 0, metric.tmAscent, &curChar, 1));
	
	// Unselect our bmap object
	VERIFY(SelectObject(bitDevice, origBmap));
	
	// Convert the display dependant representation to a 1 bit deep DIB
	numBytes = (bmapWidth * bmapHeight) / 8;
	bmap = malloc(numBytes);
	dibInfo->bmiHeader.biWidth = bmapWidth;
	dibInfo->bmiHeader.biHeight = bmapHeight;
	res = GetDIBits(bitDevice, bitObject, 0, bmapHeight, bmap,
			dibInfo,
			DIB_RGB_COLORS);
	//VERIFY(res);
	
	// Create the GL object
	glNewList(i + listBase, GL_COMPILE);
	glBitmap(bmapWidth, bmapHeight, 0.0, (GLfloat)metric.tmDescent,
		 (GLfloat)charWidth, 0.0,
		 bmap);
	glEndList();
	// CheckGL();
	
	// Destroy the bmap object
	DeleteObject(bitObject);
	
	// Deallocate the bitmap data
	free(bmap);
    }
    
    // Destroy the DC
    VERIFY(DeleteDC(bitDevice));
    
    free(dibInfo);
    
    return TRUE;
#undef VERIFY
}
示例#18
0
LRESULT CALLBACK EventAreaWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
	case WM_CREATE:
		hwndEventFrame = hwnd;
		return FALSE;

	case WM_MEASUREITEM:
		{
			MEASUREITEMSTRUCT *lpi = (LPMEASUREITEMSTRUCT)lParam;
			MENUITEMINFOA mii = { 0 };

			mii.cbSize = sizeof(mii);
			mii.fMask = MIIM_DATA | MIIM_ID;
			if (GetMenuItemInfoA(cfg::dat.hMenuNotify, lpi->itemID, FALSE, &mii) != 0) {
				if (mii.dwItemData == lpi->itemData) {
					lpi->itemWidth = 8 + 16;
					lpi->itemHeight = 0;
					return TRUE;
				}
			}
			break;
		}
	case WM_NCCALCSIZE:
		return FrameNCCalcSize(hwnd, DefWindowProc, wParam, lParam,
			wndFrameEventArea ? wndFrameEventArea->TitleBar.ShowTitleBar : 0);
	case WM_NCPAINT:
		return FrameNCPaint(hwnd, DefWindowProc, wParam, lParam,
			wndFrameEventArea ? wndFrameEventArea->TitleBar.ShowTitleBar : 0);
	case WM_DRAWITEM:
		{
			LPDRAWITEMSTRUCT dis = (LPDRAWITEMSTRUCT)lParam;

			if (dis->hwndItem == (HWND)cfg::dat.hMenuNotify) {
				MENUITEMINFOA mii = { 0 };

				struct NotifyMenuItemExData *nmi = 0;
				int iIcon;
				HICON hIcon;

				mii.cbSize = sizeof(mii);
				mii.fMask = MIIM_DATA;
				if (GetMenuItemInfoA(cfg::dat.hMenuNotify, (UINT)dis->itemID, FALSE, &mii) != 0) {
					nmi = (struct NotifyMenuItemExData *) mii.dwItemData;
					if (nmi) {
						iIcon = pcli->pfnGetContactIcon(nmi->hContact);
						hIcon = ImageList_GetIcon(hCListImages, iIcon, ILD_NORMAL);
						pcli->pfnDrawMenuItem(dis, hIcon, nmi->hIcon);
						return TRUE;
					}
				}
			}
			break;
		}
	case WM_LBUTTONUP:
		if (cfg::dat.bEventAreaEnabled)
			SendMessage(hwnd, WM_COMMAND, MAKEWPARAM(IDC_NOTIFYBUTTON, 0), 0);
		break;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDC_NOTIFYBUTTON) {
			int iSelection;
			struct NotifyMenuItemExData *nmi = 0;
			int iCount = GetMenuItemCount(cfg::dat.hMenuNotify);

			POINT pt;
			GetCursorPos(&pt);

			MENUITEMINFO mii = { 0 };
			mii.cbSize = sizeof(mii);
			mii.fMask = MIIM_DATA;
			if (iCount > 1)
				iSelection = TrackPopupMenu(cfg::dat.hMenuNotify, TPM_RETURNCMD, pt.x, pt.y, 0, hwnd, NULL);
			else
				iSelection = GetMenuItemID(cfg::dat.hMenuNotify, 0);
			
			BOOL result = GetMenuItemInfo(cfg::dat.hMenuNotify, (UINT)iSelection, FALSE, &mii);
			if (result != 0) {
				nmi = (struct NotifyMenuItemExData *) mii.dwItemData;
				if (nmi) {
					CLISTEVENT *cle = MyGetEvent(iSelection);
					if (cle) {
						CLISTEVENT *cle1 = NULL;
						CallService(cle->pszService, (WPARAM)NULL, (LPARAM)cle);
						// re-obtain the pointer, it may already be invalid/point to another event if the
						// event we're interested in was removed by the service (nasty one...)
						cle1 = MyGetEvent(iSelection);
						if (cle1 != NULL)
							pcli->pfnRemoveEvent(cle->hContact, cle->hDbEvent);
					}
				}
			}
		}
		break;

	case WM_ERASEBKGND:
		return TRUE;

	case WM_PAINT:
		{
			PAINTSTRUCT ps;
			HDC hdc = BeginPaint(hwnd, &ps);

			RECT rc, rcClient;
			GetClientRect(hwnd, &rc);
			rcClient = rc;

			HDC hdcMem = CreateCompatibleDC(hdc);
			HBITMAP hbm = CreateCompatibleBitmap(hdc, rc.right, rc.bottom);
			HBITMAP hbmold = reinterpret_cast<HBITMAP>(SelectObject(hdcMem, hbm));
			SetBkMode(hdcMem, TRANSPARENT);

			HFONT hFontOld = 0;
			if (cfg::clcdat) {
				int height;
				hFontOld = ChangeToFont(hdcMem, cfg::clcdat, FONTID_EVENTAREA, &height);
			}

			if (cfg::dat.bWallpaperMode)
				SkinDrawBg(hwnd, hdcMem);

			StatusItems_t *item = arStatusItems[ID_EXTBKEVTAREA - ID_STATUS_OFFLINE];
			if (item->IGNORED)
				FillRect(hdcMem, &rc, GetSysColorBrush(COLOR_3DFACE));
			else {
				rc.top += item->MARGIN_TOP; rc.bottom -= item->MARGIN_BOTTOM;
				rc.left += item->MARGIN_LEFT; rc.right -= item->MARGIN_RIGHT;

				DrawAlpha(hdcMem, &rc, item->COLOR, item->ALPHA, item->COLOR2, item->COLOR2_TRANSPARENT,
					item->GRADIENT, item->CORNER, item->BORDERSTYLE, item->imageItem);
				SetTextColor(hdcMem, item->TEXTCOLOR);
			}

			LONG dwLeft = rc.left;

			PaintNotifyArea(hdcMem, &rc);
			if (cfg::dat.dwFlags & CLUI_FRAME_EVENTAREASUNKEN) {
				rc.left = dwLeft;
				InflateRect(&rc, -2, -2);
				DrawEdge(hdcMem, &rc, BDR_SUNKENOUTER, BF_RECT);
			}
			BitBlt(hdc, 0, 0, rcClient.right, rcClient.bottom, hdcMem, 0, 0, SRCCOPY);
			SelectObject(hdcMem, hbmold);
			if (hFontOld)
				SelectObject(hdcMem, hFontOld);
			DeleteObject(hbm);
			DeleteDC(hdcMem);
			ps.fErase = FALSE;
			EndPaint(hwnd, &ps);
		}
		return 0;

	default:
		return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	return TRUE;
}
示例#19
0
BOOL MyListCtrl::init()
{
	//Create Image list. 

	m_ImageListThumb.DeleteImageList();
	m_IconWidth=2;
	m_IconHeight=27;
	m_ImageListThumb.Create(m_IconWidth, m_IconHeight, ILC_COLOR24, 0, 1);
	SetImageList(&m_ImageListThumb, LVSIL_SMALL);
	m_ShowIcons=FALSE;
	Arrange(LVSCW_AUTOSIZE);
	//LVSCW_AUTOSIZE
	FreeListItems();

	// For the resize problem...... 
	m_iNumberOfColumns=2;
	m_iColumnWidthArray[0]=60;
	m_iColumnWidthArray[1]=80;
	m_iColumnWidthArray[2]=110;
	m_iColumnWidthArray[3]=100;



	InsertColumn(0,"Client Address",LVCFMT_LEFT,m_iColumnWidthArray[0]);
	InsertColumn(1,"Status",LVCFMT_LEFT,m_iColumnWidthArray[1]);
	//InsertColumn(1,"Storlek",LVCFMT_LEFT,110);
	//InsertColumn(2,"Unik ID",LVCFMT_LEFT,110);
	// We whant a nice flat list-  	
	SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FLATSB |
		LVS_EX_FULLROWSELECT );


	//
	// Setting the header INFO
	//

	// Loading header images.. 
	m_HeaderImages.DeleteImageList();
	m_HeaderImages.Create(IDB_HEADER, 9*2, 1, RGB(255,255,255));

	CHeaderCtrl* pHeader=GetHeaderCtrl();
	if(pHeader)
	{

		pHeader->SetImageList(&m_HeaderImages);

		for (int i=0; i < pHeader->GetItemCount(); i++)
		{
			SetHeaderIcon(i,-1);
		}

		SetBkColor(RGB(255,255,255));
		SetTextBkColor(RGB(255,255,255));
		SetTextColor(RGB(0,0,0));
		SetHeaderIcon(0,0);
		m_iCurrentSortColumn=0;
	}

	ResizeColumns();

	return TRUE;
}
示例#20
0
extern "C" BOOL EditPrint(HWND hwnd,LPCWSTR pszDocTitle,LPCWSTR pszPageFormat)
{

  // Don't print empty documents
  if (SendMessage(hwnd,SCI_GETLENGTH,0,0) == 0) {
    MsgBox(MBWARN,IDS_PRINT_EMPTY);
    return TRUE;
  }

  int startPos;
  int endPos;

  HDC hdc;

  RECT rectMargins;
  RECT rectPhysMargins;
  RECT rectSetup;
  POINT ptPage;
  POINT ptDpi;

  //RECT rectSetup;

  TEXTMETRIC tm;

  int headerLineHeight;
  HFONT fontHeader;

  int footerLineHeight;
  HFONT fontFooter;

  WCHAR dateString[256];

  DOCINFO di = {sizeof(DOCINFO), 0, 0, 0, 0};

  LONG lengthDoc;
  LONG lengthDocMax;
  LONG lengthPrinted;

  struct RangeToFormat frPrint;

  int pageNum;
  BOOL printPage;

  WCHAR pageString[32];

  HPEN pen;
  HPEN penOld;

  PRINTDLG pdlg = { sizeof(PRINTDLG), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  pdlg.hwndOwner = GetParent(hwnd);
  pdlg.hInstance = g_hInstance;
  pdlg.Flags = PD_USEDEVMODECOPIES | PD_ALLPAGES | PD_RETURNDC;
  pdlg.nFromPage = 1;
  pdlg.nToPage = 1;
  pdlg.nMinPage = 1;
  pdlg.nMaxPage = 0xffffU;
  pdlg.nCopies = 1;
  pdlg.hDC = 0;
  pdlg.hDevMode = hDevMode;
  pdlg.hDevNames = hDevNames;

  startPos = SendMessage(hwnd,SCI_GETSELECTIONSTART,0,0);;
  endPos = SendMessage(hwnd,SCI_GETSELECTIONEND,0,0);

  if (startPos == endPos) {
    pdlg.Flags |= PD_NOSELECTION;
  } else {
    pdlg.Flags |= PD_SELECTION;
  }
  if (0) {
    // Don't display dialog box, just use the default printer and options
    pdlg.Flags |= PD_RETURNDEFAULT;
  }
  if (!PrintDlg(&pdlg)) {
    return TRUE; // False means error...
  }

  hDevMode = pdlg.hDevMode;
  hDevNames = pdlg.hDevNames;

  hdc = pdlg.hDC;

  // Get printer resolution
  ptDpi.x = GetDeviceCaps(hdc, LOGPIXELSX);    // dpi in X direction
  ptDpi.y = GetDeviceCaps(hdc, LOGPIXELSY);    // dpi in Y direction

  // Start by getting the physical page size (in device units).
  ptPage.x = GetDeviceCaps(hdc, PHYSICALWIDTH);   // device units
  ptPage.y = GetDeviceCaps(hdc, PHYSICALHEIGHT);  // device units

  // Get the dimensions of the unprintable
  // part of the page (in device units).
  rectPhysMargins.left = GetDeviceCaps(hdc, PHYSICALOFFSETX);
  rectPhysMargins.top = GetDeviceCaps(hdc, PHYSICALOFFSETY);

  // To get the right and lower unprintable area,
  // we take the entire width and height of the paper and
  // subtract everything else.
  rectPhysMargins.right = ptPage.x            // total paper width
                          - GetDeviceCaps(hdc, HORZRES) // printable width
                          - rectPhysMargins.left;        // left unprintable margin

  rectPhysMargins.bottom = ptPage.y            // total paper height
                           - GetDeviceCaps(hdc, VERTRES)  // printable height
                           - rectPhysMargins.top;        // right unprintable margin

  // At this point, rectPhysMargins contains the widths of the
  // unprintable regions on all four sides of the page in device units.

  // Take in account the page setup given by the user (if one value is not null)
  if (pagesetupMargin.left != 0 || pagesetupMargin.right != 0 ||
          pagesetupMargin.top != 0 || pagesetupMargin.bottom != 0) {

    // Convert the hundredths of millimeters (HiMetric) or
    // thousandths of inches (HiEnglish) margin values
    // from the Page Setup dialog to device units.
    // (There are 2540 hundredths of a mm in an inch.)

    WCHAR localeInfo[3];
    GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3);

    if (localeInfo[0] == L'0') {  // Metric system. L'1' is US System
      rectSetup.left = MulDiv (pagesetupMargin.left, ptDpi.x, 2540);
      rectSetup.top = MulDiv (pagesetupMargin.top, ptDpi.y, 2540);
      rectSetup.right  = MulDiv(pagesetupMargin.right, ptDpi.x, 2540);
      rectSetup.bottom  = MulDiv(pagesetupMargin.bottom, ptDpi.y, 2540);
    } else {
      rectSetup.left  = MulDiv(pagesetupMargin.left, ptDpi.x, 1000);
      rectSetup.top  = MulDiv(pagesetupMargin.top, ptDpi.y, 1000);
      rectSetup.right  = MulDiv(pagesetupMargin.right, ptDpi.x, 1000);
      rectSetup.bottom  = MulDiv(pagesetupMargin.bottom, ptDpi.y, 1000);
    }

    // Dont reduce margins below the minimum printable area
    rectMargins.left  = max(rectPhysMargins.left, rectSetup.left);
    rectMargins.top  = max(rectPhysMargins.top, rectSetup.top);
    rectMargins.right  = max(rectPhysMargins.right, rectSetup.right);
    rectMargins.bottom  = max(rectPhysMargins.bottom, rectSetup.bottom);
  } else {
    rectMargins.left  = rectPhysMargins.left;
    rectMargins.top  = rectPhysMargins.top;
    rectMargins.right  = rectPhysMargins.right;
    rectMargins.bottom  = rectPhysMargins.bottom;
  }

  // rectMargins now contains the values used to shrink the printable
  // area of the page.

  // Convert device coordinates into logical coordinates
  DPtoLP(hdc, (LPPOINT)&rectMargins, 2);
  DPtoLP(hdc, (LPPOINT)&rectPhysMargins, 2);

  // Convert page size to logical units and we're done!
  DPtoLP(hdc, (LPPOINT) &ptPage, 1);

  headerLineHeight = MulDiv(8,ptDpi.y, 72);
  fontHeader = CreateFont(headerLineHeight,
                          0, 0, 0,
                          FW_BOLD,
                          0,
                          0,
                          0, 0, 0,
                          0, 0, 0,
                          L"Arial");
  SelectObject(hdc, fontHeader);
  GetTextMetrics(hdc, &tm);
  headerLineHeight = tm.tmHeight + tm.tmExternalLeading;

  if (iPrintHeader == 3)
    headerLineHeight = 0;

  footerLineHeight = MulDiv(7,ptDpi.y, 72);
  fontFooter = CreateFont(footerLineHeight,
                          0, 0, 0,
                          FW_NORMAL,
                          0,
                          0,
                          0, 0, 0,
                          0, 0, 0,
                          L"Arial");
  SelectObject(hdc, fontFooter);
  GetTextMetrics(hdc, &tm);
  footerLineHeight = tm.tmHeight + tm.tmExternalLeading;

  if (iPrintFooter == 1)
    footerLineHeight = 0;

  di.lpszDocName = pszDocTitle;
  di.lpszOutput = 0;
  di.lpszDatatype = 0;
  di.fwType = 0;
  if (StartDoc(hdc, &di) < 0) {
    DeleteDC(hdc);
    if (fontHeader)
      DeleteObject(fontHeader);
    if (fontFooter)
      DeleteObject(fontFooter);
    return FALSE;
  }

  // Get current date...
  SYSTEMTIME st;
  GetLocalTime(&st);
  GetDateFormat(LOCALE_USER_DEFAULT,DATE_SHORTDATE,&st,NULL,dateString,256);

  // Get current time...
  if (iPrintHeader == 0)
  {
    WCHAR timeString[128];
    GetTimeFormat(LOCALE_USER_DEFAULT,TIME_NOSECONDS,&st,NULL,timeString,128);
    lstrcat(dateString,L" ");
    lstrcat(dateString,timeString);
  }

  // Set print color mode
  int printColorModes[5] = {
    SC_PRINT_NORMAL,
    SC_PRINT_INVERTLIGHT,
    SC_PRINT_BLACKONWHITE,
    SC_PRINT_COLOURONWHITE,
    SC_PRINT_COLOURONWHITEDEFAULTBG };
  SendMessage(hwnd,SCI_SETPRINTCOLOURMODE,printColorModes[iPrintColor],0);

  // Set print zoom...
  SendMessage(hwnd,SCI_SETPRINTMAGNIFICATION,(WPARAM)iPrintZoom,0);

  lengthDoc = SendMessage(hwnd,SCI_GETLENGTH,0,0);
  lengthDocMax = lengthDoc;
  lengthPrinted = 0;

  // Requested to print selection
  if (pdlg.Flags & PD_SELECTION) {
    if (startPos > endPos) {
      lengthPrinted = endPos;
      lengthDoc = startPos;
    } else {
      lengthPrinted = startPos;
      lengthDoc = endPos;
    }

    if (lengthPrinted < 0)
      lengthPrinted = 0;
    if (lengthDoc > lengthDocMax)
      lengthDoc = lengthDocMax;
  }

  // We must substract the physical margins from the printable area
  frPrint.hdc = hdc;
  frPrint.hdcTarget = hdc;
  frPrint.rc.left = rectMargins.left - rectPhysMargins.left;
  frPrint.rc.top = rectMargins.top - rectPhysMargins.top;
  frPrint.rc.right = ptPage.x - rectMargins.right - rectPhysMargins.left;
  frPrint.rc.bottom = ptPage.y - rectMargins.bottom - rectPhysMargins.top;
  frPrint.rcPage.left = 0;
  frPrint.rcPage.top = 0;
  frPrint.rcPage.right = ptPage.x - rectPhysMargins.left - rectPhysMargins.right - 1;
  frPrint.rcPage.bottom = ptPage.y - rectPhysMargins.top - rectPhysMargins.bottom - 1;
  frPrint.rc.top += headerLineHeight + headerLineHeight / 2;
  frPrint.rc.bottom -= footerLineHeight + footerLineHeight / 2;
  // Print each page
  pageNum = 1;

  while (lengthPrinted < lengthDoc) {
    printPage = (!(pdlg.Flags & PD_PAGENUMS) ||
                 (pageNum >= pdlg.nFromPage) && (pageNum <= pdlg.nToPage));

    wsprintf(pageString, pszPageFormat, pageNum);

    if (printPage) {

      // Show wait cursor...
      BeginWaitCursor();

      // Display current page number in Statusbar
      StatusUpdatePrintPage(pageNum);

      StartPage(hdc);

      SetTextColor(hdc, RGB(0,0,0));
      SetBkColor(hdc, RGB(255,255,255));
      SelectObject(hdc, fontHeader);
      UINT ta = SetTextAlign(hdc, TA_BOTTOM);
      RECT rcw = {frPrint.rc.left, frPrint.rc.top - headerLineHeight - headerLineHeight / 2,
                  frPrint.rc.right, frPrint.rc.top - headerLineHeight / 2};
      rcw.bottom = rcw.top + headerLineHeight;

      if (iPrintHeader < 3)
      {
        ExtTextOut(hdc, frPrint.rc.left + 5, frPrint.rc.top - headerLineHeight / 2,
                      /*ETO_OPAQUE*/0, &rcw, pszDocTitle,
                      lstrlen(pszDocTitle), NULL);
      }

      // Print date in header
      if (iPrintHeader == 0 || iPrintHeader == 1)
      {
        SIZE sizeInfo;
        SelectObject(hdc,fontFooter);
        GetTextExtentPoint32(hdc,dateString,lstrlen(dateString),&sizeInfo);
        ExtTextOut(hdc, frPrint.rc.right - 5 - sizeInfo.cx, frPrint.rc.top - headerLineHeight / 2,
                      /*ETO_OPAQUE*/0, &rcw, dateString,
                      lstrlen(dateString), NULL);
      }

      if (iPrintHeader < 3)
      {
        SetTextAlign(hdc, ta);
        pen = CreatePen(0, 1, RGB(0,0,0));
        penOld = (HPEN)SelectObject(hdc, pen);
        MoveToEx(hdc, frPrint.rc.left, frPrint.rc.top - headerLineHeight / 4, NULL);
        LineTo(hdc, frPrint.rc.right, frPrint.rc.top - headerLineHeight / 4);
        SelectObject(hdc, penOld);
        DeleteObject(pen);
      }
    }

    frPrint.chrg.cpMin = lengthPrinted;
    frPrint.chrg.cpMax = lengthDoc;

    lengthPrinted = SendMessage(hwnd,SCI_FORMATRANGE,printPage,(LPARAM)&frPrint);

    if (printPage) {
      SetTextColor(hdc, RGB(0,0,0));
      SetBkColor(hdc, RGB(255,255,255));
      SelectObject(hdc, fontFooter);
      UINT ta = SetTextAlign(hdc, TA_TOP);
      RECT rcw = {frPrint.rc.left, frPrint.rc.bottom + footerLineHeight / 2,
                  frPrint.rc.right, frPrint.rc.bottom + footerLineHeight + footerLineHeight / 2};

      if (iPrintFooter == 0)
      {
        SIZE sizeFooter;
        GetTextExtentPoint32(hdc,pageString,lstrlen(pageString),&sizeFooter);
        ExtTextOut(hdc, frPrint.rc.right - 5 - sizeFooter.cx, frPrint.rc.bottom + footerLineHeight / 2,
                      /*ETO_OPAQUE*/0, &rcw, pageString,
                      lstrlen(pageString), NULL);

        SetTextAlign(hdc, ta);
        pen = ::CreatePen(0, 1, RGB(0,0,0));
        penOld = (HPEN)SelectObject(hdc, pen);
        SetBkColor(hdc, RGB(0,0,0));
        MoveToEx(hdc, frPrint.rc.left, frPrint.rc.bottom + footerLineHeight / 4, NULL);
        LineTo(hdc, frPrint.rc.right, frPrint.rc.bottom + footerLineHeight / 4);
        SelectObject(hdc, penOld);
        DeleteObject(pen);
      }

      EndPage(hdc);
    }
    pageNum++;

    if ((pdlg.Flags & PD_PAGENUMS) && (pageNum > pdlg.nToPage))
      break;
  }

  SendMessage(hwnd,SCI_FORMATRANGE, FALSE, 0);

  EndDoc(hdc);
  DeleteDC(hdc);
  if (fontHeader)
    DeleteObject(fontHeader);
  if (fontFooter)
    DeleteObject(fontFooter);

  // Reset Statusbar to default mode
  StatusSetSimple(hwndStatus,FALSE);

  // Remove wait cursor...
  EndWaitCursor();

  return TRUE;
}
示例#21
0
static LRESULT CALLBACK HyperlinkWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
	struct HyperlinkWndData *dat=(struct HyperlinkWndData*)GetWindowLongPtr(hwnd,0);
	switch(msg) {
		case WM_NCCREATE:
			dat=(struct HyperlinkWndData*)mir_calloc(sizeof(struct HyperlinkWndData));
			if(dat==NULL) return FALSE; /* fail creation */
			SetWindowLongPtr(hwnd,0,(LONG_PTR)dat); /* always succeeds */
			/* fall thru */
		case WM_SYSCOLORCHANGE:
			if(!(dat->flags&HLKF_HASENABLECOLOR)) {
				if(GetSysColorBrush(COLOR_HOTLIGHT)==NULL) dat->enableColor=RGB(0,0,255);
				else dat->enableColor=GetSysColor(COLOR_HOTLIGHT);
				dat->focusColor = RGB(GetRValue(dat->enableColor) / 2, GetGValue(dat->enableColor) / 2, GetBValue(dat->enableColor) / 2);
			}
			if(!(dat->flags&HLKF_HASDISABLECOLOR))
				dat->disableColor=GetSysColor(COLOR_GRAYTEXT);
			break;

		case WM_SETFOCUS:
		case WM_KILLFOCUS:
			RedrawWindow(hwnd, NULL, NULL, RDW_INVALIDATE);
			break;
		case WM_MOUSEACTIVATE:
			SetFocus(hwnd);
			return MA_ACTIVATE;
		case WM_GETDLGCODE:
		{
			if (lParam)
			{
				MSG *msg = (MSG *) lParam;
				if (msg->message == WM_KEYDOWN)
				{
					if (msg->wParam == VK_TAB)
						return 0;
					if (msg->wParam == VK_ESCAPE)
						return 0;
				} else
				if (msg->message == WM_CHAR)
				{
					if (msg->wParam == '\t')
						return 0;
					if (msg->wParam == 27)
						return 0;
				}
			}
			return DLGC_WANTMESSAGE;
		}

		case WM_KEYDOWN:
		{
			switch (wParam)
			{
			case VK_SPACE:
			case VK_RETURN:
				SendMessage(GetParent(hwnd),WM_COMMAND,MAKEWPARAM(GetDlgCtrlID(hwnd),STN_CLICKED),(LPARAM)hwnd);
				break;
			}
			return 0;
		}

		case WM_LBUTTONDOWN:
		{	POINT pt;
			POINTSTOPOINT(pt,MAKEPOINTS(lParam));
			if(!PtInRect(&dat->rcText,pt)) break;
			SendMessage(GetParent(hwnd),WM_COMMAND,MAKEWPARAM(GetDlgCtrlID(hwnd),STN_CLICKED),(LPARAM)hwnd);
			return 0;
		}
		case WM_SETFONT:
		{	LOGFONT lf;
			HFONT hFont;
			if((HFONT)wParam==NULL) { /* use default system color */
				dat->hEnableFont=dat->hDisableFont=NULL;
				return 0;
			}
			if(GetObject((HFONT)wParam,sizeof(lf),&lf)) {
				lf.lfUnderline=1;
				hFont=CreateFontIndirect(&lf);
				if(hFont!=NULL) {
					dat->hEnableFont=hFont;
					dat->hDisableFont=(HFONT)wParam;
					if(LOWORD(lParam)) SendMessage(hwnd,HLK_INVALIDATE,0,0);
					SendMessage(hwnd,HLK_MEASURETEXT,0,0);
				}
			}
			return 0;
		}
		case WM_ERASEBKGND:
			return TRUE;
		case WM_ENABLE:
		case HLK_INVALIDATE:
		{	RECT rcWnd;
			POINT pt;
			HWND hwndParent;
			if(!GetWindowRect(hwnd,&rcWnd)) break;
			pt.x=rcWnd.left;
			pt.y=rcWnd.top;
			hwndParent=GetParent(hwnd);
			if(hwndParent==NULL) hwndParent=hwnd;
			if(!ScreenToClient(hwndParent,&pt)) break;
			rcWnd.right=pt.x+(rcWnd.right-rcWnd.left);
			rcWnd.bottom=pt.y+(rcWnd.bottom-rcWnd.top);
			rcWnd.left=pt.x;
			rcWnd.top=pt.y;
			InvalidateRect(hwndParent,&rcWnd,TRUE);
			return 0;
		}
		case WM_GETFONT:
			return (LRESULT)dat->hDisableFont;
		case WM_CREATE:
		case HLK_MEASURETEXT:
		{	TCHAR szText[256];
			if(!GetWindowText(hwnd,szText,SIZEOF(szText))) return 0;
			lParam=(LPARAM)szText;
			/* fall thru */
		case WM_SETTEXT:
		{	HFONT hPrevFont = NULL;
			SIZE textSize;
			RECT rc;
			HDC hdc;
			LONG style;
			BOOL fMeasured=FALSE;
			hdc=GetDC(hwnd);
			if(hdc==NULL) return 0; /* text change failed */
			if(dat->hEnableFont!=NULL) hPrevFont=(HFONT)SelectObject(hdc,dat->hEnableFont);
			if(dat->hEnableFont==NULL || hPrevFont!=NULL) /* select failed? */
				if(GetTextExtentPoint32(hdc,(TCHAR*)lParam,lstrlen((TCHAR*)lParam),&textSize))
					if(GetClientRect(hwnd,&rc)) {
						dat->rcText.top=0;
						dat->rcText.bottom=dat->rcText.top+textSize.cy;
						style=GetWindowLongPtr(hwnd,GWL_STYLE);
						if(style&SS_CENTER) dat->rcText.left=(rc.right-textSize.cx)/2;
						else if(style&SS_RIGHT) dat->rcText.left=rc.right-textSize.cx;
						else dat->rcText.left=0;
						dat->rcText.right=dat->rcText.left+textSize.cx;
						fMeasured=TRUE;
					}
			if(dat->hEnableFont!=NULL && hPrevFont!=NULL) SelectObject(hdc,hPrevFont);
			ReleaseDC(hwnd,hdc);
			if(!fMeasured) return 0; /* text change failed */
			SendMessage(hwnd,HLK_INVALIDATE,0,0);
			break;
		}}
		case WM_SETCURSOR:
		{	POINT pt;
			HCURSOR hCursor;
			if(!GetCursorPos(&pt)) return FALSE;
			if(!ScreenToClient(hwnd,&pt)) return FALSE;
			if(PtInRect(&dat->rcText,pt)) {
				hCursor=(HCURSOR)GetClassLongPtr(hwnd,GCLP_HCURSOR);
				if(hCursor==NULL) hCursor=LoadCursor(NULL,IDC_HAND); /* Win2000+ */
			}
			else hCursor=LoadCursor(NULL,IDC_ARROW);
			SetCursor(hCursor);
			return TRUE;
		}
		case HLK_SETENABLECOLOUR:
		{	COLORREF prevColor=dat->enableColor;
			dat->enableColor=(COLORREF)wParam;
			dat->focusColor = RGB(GetRValue(dat->enableColor) / 2, GetGValue(dat->enableColor) / 2, GetBValue(dat->enableColor) / 2);
			dat->flags|=HLKF_HASENABLECOLOR;
			return (LRESULT)prevColor;
		}
		case HLK_SETDISABLECOLOUR:
		{	COLORREF prevColor=dat->disableColor;
			dat->disableColor=(COLORREF)wParam;
			dat->flags|=HLKF_HASDISABLECOLOR;
			return (LRESULT)prevColor;
		}
		case WM_NCPAINT:
			return 0;
		case WM_PAINT:
		{	HFONT hPrevFont;
			RECT rc;
			TCHAR szText[256];
			UINT alignFlag;
			COLORREF textColor;
			PAINTSTRUCT ps;
			HDC hdc;
			
			hdc=BeginPaint(hwnd,&ps);
			if(hdc!=NULL) {
				if(IsWindowEnabled(hwnd)) {
					hPrevFont=(HFONT)SelectObject(hdc,dat->hEnableFont);
					textColor = (GetFocus() == hwnd) ? dat->focusColor : dat->enableColor;
				} else {
					hPrevFont=(HFONT)SelectObject(hdc,dat->hDisableFont);
					textColor=dat->disableColor;
				}
				if(GetClientRect(hwnd,&rc) && GetWindowText(hwnd,szText,SIZEOF(szText))) {
					if (drawThemeParentBackground && IsWinVerXPPlus())
					{
						BOOL fSmoothing;
						UINT fSmoothingType;
						SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &fSmoothing, 0);
						SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &fSmoothingType, 0);
						if (fSmoothing && fSmoothingType == FE_FONTSMOOTHINGCLEARTYPE)
							drawThemeParentBackground(hwnd, hdc, &rc);
					}
					SetBkMode(hdc,TRANSPARENT);
					SetTextColor(hdc,textColor);
					alignFlag=(GetWindowLongPtr(hwnd,GWL_STYLE)&(SS_CENTER|SS_RIGHT|SS_LEFT));
					DrawText(hdc,szText,-1,&rc,alignFlag|DT_NOPREFIX|DT_SINGLELINE|DT_TOP);
				}
				if(hPrevFont!=NULL) SelectObject(hdc,hPrevFont);
				EndPaint(hwnd,&ps);
			}
			return 0;
		}
		case WM_NCDESTROY:			
			if(dat->hEnableFont!=NULL) DeleteObject(dat->hEnableFont);
			mir_free(dat);			
			break;
	}
	return DefWindowProc(hwnd,msg,wParam,lParam);
}
示例#22
0
static INT_PTR CALLBACK PhpHiddenProcessesDlgProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
    )
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            HWND lvHandle;

            PhCenterWindow(hwndDlg, GetParent(hwndDlg));
            PhHiddenProcessesListViewHandle = lvHandle = GetDlgItem(hwndDlg, IDC_PROCESSES);

            PhInitializeLayoutManager(&WindowLayoutManager, hwndDlg);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_INTRO),
                NULL, PH_ANCHOR_LEFT | PH_ANCHOR_TOP | PH_ANCHOR_RIGHT | PH_LAYOUT_FORCE_INVALIDATE);
            PhAddLayoutItem(&WindowLayoutManager, lvHandle,
                NULL, PH_ANCHOR_ALL);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_DESCRIPTION),
                NULL, PH_ANCHOR_LEFT | PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM | PH_LAYOUT_FORCE_INVALIDATE);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_METHOD),
                NULL, PH_ANCHOR_LEFT | PH_ANCHOR_BOTTOM);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_TERMINATE),
                NULL, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_SAVE),
                NULL, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_SCAN),
                NULL, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDOK),
                NULL, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);

            MinimumSize.left = 0;
            MinimumSize.top = 0;
            MinimumSize.right = 330;
            MinimumSize.bottom = 140;
            MapDialogRect(hwndDlg, &MinimumSize);

            PhRegisterDialog(hwndDlg);

            PhLoadWindowPlacementFromSetting(L"HiddenProcessesWindowPosition", L"HiddenProcessesWindowSize", hwndDlg);

            PhSetListViewStyle(lvHandle, TRUE, TRUE);
            PhSetControlTheme(lvHandle, L"explorer");
            PhAddListViewColumn(lvHandle, 0, 0, 0, LVCFMT_LEFT, 320, L"Process");
            PhAddListViewColumn(lvHandle, 1, 1, 1, LVCFMT_LEFT, 60, L"PID");

            PhSetExtendedListView(lvHandle);
            PhLoadListViewColumnsFromSetting(L"HiddenProcessesListViewColumns", lvHandle);
            ExtendedListView_AddFallbackColumn(lvHandle, 0);
            ExtendedListView_AddFallbackColumn(lvHandle, 1);
            ExtendedListView_SetItemColorFunction(lvHandle, PhpHiddenProcessesColorFunction);

            ComboBox_AddString(GetDlgItem(hwndDlg, IDC_METHOD), L"Brute Force");
            ComboBox_AddString(GetDlgItem(hwndDlg, IDC_METHOD), L"CSR Handles");
            PhSelectComboBoxString(GetDlgItem(hwndDlg, IDC_METHOD), L"CSR Handles", FALSE);

            EnableWindow(GetDlgItem(hwndDlg, IDC_TERMINATE), FALSE);
        }
        break;
    case WM_DESTROY:
        {
            PhSaveWindowPlacementToSetting(L"HiddenProcessesWindowPosition", L"HiddenProcessesWindowSize", hwndDlg);
            PhSaveListViewColumnsToSetting(L"HiddenProcessesListViewColumns", PhHiddenProcessesListViewHandle);
        }
        break;
    case WM_CLOSE:
        {
            // Hide, don't close.
            ShowWindow(hwndDlg, SW_HIDE);
            SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, 0);
        }
        return TRUE;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
            case IDOK:
                {
                    SendMessage(hwndDlg, WM_CLOSE, 0, 0);
                }
                break;
            case IDC_SCAN:
                {
                    NTSTATUS status;
                    PPH_STRING method;

                    method = PhGetWindowText(GetDlgItem(hwndDlg, IDC_METHOD));
                    PhAutoDereferenceObject(method);

                    if (ProcessesList)
                    {
                        ULONG i;

                        for (i = 0; i < ProcessesList->Count; i++)
                        {
                            PPH_HIDDEN_PROCESS_ENTRY entry = ProcessesList->Items[i];

                            if (entry->FileName)
                                PhDereferenceObject(entry->FileName);

                            PhFree(entry);
                        }

                        PhDereferenceObject(ProcessesList);
                    }

                    ListView_DeleteAllItems(PhHiddenProcessesListViewHandle);

                    ProcessesList = PhCreateList(40);

                    ProcessesMethod =
                        PhEqualString2(method, L"Brute Force", TRUE) ?
                        BruteForceScanMethod :
                        CsrHandlesScanMethod;
                    NumberOfHiddenProcesses = 0;
                    NumberOfTerminatedProcesses = 0;

                    ExtendedListView_SetRedraw(PhHiddenProcessesListViewHandle, FALSE);
                    status = PhEnumHiddenProcesses(
                        ProcessesMethod,
                        PhpHiddenProcessesCallback,
                        NULL
                        );
                    ExtendedListView_SortItems(PhHiddenProcessesListViewHandle);
                    ExtendedListView_SetRedraw(PhHiddenProcessesListViewHandle, TRUE);

                    if (NT_SUCCESS(status))
                    {
                        SetDlgItemText(hwndDlg, IDC_DESCRIPTION,
                            PhaFormatString(L"%u hidden process(es), %u terminated process(es).",
                            NumberOfHiddenProcesses, NumberOfTerminatedProcesses)->Buffer
                            );
                        InvalidateRect(GetDlgItem(hwndDlg, IDC_DESCRIPTION), NULL, TRUE);
                    }
                    else
                    {
                        PhShowStatus(hwndDlg, L"Unable to perform the scan", status, 0);
                    }
                }
                break;
            case IDC_TERMINATE:
                {
                    PPH_HIDDEN_PROCESS_ENTRY *entries;
                    ULONG numberOfEntries;
                    ULONG i;

                    PhGetSelectedListViewItemParams(PhHiddenProcessesListViewHandle, &entries, &numberOfEntries);

                    if (numberOfEntries != 0)
                    {
                        if (!PhGetIntegerSetting(L"EnableWarnings") ||
                            PhShowConfirmMessage(
                            hwndDlg,
                            L"terminate",
                            L"the selected process(es)",
                            L"Terminating a hidden process may cause the system to become unstable "
                            L"or crash.",
                            TRUE
                            ))
                        {
                            NTSTATUS status;
                            HANDLE processHandle;
                            BOOLEAN refresh;

                            refresh = FALSE;

                            for (i = 0; i < numberOfEntries; i++)
                            {
                                if (ProcessesMethod == BruteForceScanMethod)
                                {
                                    status = PhOpenProcess(
                                        &processHandle,
                                        PROCESS_TERMINATE,
                                        entries[i]->ProcessId
                                        );
                                }
                                else
                                {
                                    status = PhOpenProcessByCsrHandles(
                                        &processHandle,
                                        PROCESS_TERMINATE,
                                        entries[i]->ProcessId
                                        );
                                }

                                if (NT_SUCCESS(status))
                                {
                                    status = PhTerminateProcess(processHandle, STATUS_SUCCESS);
                                    NtClose(processHandle);

                                    if (NT_SUCCESS(status))
                                        refresh = TRUE;
                                }
                                else
                                {
                                    PhShowStatus(hwndDlg, L"Unable to terminate the process", status, 0);
                                }
                            }

                            if (refresh)
                            {
                                LARGE_INTEGER interval;

                                // Sleep for a bit before continuing. It seems to help avoid
                                // BSODs.
                                interval.QuadPart = -250 * PH_TIMEOUT_MS;
                                NtDelayExecution(FALSE, &interval);
                                SendMessage(hwndDlg, WM_COMMAND, IDC_SCAN, 0);
                            }
                        }
                    }

                    PhFree(entries);
                }
                break;
            case IDC_SAVE:
                {
                    static PH_FILETYPE_FILTER filters[] =
                    {
                        { L"Text files (*.txt)", L"*.txt" },
                        { L"All files (*.*)", L"*.*" }
                    };
                    PVOID fileDialog;

                    fileDialog = PhCreateSaveFileDialog();

                    PhSetFileDialogFilter(fileDialog, filters, sizeof(filters) / sizeof(PH_FILETYPE_FILTER));
                    PhSetFileDialogFileName(fileDialog, L"Hidden Processes.txt");

                    if (PhShowFileDialog(hwndDlg, fileDialog))
                    {
                        NTSTATUS status;
                        PPH_STRING fileName;
                        PPH_FILE_STREAM fileStream;

                        fileName = PhGetFileDialogFileName(fileDialog);
                        PhAutoDereferenceObject(fileName);

                        if (NT_SUCCESS(status = PhCreateFileStream(
                            &fileStream,
                            fileName->Buffer,
                            FILE_GENERIC_WRITE,
                            FILE_SHARE_READ,
                            FILE_OVERWRITE_IF,
                            0
                            )))
                        {
                            PhWriteStringAsUtf8FileStream(fileStream, &PhUnicodeByteOrderMark);
                            PhWritePhTextHeader(fileStream);
                            PhWriteStringAsUtf8FileStream2(fileStream, L"Method: ");
                            PhWriteStringAsUtf8FileStream2(fileStream,
                                ProcessesMethod == BruteForceScanMethod ? L"Brute Force\r\n" : L"CSR Handles\r\n");
                            PhWriteStringFormatAsUtf8FileStream(
                                fileStream,
                                L"Hidden: %u\r\nTerminated: %u\r\n\r\n",
                                NumberOfHiddenProcesses,
                                NumberOfTerminatedProcesses
                                );

                            if (ProcessesList)
                            {
                                ULONG i;

                                for (i = 0; i < ProcessesList->Count; i++)
                                {
                                    PPH_HIDDEN_PROCESS_ENTRY entry = ProcessesList->Items[i];

                                    if (entry->Type == HiddenProcess)
                                        PhWriteStringAsUtf8FileStream2(fileStream, L"[HIDDEN] ");
                                    else if (entry->Type == TerminatedProcess)
                                        PhWriteStringAsUtf8FileStream2(fileStream, L"[Terminated] ");
                                    else if (entry->Type != NormalProcess)
                                        continue;

                                    PhWriteStringFormatAsUtf8FileStream(
                                        fileStream,
                                        L"%s (%u)\r\n",
                                        entry->FileName->Buffer,
                                        HandleToUlong(entry->ProcessId)
                                        );
                                }
                            }

                            PhDereferenceObject(fileStream);
                        }

                        if (!NT_SUCCESS(status))
                            PhShowStatus(hwndDlg, L"Unable to create the file", status, 0);
                    }

                    PhFreeFileDialog(fileDialog);
                }
                break;
            }
        }
        break;
    case WM_NOTIFY:
        {
            LPNMHDR header = (LPNMHDR)lParam;

            PhHandleListViewNotifyBehaviors(lParam, PhHiddenProcessesListViewHandle, PH_LIST_VIEW_DEFAULT_1_BEHAVIORS);

            switch (header->code)
            {
            case LVN_ITEMCHANGED:
                {
                    if (header->hwndFrom == PhHiddenProcessesListViewHandle)
                    {
                        EnableWindow(
                            GetDlgItem(hwndDlg, IDC_TERMINATE),
                            ListView_GetSelectedCount(PhHiddenProcessesListViewHandle) > 0
                            );
                    }
                }
                break;
            case NM_DBLCLK:
                {
                    if (header->hwndFrom == PhHiddenProcessesListViewHandle)
                    {
                        PPH_HIDDEN_PROCESS_ENTRY entry;

                        entry = PhGetSelectedListViewItemParam(PhHiddenProcessesListViewHandle);

                        if (entry)
                        {
                            PPH_PROCESS_ITEM processItem;

                            if (processItem = PhpCreateProcessItemForHiddenProcess(entry))
                            {
                                ProcessHacker_ShowProcessProperties(PhMainWndHandle, processItem);
                                PhDereferenceObject(processItem);
                            }
                            else
                            {
                                PhShowError(hwndDlg, L"Unable to create a process structure for the selected process.");
                            }
                        }
                    }
                }
                break;
            }
        }
        break;
    case WM_SIZE:
        {
            PhLayoutManagerLayout(&WindowLayoutManager);
        }
        break;
    case WM_SIZING:
        {
            PhResizingMinimumSize((PRECT)lParam, wParam, MinimumSize.right, MinimumSize.bottom);
        }
        break;
    case WM_CTLCOLORSTATIC:
        {
            if ((HWND)lParam == GetDlgItem(hwndDlg, IDC_DESCRIPTION))
            {
                if (NumberOfHiddenProcesses != 0)
                {
                    SetTextColor((HDC)wParam, RGB(0xff, 0x00, 0x00));
                }

                SetBkColor((HDC)wParam, GetSysColor(COLOR_3DFACE));

                return (INT_PTR)GetSysColorBrush(COLOR_3DFACE);
            }
        }
        break;
    }

    REFLECT_MESSAGE_DLG(hwndDlg, PhHiddenProcessesListViewHandle, uMsg, wParam, lParam);

    return FALSE;
}
示例#23
0
	void ButtonX::drawCaption(HDC hdc, RECT updRect) {
		//if (!this->_icon) return;
		Rect textRc, clientRc;
		GetClientRect(this->_hwnd, textRc.ref());
		clientRc = textRc;
		Size imageSize = _image ? _image->getSize() : Size();
		bool enabled = IsWindowEnabled(this->_hwnd)!=0;
		int state = SendMessage(this->_hwnd, BM_GETSTATE, 0, 0);
		int style = GetWindowLong(this->_hwnd, GWL_STYLE);
		
		if (this->isFlat() && state == BST_FOCUS) {
			Rect focusRc = clientRc;
			focusRc.expand(-2, -2);
			DrawFocusRect(hdc, focusRc.ref());
		}

		if (!this->_text.empty()) {
			SetBkMode(hdc , TRANSPARENT);
			SetTextColor(hdc, enabled ? GetSysColor(COLOR_BTNTEXT) : GetSysColor(COLOR_BTNSHADOW));
			textRc.bottom = 0;
			textRc.right -=	6;
			if (this->_image)
				textRc.right -=	this->_iconMargin + imageSize.w;
			HFONT oldFont = (HFONT) SelectObject(hdc, (HGDIOBJ)SendMessage(this->_hwnd, WM_GETFONT, 0, 0));
			DrawText(hdc, this->_text, -1, textRc.ref(), DT_LEFT | DT_NOPREFIX | DT_CALCRECT | DT_WORDBREAK);
			Point pt, ptImg;
			bool imgAside = ((style & BS_VCENTER) == BS_VCENTER || (style & BS_VCENTER) == 0);
			int textStyle = 0;
			switch (style & BS_CENTER) {
				case BS_LEFT:
					pt.x = ((imgAside && this->_image.isValid()) ? (imageSize.w + this->_iconMargin) : 0) + 2;
					ptImg.x = 2;
					textStyle = DT_LEFT;
					break;
				case BS_RIGHT:
					pt.x = clientRc.width() - textRc.width() - 2;
					if (!imgAside && _image.isValid()) {
						ptImg.x = clientRc.width() - imageSize.w - 2;
					}
					textStyle = DT_RIGHT;
					break;
				default:
					pt.x = (clientRc.right - textRc.right + ((imgAside && this->_image.isValid()) ? (imageSize.w + this->_iconMargin) : 0))/2;
					if (!imgAside && _image.isValid()) 
						ptImg.x = clientRc.getCenter().x - imageSize.w / 2;
					textStyle = DT_CENTER;
					break;
			}
			if (imgAside) {
				ptImg.x = pt.x - imageSize.w - this->_iconMargin;
			}
			// BS_TOP / BOTTOM oznaczaj¹ pozycjê SAMEGO TEKSTU wzglêdem ikonki
			switch (style & BS_VCENTER) {
				case BS_TOP:
                    pt.y = (clientRc.bottom - textRc.bottom)/2 - (imageSize.h + _iconMargin) / 2;
					ptImg.y = (clientRc.bottom - imageSize.h)/2 + (textRc.bottom + _iconMargin) / 2;
					break;
				case BS_BOTTOM:
                    pt.y = (clientRc.bottom - textRc.bottom)/2 + (imageSize.h + _iconMargin) / 2;
					ptImg.y = (clientRc.bottom - imageSize.h)/2 - (textRc.bottom + _iconMargin) / 2;
					break;
				default: // w jednej linii na œrodku
					pt.y = (clientRc.bottom - textRc.bottom)/2;
					ptImg.y = (clientRc.bottom - imageSize.h)/2;
			}
			textRc.setPos(pt);
			DrawText(hdc, this->_text, -1, textRc.ref(), textStyle | DT_NOPREFIX | DT_WORDBREAK);
			SelectObject(hdc, (HGDIOBJ)oldFont);
			if (this->_image) {
				this->_image->draw(hdc, ptImg);
			}
		} else {
			if (this->_image) {
				this->_image->draw(hdc, Point((clientRc.right - imageSize.w)/2 , (clientRc.bottom - imageSize.h)/2));
			}
		}
	}
示例#24
0
static BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
	case WM_INITDIALOG:
		{
			HINSTANCE hInst = GetModuleHandle(NULL);
			SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(hInst, MAKEINTRESOURCE(IDI_ICON1)));
			SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)LoadIcon(hInst, MAKEINTRESOURCE(IDI_ICON1)));
		}
		break;
	case WM_CTLCOLORDLG:
		return (LONG)g_hbrBackground;
	case WM_CTLCOLORSTATIC:
		{
			HDC hdcStatic = (HDC)wParam;
			SetTextColor(hdcStatic, RGB(255,255,255));
			//if you leave this line off the background will be filled in with the brush you specify, 
			//but when the control draws the text it will get written over with the default background 
			//color! Setting the text drawing mode to transparent fixes this problem. The other option 
			//would be to SetBkColor() to the same color as our background brush, but I like this solution better.
			SetBkMode(hdcStatic, TRANSPARENT);
			return (LONG)g_hbrBackground;
		}
		break;
	case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
			case IDC_BUTTON1: //fill random text
				//IDC_EDIT1
				SetDlgItemText(hwnd, IDC_EDIT1, L"Hello how are you?");
				break;
			case IDC_BUTTON2: // get text
				{
					int len = GetWindowTextLength(GetDlgItem(hwnd, IDC_EDIT1));
					if (len > 0)
					{
						wchar_t* buf;
						//NOTE: len+1 because GetWindowTextLength returns number of characters (not including NULL). 
						buf = (wchar_t*)GlobalAlloc(GPTR, (len+1)*sizeof(wchar_t));
						//returns number of characters (not including NULL). 
						GetDlgItemText(hwnd, IDC_EDIT1, buf, len+1);

						MessageBox(hwnd, buf, L"Notice", MB_OK);

						GlobalFree((HANDLE)buf);
					}
				}
				break;
			case IDC_BUTTON4: // get number
				{
					//last param: signed
					BOOL translated;
					int num = GetDlgItemInt(hwnd, IDC_EDIT1, &translated, TRUE);
					if (translated)
					{
						std::wostringstream wostr;
						wostr << L"the number is " << num;
						MessageBox(hwnd, wostr.str().data(), L"Notice", MB_OK);
					}
					else
					{
						MessageBox(hwnd, L"not a number", L"Notice", MB_OK);
					}
				}
				break;
			case IDC_BUTTON5:
				{
					int index = SendDlgItemMessage(hwnd, IDC_LIST1, LB_ADDSTRING, 0, (LPARAM)L"Hi there!");
				}
				break;
			case IDC_LIST1:
				{
					switch(HIWORD(wParam))
					{
					case LBN_SELCHANGE:
						//Selection changed, do stuff here
						MessageBox(hwnd, L"sel changed", L"Notice", MB_OK);
						break;
					}
				}
				break;
			case IDC_BUTTON6:
				{
					HWND hList = GetDlgItem(hwnd, IDC_LIST1);
					int index = SendMessage(hList, LB_GETCURSEL, 0,0);
					std::cout << index;
					//Note that static controls are all given a default ID of IDC_STATIC (-1) by the resource editor, 
					//so if you want to be able to tell them apart you'll need to assign them new IDs.
					SetDlgItemInt(hwnd, IDC_STATIC1, index, TRUE);
				}
				break;
			case IDOK:
				EndDialog(hwnd, IDOK);
				break;
			case IDCANCEL:
				EndDialog(hwnd, IDCANCEL);
				break;
			}
		}
		break;
	default:
		return FALSE;
	}
	return TRUE;
}
示例#25
0
INT_PTR CALLBACK DlgProcAlarm(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	WindowData *wd = (WindowData*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);

		Utils_RestoreWindowPositionNoSize(hwndDlg, 0, MODULENAME, "Notify");
		SetFocus(GetDlgItem(hwndDlg, IDC_SNOOZE));

		wd = new WindowData;
		wd->moving = false;
		wd->alarm = nullptr;
		wd->win_num = win_num++;

		if (wd->win_num > 0) {
			RECT r;
			GetWindowRect(hwndDlg, &r);
			r.top += 20;
			r.left += 20;

			SetWindowPos(hwndDlg, nullptr, r.left, r.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
			Utils_SaveWindowPosition(hwndDlg, 0, MODULENAME, "Notify");
		}
		SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)wd);

		// options
		SendMessage(hwndDlg, WMU_SETOPT, 0, 0);

		// fonts
		SendMessage(hwndDlg, WMU_SETFONTS, 0, 0);
		return FALSE;

	case WMU_REFRESH:
		InvalidateRect(hwndDlg, nullptr, TRUE);
		return TRUE;

	case WM_CTLCOLORSTATIC:
		{
			HDC hdc = (HDC)wParam;
			HWND hwndCtrl = (HWND)lParam;

			if (hBackgroundBrush) {
				if (hTitleFont && GetDlgItem(hwndDlg, IDC_TITLE) == hwndCtrl)
					SetTextColor(hdc, title_font_colour);
				else if (hWindowFont)
					SetTextColor(hdc, window_font_colour);

				SetBkMode(hdc, TRANSPARENT);
				return (INT_PTR)hBackgroundBrush;
			}
		}
		break;

	case WM_CTLCOLORDLG:
		if (hBackgroundBrush)
			return (INT_PTR)hBackgroundBrush;
		break;

	case WMU_SETFONTS:
		// fonts
		if (hWindowFont)
			SendMessage(hwndDlg, WM_SETFONT, (WPARAM)hWindowFont, TRUE);
		if (hTitleFont)
			SendDlgItemMessage(hwndDlg, IDC_TITLE, WM_SETFONT, (WPARAM)hTitleFont, TRUE);

		if (hBackgroundBrush) {
			SetClassLongPtr(hwndDlg, GCLP_HBRBACKGROUND, (LONG_PTR)hBackgroundBrush);
			InvalidateRect(hwndDlg, nullptr, TRUE);
		}
		return TRUE;

	case WMU_SETOPT:
		Options *opt;
		if (lParam)
			opt = (Options*)lParam;
		else
			opt = &options;

		// round corners
		if (opt->aw_roundcorners) {
			HRGN hRgn1;
			RECT r;
			int w = 10;
			GetWindowRect(hwndDlg, &r);
			int h = (r.right - r.left) > (w * 2) ? w : (r.right - r.left);
			int v = (r.bottom - r.top) > (w * 2) ? w : (r.bottom - r.top);
			h = (h < v) ? h : v;
			hRgn1 = CreateRoundRectRgn(0, 0, (r.right - r.left + 1), (r.bottom - r.top + 1), h, h);
			SetWindowRgn(hwndDlg, hRgn1, 1);
		}
		else {
			HRGN hRgn1;
			RECT r;
			int w = 10;
			GetWindowRect(hwndDlg, &r);
			int h = (r.right - r.left) > (w * 2) ? w : (r.right - r.left);
			int v = (r.bottom - r.top) > (w * 2) ? w : (r.bottom - r.top);
			h = (h < v) ? h : v;
			hRgn1 = CreateRectRgn(0, 0, (r.right - r.left + 1), (r.bottom - r.top + 1));
			SetWindowRgn(hwndDlg, hRgn1, 1);
		}
		// transparency

		#ifdef WS_EX_LAYERED 
			SetWindowLongPtr(hwndDlg, GWL_EXSTYLE, GetWindowLongPtr(hwndDlg, GWL_EXSTYLE) | WS_EX_LAYERED);
		#endif
		#ifdef LWA_ALPHA
			SetLayeredWindowAttributes(hwndDlg, RGB(0, 0, 0), (int)((100 - opt->aw_trans) / 100.0 * 255), LWA_ALPHA);
		#endif
		return TRUE;

	case WMU_SETALARM:
		{
			ALARM *data = (ALARM *)lParam;
			SetWindowText(hwndDlg, data->szTitle);
			SetWindowText(GetDlgItem(hwndDlg, IDC_TITLE), data->szTitle);

			SetDlgItemText(hwndDlg, IDC_ED_DESC, data->szDesc);
			wd->alarm = data;

			if (data->action & AAF_SOUND && options.loop_sound) {
				if (data->sound_num <= 3)
					SetTimer(hwndDlg, ID_TIMER_SOUND, SOUND_REPEAT_PERIOD, nullptr);
				else if (data->sound_num == 4)
					SetTimer(hwndDlg, ID_TIMER_SOUND, SPEACH_REPEAT_PERIOD, nullptr);
			}

			HWND hw = GetDlgItem(hwndDlg, IDC_SNOOZE);
			EnableWindow(hw, !(data->flags & ALF_NOSNOOZE));
			ShowWindow(hw, (data->flags & ALF_NOSNOOZE) ? SW_HIDE : SW_SHOWNA);
		}
		return TRUE;

	case WMU_FAKEALARM:
		SetWindowText(hwndDlg, TranslateT("Example alarm"));
		SetDlgItemText(hwndDlg, IDC_TITLE, TranslateT("Example alarm"));
		SetDlgItemText(hwndDlg, IDC_ED_DESC, TranslateT("Some example text. Example, example, example."));
		return TRUE;

	case WM_TIMER:
		if (wParam == ID_TIMER_SOUND && wd) {
			ALARM *data = wd->alarm;
			if (data && data->action & AAF_SOUND) {
				if (data->sound_num <= 3) {
					char buff[128];
					mir_snprintf(buff, "Triggered%d", data->sound_num);
					Skin_PlaySound(buff);
				}
				else if (data->sound_num == 4) {
					if (data->szTitle != nullptr && data->szTitle[0] != '\0') {
						if (ServiceExists("Speak/Say")) {
							CallService("Speak/Say", 0, (LPARAM)data->szTitle);
						}
					}
				}
			}
		}
		return TRUE;

	case WM_MOVE:
		Utils_SaveWindowPosition(hwndDlg, 0, MODULENAME, "Notify");
		break;

	case WMU_ADDSNOOZER:
		if (wd) {
			ALARM *data = wd->alarm;
			if (data) {
				// add snooze minutes to current time
				FILETIME ft;
				GetLocalTime(&data->time);
				SystemTimeToFileTime(&data->time, &ft);

				ULARGE_INTEGER uli;
				uli.LowPart = ft.dwLowDateTime;
				uli.HighPart = ft.dwHighDateTime;

				// there are 10000000 100-nanosecond blocks in a second...
				uli.QuadPart += mult.QuadPart * (int)(wParam);

				ft.dwHighDateTime = uli.HighPart;
				ft.dwLowDateTime = uli.LowPart;

				FileTimeToSystemTime(&ft, &data->time);

				data->occurrence = OC_ONCE;
				data->snoozer = true;
				data->flags = data->flags & ~ALF_NOSTARTUP;

				data->id = next_alarm_id++;

				append_to_list(data);
			}
		}
		return TRUE;

	case WM_COMMAND:
		if (HIWORD(wParam) == BN_CLICKED) {
			switch (LOWORD(wParam)) {
			case IDCANCEL:  // no button - esc pressed
			case IDOK:		// space?
			case IDC_SNOOZE:
				SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)options.snooze_minutes, 0);
				//drop through

			case IDC_DISMISS:
				KillTimer(hwndDlg, ID_TIMER_SOUND);
				if (wd) {
					if (wd->alarm) {
						free_alarm_data(wd->alarm);
						delete wd->alarm;
					}
					delete wd;
				}
				SetWindowLongPtr(hwndDlg, GWLP_USERDATA, 0);

				win_num--;
				WindowList_Remove(hAlarmWindowList, hwndDlg);
				DestroyWindow(hwndDlg);
				break;

			case IDC_SNOOZELIST:
				POINT pt, pt_rel;
				GetCursorPos(&pt);
				pt_rel = pt;
				ScreenToClient(hwndDlg, &pt_rel);

				HMENU hMenu = CreatePopupMenu();
				MENUITEMINFO mii = { 0 };
				mii.cbSize = sizeof(mii);
				mii.fMask = MIIM_ID | MIIM_STRING;

				#define AddItem(x) \
					mii.wID++; \
					mii.dwTypeData = TranslateW(x); \
					mii.cch = ( UINT )mir_wstrlen(mii.dwTypeData); \
					InsertMenuItem(hMenu, mii.wID, FALSE, &mii);

				AddItem(LPGENW("5 mins"));
				AddItem(LPGENW("15 mins"));
				AddItem(LPGENW("30 mins"));
				AddItem(LPGENW("1 hour"));
				AddItem(LPGENW("1 day"));
				AddItem(LPGENW("1 week"));

				TPMPARAMS tpmp = { 0 };
				tpmp.cbSize = sizeof(tpmp);
				LRESULT ret = (LRESULT)TrackPopupMenuEx(hMenu, TPM_RETURNCMD, pt.x, pt.y, hwndDlg, &tpmp);
				switch (ret) {
					case 0: DestroyMenu(hMenu); return 0; // dismis menu
					case 1: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)5, 0); break;
					case 2: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)15, 0); break;
					case 3: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)30, 0); break;
					case 4: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)60, 0); break;
					case 5: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)(60 * 24), 0); break;
					case 6: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)(60 * 24 * 7), 0); break;
				}

				DestroyMenu(hMenu);

				SendMessage(hwndDlg, WM_COMMAND, IDC_DISMISS, 0);
				break;
			}
		}
		return TRUE;

	case WM_MOUSEMOVE:
		if (wParam & MK_LBUTTON) {
			SetCapture(hwndDlg);

			POINT newp;
			newp.x = (short)LOWORD(lParam);
			newp.y = (short)HIWORD(lParam);
			ClientToScreen(hwndDlg, &newp);

			if (!wd->moving)
				wd->moving = true;
			else {
				RECT r;
				GetWindowRect(hwndDlg, &r);

				SetWindowPos(hwndDlg, nullptr, r.left + (newp.x - wd->p.x), r.top + (newp.y - wd->p.y), 0, 0, SWP_NOSIZE | SWP_NOZORDER);
			}
			wd->p.x = newp.x;
			wd->p.y = newp.y;
		}
		else {
			ReleaseCapture();
			wd->moving = false;
		}
		return TRUE;
	}

	return FALSE;
}
示例#26
0
int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst, LPSTR lpszArgs, int nWinMode)
{
	HWND hwnd;
	MSG msg;
	WNDCLASS wcl;
	HDC hdc;
	char buffer[] = "hello";

	wcl.hInstance = hThisInst;
	wcl.lpszClassName = WINDOW_CLASS_NAME;
	wcl.lpfnWndProc = WindowFunc;
	wcl.style = CS_HREDRAW | CS_VREDRAW;

	wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	//wcl.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
	wcl.hCursor = LoadCursor(NULL, IDC_ARROW);

	wcl.lpszMenuName = WINDOW_CLASS_NAME;
	wcl.cbClsExtra = 0;
	wcl.cbWndExtra = 0;	

	wcl.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
	

	if(!RegisterClass(&wcl)) return 0;

	if(!(hwnd = CreateWindowEx (
		WS_EX_TOPMOST,
		WINDOW_CLASS_NAME,
		"My First Proper Thing 2",
		WS_POPUP,
		0,
		0,
		GetSystemMetrics(SM_CXSCREEN),
		GetSystemMetrics(SM_CYSCREEN),
		NULL,
		NULL,
		hThisInst,
		NULL
		))) return 0;

	ShowWindow(hwnd, nWinMode);
	UpdateWindow(hwnd);
	SetFocus(hwnd);
	ShowCursor(0);
	main_window_handle = hwnd;

	LoadBitmap(&colour_bmp_file,"texture2.bmp");
	LoadBitmap(&height_bmp_file,"heightd2.bmp");
	
	if (!DD_Init(hwnd))
	{

		DestroyWindow(hwnd);
		return 0;
	}


	ofstream fout("myfile.dem");

	int i,j,n,index = 0;
	for ( i = 0; i < 512; i++) {

		for ( j = 0; j < 512; j++) {

//			heights[i][j] = height_bmp_file.buffer[index++] * 8;
//			fout << heights[i][j] << " ";
			heights[i][j] = 0;
		
		}	

	fout << "\n";
	}

	index = 0;
	for ( i = 0; i < 1024; i++) {

		for ( j = 0; j < 1024; j++) {

			if ((colours[i][j] = colour_bmp_file.buffer[index++])>250) colours[i][j] = 250;
		
		
		}	

	fout << "\n";
	}

	LoadDEM();

	fout.close();

	LoadDEM();

	while (1) 
	{
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			if(msg.message == WM_QUIT) { DD_Shutdown(); break; }
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		} 
		else 
		{	
			
			memset(&ddsd,0,sizeof(ddsd));
			ddsd.dwSize = sizeof(ddsd);


		



			
			while ( lpddsback->Lock(NULL,&ddsd,DDLOCK_SURFACEMEMORYPTR,NULL) != DD_OK);

				video_buffer = (UCHAR *) ddsd.lpSurface;

				memset(video_buffer,0,SCREEN_WIDTH*SCREEN_HEIGHT);


				GameMain();
			
				lpddsback->Unlock(NULL);
			
			

		sprintf(buffer,"%d",poo);
	

		if (lpddsback->GetDC(&hdc) == DD_OK) {
		 
			 SetBkColor(hdc, RGB(0, 0, 255));
			SetTextColor(hdc, RGB(255, 255, 0));
       
            TextOut(hdc, 0, 0, buffer, lstrlen(buffer));
           
		
        lpddsback->ReleaseDC(hdc);
		}

		
//Z+=10;
if (Z>3840.0) Z -=3840.0;

			while (TRUE)
               {
                   ddrval = lpddsprimary->Flip(NULL, 0);
                   if (ddrval == DD_OK)
					  
					   
                       break;
                   if (ddrval == DDERR_SURFACELOST)
                   {
                       ddrval = lpddsprimary->Restore();
                       if (ddrval != DD_OK)
                           break;
                   }
                   if (ddrval != DDERR_WASSTILLDRAWING)
                       break; 
			} 
			
            
			if (KEY_DOWN(VK_ESCAPE)) {
				
			DD_Shutdown();
			
				PostMessage(main_window_handle,WM_CLOSE,0,0);
			}
		} 
	}

	DD_Shutdown();

	return(msg.wParam);

}
示例#27
-1
LRESULT CALLBACK thread_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;
	RECT rc = {0};
	UINT notify_duration = 0;
	HFONT hOldFont = NULL;

	switch (message)
	{
	case WM_LIBNOTIFYSHOW:
		if(notification_data)
		{
			/* deduce the allowed text width from the max width; see geometry for rationale */
			rc.right = notification_window_width_max - (icon_size + (icon_padding * 3));
			
			hdc = GetDC(hWnd);
			if(hdc)
			{
				HFONT hOldFont = NULL;
				HRGN hRgn = NULL;

				hOldFont = (HFONT) SelectObject(hdc, font_body);
				if(hOldFont)
				{
					DrawText(hdc, notification_data->body, -1, &rc, DT_CALCRECT | DT_WORDBREAK | DT_EDITCONTROL | DT_NOCLIP | DT_NOPREFIX | DT_EXTERNALLEADING);
					SelectObject(hdc, hOldFont);
				}

				ReleaseDC(hWnd, hdc);
				if(!hOldFont) return 0;	/* exit if font selection failed */

				/* calculate the actual bounding rectangle from the DrawText output */
				notification_window_height = summary_body_divider + rc.bottom + (icon_padding * 3);
				notification_window_width = rc.right + icon_size + (icon_padding * 3);

				/* word count * milliseconds per word */
				notify_duration = word_count(notification_data->body) * milliseconds_per_word;

				/* in case the calculation renders too low a value, replace it with a de facto minimum */
				notify_duration = MAX(notify_duration, min_notification_timeout);

				/* get the screen area uncluttered by the taskbar */
				if(SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0))
				{
					LONG window_x = 0, window_y = 0;

					/* system tray @ right bottom */
					if((rc.bottom != GetSystemMetrics(SM_CYSCREEN)) || 
						(rc.right != GetSystemMetrics(SM_CXSCREEN)))
					{
						window_x = rc.right - (GetSystemMetrics(SM_CXSCREEN) / window_offset_factor) - notification_window_width;
						window_y = rc.bottom - (GetSystemMetrics(SM_CYSCREEN) / window_offset_factor) - notification_window_height;
					}
					else if(rc.left != 0)	/* left bottom */
					{
						window_x = rc.left + (GetSystemMetrics(SM_CXSCREEN) / window_offset_factor);
						window_y = rc.bottom - (GetSystemMetrics(SM_CYSCREEN) / window_offset_factor) - notification_window_height;
					}
					else					/* right top */
					{
						window_x = rc.right - (GetSystemMetrics(SM_CXSCREEN) / window_offset_factor) - notification_window_width;
						window_y = rc.top + (GetSystemMetrics(SM_CYSCREEN) / window_offset_factor);
					}

					/* resize and reposition the window */
					MoveWindow(hWnd, window_x, window_y, notification_window_width, notification_window_height, TRUE);

					/* set the new positions to be used by the mouse over hook */
					notification_window_rect.left = window_x;
					notification_window_rect.top = window_y;
					notification_window_rect.right = window_x + notification_window_width;
					notification_window_rect.bottom = window_y + notification_window_height;
					
					/* make it as a rounded rect. */
					hRgn = CreateRoundRectRgn(0, 0, notification_window_width, notification_window_height, rounded_rect_edge, rounded_rect_edge);
					SetWindowRgn(notification_window, hRgn, TRUE);

					/* since bRedraw is set to TRUE in SetWindowRgn invalidation isn't required */
					/*InvalidateRect(hWnd, NULL, TRUE);*/

					/* show the window and set the timers for animation and overall visibility */
					ShowWindow(hWnd, SW_SHOWNOACTIVATE);

					SetTimer(notification_window, TIMER_ANIMATION, fade_duration, NULL);
					SetTimer(notification_window, TIMER_NOTIFICATION, notify_duration, NULL);
				}
			}
		}
		break;
	case WM_LIBNOTIFYCLOSE:
		/* clean up and reset flags */
		{
			if(hook_mouse_over)
			{
				UnhookWindowsHookEx(hook_mouse_over);
				hook_mouse_over = NULL;
			}

			KillTimer(hWnd, TIMER_ANIMATION);
			KillTimer(hWnd, TIMER_NOTIFICATION);
			is_fading_out = FALSE;

			ShowWindow(hWnd, SW_HIDE);
		}
		break;
	case WM_PAINT:
		if(notification_data && notification_data->summary && 
			notification_data->body && notification_data->icon)
		{
			hdc = BeginPaint(hWnd, &ps);

			SetTextColor(hdc, RGB(255, 255, 255));
			SetBkMode(hdc, TRANSPARENT);

			hOldFont = (HFONT) SelectObject(hdc, font_summary);

			if(hOldFont)
			{
				/* set the padding as left offset and center the icon horizontally */
				DrawIcon(hdc, icon_padding, (notification_window_height / 2) - (icon_size / 2), notification_data->icon);

				/* calculate and DrawText for both summary and body based on the geometry given above */
				rc.left = icon_size + (icon_padding * 2);
				rc.right = notification_window_width - icon_padding;
				rc.top = icon_padding;
				rc.bottom = summary_body_divider + (icon_padding * 2);

				DrawText(hdc, notification_data->summary, -1, &rc, DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX);

				if(SelectObject(hdc, font_body))
				{
					rc.top = rc.bottom;
					rc.bottom = notification_window_height - icon_padding;

					DrawText(hdc, notification_data->body, -1, &rc, DT_WORDBREAK | DT_EDITCONTROL | DT_NOCLIP | DT_NOPREFIX | DT_EXTERNALLEADING);
				}

				SelectObject(hdc, hOldFont);
			}

			EndPaint(hWnd, &ps);
		}
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_TIMER:
		if(IsWindowVisible(hWnd))
		{
			if(wParam == TIMER_ANIMATION)	/* notification animation timer */
			{
				if(is_fading_out)
				{
					if(notification_window_alpha > 5)
					{
						notification_window_alpha -= 25;
						SetLayeredWindowAttributes(notification_window, 0, notification_window_alpha, LWA_ALPHA);
					}
					else
					{
						/* once fully faded out, self destroy and reset the flags */
						KillTimer(hWnd, TIMER_ANIMATION);
						is_fading_out = FALSE;
						notification_window_alpha = 0;
						PostMessage(hWnd, WM_LIBNOTIFYCLOSE, 0, 0);
					}
				}
				else
				{
					if(notification_window_alpha < 250)
					{
						notification_window_alpha += 25;
						SetLayeredWindowAttributes(notification_window, 0, notification_window_alpha, LWA_ALPHA);
					}
					else
					{
						/* self destory as alpha reaches the maximum */
						KillTimer(hWnd, TIMER_ANIMATION);
						notification_window_alpha = 255;

						/* set the mouse over hook once the window is fully visible */
						hook_mouse_over = SetWindowsHookEx(WH_MOUSE_LL, mouse_over_hook_proc, (HINSTANCE) GetModuleHandle(NULL), 0);
					}
				}
			}
			else	/* notification duration timer */
			{
				/* self destruct once timed out */
				KillTimer(hWnd, TIMER_NOTIFICATION);

				/* kill the hook set by animation timer */
				if(hook_mouse_over)
				{
					UnhookWindowsHookEx(hook_mouse_over);
					hook_mouse_over = NULL;
				}

				/* start fading out sequence */
				is_fading_out = TRUE;
				SetTimer(hWnd, 1, fade_duration, NULL);
			}
		}
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}

	return 0;
}
示例#28
-1
文件: monslctl.c 项目: GYGit/reactos
static VOID
MonSelPaintMonitor(IN OUT PMONITORSELWND infoPtr,
                   IN HDC hDC,
                   IN DWORD Index,
                   IN OUT PRECT prc,
                   IN COLORREF crDefFontColor,
                   IN BOOL bHideNumber)
{
    HFONT hFont, hPrevFont;
    COLORREF crPrevText;

    if ((INT)Index == infoPtr->SelectedMonitor)
    {
        FillRect(hDC,
                 prc,
                 (HBRUSH)(COLOR_HIGHLIGHT + 1));

        if (infoPtr->HasFocus && !(infoPtr->UIState & UISF_HIDEFOCUS))
        {
            /* NOTE: We need to switch the text color to the default, because
                     DrawFocusRect draws a solid line if the text is white! */

            crPrevText = SetTextColor(hDC,
                                      crDefFontColor);

            DrawFocusRect(hDC,
                          prc);

            SetTextColor(hDC,
                         crPrevText);
        }
    }

    InflateRect(prc,
                -infoPtr->SelectionFrame.cx,
                -infoPtr->SelectionFrame.cy);

    Rectangle(hDC,
              prc->left,
              prc->top,
              prc->right,
              prc->bottom);

    InflateRect(prc,
                -1,
                -1);

    if (!bHideNumber)
    {
        hFont = MonSelGetMonitorFont(infoPtr,
                                     hDC,
                                     Index);
        if (hFont != NULL)
        {
            hPrevFont = SelectObject(hDC,
                                     hFont);

            DrawText(hDC,
                     infoPtr->Monitors[Index].szCaption,
                     -1,
                     prc,
                     DT_VCENTER | DT_CENTER | DT_NOPREFIX | DT_SINGLELINE);

            SelectObject(hDC,
                         hPrevFont);
        }
    }

    if (infoPtr->MonitorInfo[Index].Flags & MSL_MIF_DISABLED)
    {
        InflateRect(prc,
                    1,
                    1);

        MonSelDrawDisabledRect(infoPtr,
                               hDC,
                               prc);
    }
}
示例#29
-1
文件: mhmenu.c 项目: yzh/yzhack
LRESULT onDrawItem(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    LPDRAWITEMSTRUCT lpdis; 
	PNHMenuItem item;
	PNHMenuWindow data;
    TEXTMETRIC tm;
	HGDIOBJ saveFont;
	HDC tileDC;
	short ntile;
	int t_x, t_y;
	int x, y;
	TCHAR wbuf[BUFSZ];
	RECT drawRect;
	COLORREF OldBg, OldFg, NewBg;
	char *p, *p1;
	int column;

	lpdis = (LPDRAWITEMSTRUCT) lParam; 

    /* If there are no list box items, skip this message. */
    if (lpdis->itemID == -1) return FALSE;

	data = (PNHMenuWindow)GetWindowLong(hWnd, GWL_USERDATA);

    item = &data->menu.items[lpdis->itemID];

	tileDC = CreateCompatibleDC(lpdis->hDC);
	saveFont = SelectObject(lpdis->hDC, mswin_get_font(NHW_MENU, item->attr, lpdis->hDC, FALSE));
	NewBg = mswin_get_color(NHW_MENU, MSWIN_COLOR_BG);
	OldBg = SetBkColor(lpdis->hDC, NewBg);
	OldFg = SetTextColor(lpdis->hDC, mswin_get_color(NHW_MENU, MSWIN_COLOR_FG)); 

    GetTextMetrics(lpdis->hDC, &tm);

	x = lpdis->rcItem.left + 1;

	/* print check mark if it is a "selectable" menu */
	if( data->how!=PICK_NONE ) {
		if( NHMENU_IS_SELECTABLE(*item) ) {
			HGDIOBJ saveBrush;
			HBRUSH	hbrCheckMark;
			char buf[2];

			switch(item->count) {
			case -1: hbrCheckMark = CreatePatternBrush(data->bmpChecked); break;
			case 0: hbrCheckMark = CreatePatternBrush(data->bmpNotChecked); break;
			default: hbrCheckMark = CreatePatternBrush(data->bmpCheckedCount); break;
			}

			y = (lpdis->rcItem.bottom + lpdis->rcItem.top - TILE_Y) / 2; 
			SetBrushOrgEx(lpdis->hDC, x, y, NULL);
			saveBrush = SelectObject(lpdis->hDC, hbrCheckMark);
			PatBlt(lpdis->hDC, x, y, TILE_X, TILE_Y, PATCOPY);
			SelectObject(lpdis->hDC, saveBrush);
			DeleteObject(hbrCheckMark);

			x += TILE_X + 5;

			if(item->accelerator!=0) {
				buf[0] = item->accelerator;
				buf[1] = '\x0';

				SetRect( &drawRect, x, lpdis->rcItem.top, lpdis->rcItem.right, lpdis->rcItem.bottom );
/*JP
				DrawText(lpdis->hDC, NH_A2W(buf, wbuf, 2), 1, &drawRect, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);
*/
				DrawText(lpdis->hDC, NH_A2W(buf, wbuf, 2), -1, &drawRect, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);
			}
			x += tm.tmAveCharWidth + tm.tmOverhang + 5;
		} else {
			x += TILE_X + tm.tmAveCharWidth + tm.tmOverhang + 10;
		}
	}

	/* print glyph if present */
	if( item->glyph != NO_GLYPH ) {
		HGDIOBJ saveBmp;

		saveBmp = SelectObject(tileDC, GetNHApp()->bmpTiles);				
		ntile = glyph2tile[ item->glyph ];
		t_x = (ntile % TILES_PER_LINE)*TILE_X;
		t_y = (ntile / TILES_PER_LINE)*TILE_Y;

		y = (lpdis->rcItem.bottom + lpdis->rcItem.top - TILE_Y) / 2; 

		nhapply_image_transparent(
			lpdis->hDC, x, y, TILE_X, TILE_Y, 
			tileDC, t_x, t_y, TILE_X, TILE_Y, TILE_BK_COLOR );
		SelectObject(tileDC, saveBmp);
	}

	x += TILE_X + 5;

	/* draw item text */
	if( item->has_tab ) {
		p1 = item->str;
		p = strchr(item->str, '\t');
		column = 0;
		SetRect( &drawRect, x, lpdis->rcItem.top, min(x + data->menu.tab_stop_size[0], lpdis->rcItem.right),
			lpdis->rcItem.bottom );
		for (;;) {
			TCHAR wbuf[BUFSZ];
			if (p != NULL) *p = '\0'; /* for time being, view tab field as zstring */
			DrawText(lpdis->hDC,
				NH_A2W(p1, wbuf, BUFSZ),
/*JP
				strlen(p1),
*/
				-1,
				&drawRect,
				DT_LEFT | DT_VCENTER | DT_SINGLELINE
			);
			if (p != NULL) *p = '\t';
			else /* last string so, */ break;

			p1 = p + 1;
			p = strchr(p1, '\t');
			drawRect.left = drawRect.right + TAB_SEPARATION;
			++column;
			drawRect.right = min (drawRect.left + data->menu.tab_stop_size[column], lpdis->rcItem.right);
		}
	} else {
		TCHAR wbuf[BUFSZ];
		SetRect( &drawRect, x, lpdis->rcItem.top, lpdis->rcItem.right, lpdis->rcItem.bottom);
		DrawText(lpdis->hDC,
			NH_A2W(item->str, wbuf, BUFSZ),
/*JP
			strlen(item->str),
*/
			-1,
			&drawRect,
			DT_LEFT | DT_VCENTER | DT_SINGLELINE
		);
	}

	/* draw focused item */
	if( item->has_focus ) {
		RECT client_rt;
		HBRUSH bkBrush;

		GetClientRect(lpdis->hwndItem, &client_rt);
		if( NHMENU_IS_SELECTABLE(*item) && 
			data->menu.items[lpdis->itemID].count>0 &&
			item->glyph != NO_GLYPH ) {
			if( data->menu.items[lpdis->itemID].count==-1 ) {
				_stprintf(wbuf, TEXT("Count: All") );
			} else {
				_stprintf(wbuf, TEXT("Count: %d"), data->menu.items[lpdis->itemID].count );
			}

			SelectObject(lpdis->hDC, mswin_get_font(NHW_MENU, ATR_BLINK, lpdis->hDC, FALSE));

			/* calculate text rectangle */
			SetRect( &drawRect, client_rt.left, lpdis->rcItem.top, client_rt.right, lpdis->rcItem.bottom );
/*JP
			DrawText(lpdis->hDC, wbuf, _tcslen(wbuf), &drawRect, 
*/
			DrawText(lpdis->hDC, wbuf, -1, &drawRect, 
					 DT_CALCRECT | DT_RIGHT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX );
			
			/* erase text rectangle */
			drawRect.left = max(client_rt.left+1, client_rt.right - (drawRect.right - drawRect.left) - 10);
			drawRect.right = client_rt.right-1;
			drawRect.top = lpdis->rcItem.top;
			drawRect.bottom = lpdis->rcItem.bottom;
			bkBrush = CreateSolidBrush( GetBkColor(lpdis->hDC) );
			FillRect(lpdis->hDC, &drawRect, bkBrush );
			DeleteObject( bkBrush );

			/* draw text */
/*JP
			DrawText(lpdis->hDC, wbuf, _tcslen(wbuf), &drawRect, 
*/
			DrawText(lpdis->hDC, wbuf, -1, &drawRect, 
					 DT_RIGHT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX );
		}

		/* draw focus rect */
		SetRect( &drawRect, client_rt.left, lpdis->rcItem.top, client_rt.right, lpdis->rcItem.bottom );
		DrawFocusRect(lpdis->hDC, &drawRect);
	}

	SetTextColor (lpdis->hDC, OldFg);
	SetBkColor (lpdis->hDC, OldBg);
	SelectObject(lpdis->hDC, saveFont);
	DeleteDC(tileDC);
	return TRUE;
}
示例#30
-1
文件: app.c 项目: RorschachUK/Trakr
bool Run()
{
  	//Main loop - get keypresses and interpret them
  	keystate=GetRemoteKeys();
  	if(keystate != oldKeystate) {
	  	oldKeystate = keystate;

	  	if(keystate & KEY_HOME) {
		  	return false;
	  	}
		if (mode == 1 || mode == 2) { //menu navigation is only relevant to menu modes
			if(keystate & KEY_LEFT_BACK) {
				//Menu down
				if (menuItem<MAXMENU) {
					menuItem++;
					if(menuItem==3 || menuItem==4) {
						menuNum=6;
					} else if (menuItem == 5) {
						menuNum=3;
					} else {
						menuNum=1;
					}
				}
			}

			if(keystate & KEY_LEFT_FORWARD) {
				//Menu up
				if (menuItem>1) {
					menuItem--;
					if(menuItem==3 || menuItem==4) {
						menuNum=6;
					} else if (menuItem == 5) {
						menuNum=3;
					} else {
						menuNum=1;
					}
				}
			}
		}
		if (mode == 1) {
			if(keystate & KEY_RIGHT_FORWARD) {
				//Menu down
				if (menuNum<24) {
					menuNum++;
				}
			}

			if(keystate & KEY_RIGHT_BACK) {
				//Menu up
				if (menuNum>1) {
					menuNum--;
				}
			}

			if(keystate & KEY_INPUT1) {
				//Clear
				PlaySound(SOUND_FIRE);
				steps=0;
				menuItem=1;
				menuNum=1;
				mode=1;
				OpenMotors();
			}

			if(keystate & KEY_INPUT2) {
				//Menu select
				if(steps+1<MAXSTEPS) {
					steps++;
					moveList[steps].cmd=menuItem;
					moveList[steps].num=menuNum;
					PlaySound(SOUND_BEEP);
				}
			}
			if(keystate & KEY_MENU) {
				//Switch to second menu
				mode=2;
				menuItem=1;
				menuNum=1;
				PlaySound(SOUND_BEEP);
			}
		} else if (mode == 2) {
			if(keystate & KEY_INPUT1) {
				//Switch back to first menu
				mode=1;
				menuItem=1;
				menuNum=1;
				PlaySound(SOUND_BEEP);
			}
			if (keystate & KEY_INPUT2) {
				//Menu select
				switch(menuItem) {
					case 1: { //Free Roam
						mode=4;
						PlaySound(SOUND_BEEP);
						CloseMotors();
					} break;
					case 2: { //Load route
						LoadRoute();
						ClearScreen();
						PlaySound(SOUND_BEEP);
						SetTextColor(white);
						DrawText(5, 65, "Loading...");
						Show();
						Sleep(500); //Just so they notice...
						mode=2;
					} break;
					case 3: { //Save route
						PlaySound(SOUND_BEEP);
						SaveRoute();
						ClearScreen();
						SetTextColor(white);
						DrawText(5, 65, "Saving...");
						Show();
						Sleep(500); //Just so they notice...
						mode=2;
					} break;
					case 4: { //Recalibrate
						PlaySound(SOUND_BEEP);
						mode=3;		//Recalibration mode
						menuNum=1;	//Use menuNum as steps throught the process - 1=ready, 2=working
					} break;
					case 5: { //About
						PlaySound(SOUND_GO);
						mode=5;
						CloseMotors();
					} break;
				}
			}

			if(keystate & KEY_MENU) {
				//Switch back to first menu
				mode=1;
				menuItem=1;
				menuNum=1;
				PlaySound(SOUND_BEEP);
			}
		} else if (mode==3) {
			//Recalibrate.
			if(keystate & KEY_INPUT1) {
				//Cancel
				PlaySound(SOUND_BEEP);
				SetMotors(0,0);
				mode=2;
				menuItem=4;
				menuNum=1;
			}
			if (keystate & KEY_INPUT2) {
				//Start/Stop
				PlaySound(SOUND_BEEP);
				switch (menuNum) {
					case 1: { //Start
						menuNum=2;
						ResetTimer();
						SetMotors(10000,-10000);
					}
					break;
					case 2: { //Stop
						rotateSleep = ReadTimer() / 24;
						SetMotors(0,0);
						mode=2;
						menuItem=4;
						menuNum=1;
						SaveCalibration();
					}
				}
			}
		} else if (mode==4 || mode==5) {
			if(keystate & KEY_MENU) {
				//Switch back to first menu
				PlaySound(SOUND_BEEP);
				mode=2;
				menuItem=1;
				menuNum=1;
				OpenMotors();
			}
			if (keystate & KEY_INPUT1) {
				IRState = !IRState;
				SetIR(IRState);
			}

			if (keystate & KEY_INPUT2) {
				PlaySound(SOUND_BEEP);
				mode=2;
				menuItem=1;
				menuNum=1;
				OpenMotors();
			}
		}

	  	if(keystate & KEY_RUN) {
		  	//Go
		  	ClearScreen();
		  	Show();
		  	PlaySound(SOUND_GO);

		  	//Cycle through steps and execute
		  	int count;
		  	SetTextColor(green);
		  	for(count=1; count<=steps;count++) {
				switch(moveList[count].cmd) {
				  	case 1: { //Forward
						ClearScreen();
						DrawText(5, 100, "%d: Forward %d",count, moveList[count].num);
						Show();
						SetMotors(10000,10000);
						Sleep(FORWARDSLEEP * moveList[count].num);
						SetMotors(0,0);
					}
					break;
				  	case 2: { //Back
						ClearScreen();
						DrawText(5, 100, "%d: Back %d",count, moveList[count].num);
						Show();
						SetMotors(-10000,-10000);
						Sleep(FORWARDSLEEP * moveList[count].num);
						SetMotors(0,0);
					}
					break;
				  	case 3: { //Right
						ClearScreen();
						DrawText(5, 100, "%d: Right %d",count, moveList[count].num * 15);
						Show();
						SetMotors(10000,-10000);
						Sleep(rotateSleep * moveList[count].num);
						SetMotors(0,0);
					}
					break;
				  	case 4: { //Left
						ClearScreen();
						DrawText(5, 100, "%d: Left %d",count, moveList[count].num * 15);
						Show();
						SetMotors(-10000,10000);
						Sleep(rotateSleep * moveList[count].num);
						SetMotors(0,0);
					}
					break;
					case 5: { //Fire
						ClearScreen();
						SetTextColor(red);
						DrawText(10, 45, "PEW! PEW! PEW!");
						SetTextColor(green);
						DrawText(5, 100, "%d: Fire %d",count, moveList[count].num);
						Show();
						int fireCount;
						for(fireCount=0; fireCount<moveList[count].num; fireCount++) {
							PlaySound(SOUND_FIRE);
						}
					}
				}
			}
			//reset menu pointer
			menuItem=1;
			menuNum=1;
			PlaySound(SOUND_GO);
	  	}

	  	DrawMenu();
  	}
  	Sleep(50); //to stop the radio being on full time
  	return true;
}