2009-12-23 11 views
16

quiero ser capaz de escribir código como este:¿Cómo obtengo la posición de un control en relación con el cliente de la ventana?

HWND hwnd = <the hwnd of a button in a window>; 
int positionX; 
int positionY; 
GetWindowPos(hwnd, &positionX, &positionY); 
SetWindowPos(hwnd, 0, positionX, positionY, 0, 0, SWP_NOZORDER | SWP_NOSIZE); 

Y tener que hacer nada. Sin embargo, no puedo encontrar la manera de escribir una función GetWindowPos() que me da las respuestas en las unidades correctas:

void GetWindowPos(HWND hWnd, int *x, int *y) 
{ 
    HWND hWndParent = GetParent(hWnd); 

    RECT parentScreenRect; 
    RECT itemScreenRect; 
    GetWindowRect(hWndParent, &parentScreenRect); 
    GetWindowRect(hWnd, &itemScreenRect); 

    (*x) = itemScreenRect.left - parentScreenRect.left; 
    (*y) = itemScreenRect.top - parentScreenRect.top; 
} 

Si utilizo esta función, consigo coordenadas que están en relación con la parte superior izquierda de la matriz ventana, pero SetWindowPos() quiere coordenadas relativas al área debajo de la barra de título (estoy suponiendo que este es el "área de cliente", pero la terminología de win32 es un poco nueva para mí).

Solución Este es el trabajo GetWindowPos() función (gracias Sergio):

void GetWindowPos(HWND hWnd, int *x, int *y) 
{ 
    HWND hWndParent = GetParent(hWnd); 
    POINT p = {0}; 

    MapWindowPoints(hWnd, hWndParent, &p, 1); 

    (*x) = p.x; 
    (*y) = p.y; 
} 
+0

Es una aplicación de ventana –

+0

¿Cómo funciona? ¿Para qué sirve DirectX? Novato en directx. Hice mi propia función para hacer esto –

+0

Sí, es una aplicación de Windows, de ahí el uso de win32 api. – Andy

Respuesta

17

Intente utilizar GetClientRect de obtener coordenadas y MapWindowPoints para transformarlo.

1

creo que u quieren algo por el estilo. No sé para encontrar los controles. Este segmento de código alinea la posición de una etiqueta en el centro de la forma de la ventana según el tamaño de la forma.

AllignLabelToCenter(lblCompanyName, frmObj) 


Public Sub AllignLabelToCenter(ByRef lbl As Label, ByVal objFrm As Form) 
     Dim CenterOfForm As Short = GetCenter(objFrm.Size.Width) 
     Dim CenterOfLabel As Short = GetCenter(lbl.Size.Width) 
     lbl.Location = New System.Drawing.Point(CenterOfForm - CenterOfLabel, lbl.Location.Y) 
    End Sub 
    Private ReadOnly Property GetCenter(ByVal obj As Short) 
     Get 
      Return obj/2 
     End Get 
    End Property 
+0

Eso no es realmente útil ya que no hay un equivalente a la propiedad ".Location" que está utilizando en el win32 (o al menos, ninguno que he encontrado). – Andy

+0

Nunca utilicé win32. En caso de que encuentre una solución, por favor hágamelo saber también –

Cuestiones relacionadas