El viejo nuevo Win32api
Esta página proporciona una lista de enlaces al subconjunto de publicaciones del famoso blog de Raymond Chen, The Old New Thing . El subconjunto está limitado principalmente a Win32API y algunas cosas relacionadas con la Com.
La razón por la que mantengo esta página es que a menudo proporciona información que falta en MSDN o que se describe allí de manera críptica, y también porque el blog no se puede buscar fácilmente.
Los enlaces aquí se clasifican por su tema en lugar de un orden cronológico. A veces, cuando es apropiado, se puede poner una sola publicación en múltiples categorías.
En algunos casos (bastante raros), los enlaces a otras fuentes se incluyen si se encuentran útiles.
Descargo de responsabilidad: no reclamo la autoría de ningún contenido vinculado. Esto se trata solo de la organización útil de los grandes artículos que Raymond ha escrito a lo largo de los años.
Tabla de contenido
- Procesos e hilos
- Procesos
- Trapos
- Piscinas de hilos
- Afinidad de hilo de los objetos
- Pila
- Fibras
- Sincronización
-
WaitOnAddress()
-
WaitForMultipleObjects()
y parientes - Patrones sin bloqueo
- Dlls
- Recursos
- Recursos de mapa de bits e icono
- Plantillas de diálogo
- Plantillas de menú y recursos del acelerador
- Recursos de cadena
- Plantillas de versión
- Datos y recursos personalizados
- Aplicación (en su conjunto)
- Línea de comando
- Barra de tareas
-
HWND
(punto de vista general)- Jerarquía de Windows
- Estilos de ventana
- Clases de ventana
- Ventanas de nivel superior
- Marco y subtítulo de la ventana
- DWM
- Diálogo
- Diálogos anidados e incrustados
- Diálogo comunes
- Navegación de control
- Administrador de diálogo
- Modalidad
- Hojas de propiedad
- Control
- Controles de animación
- Botones
- Cajas combinadas
- Editar controles
- Vistas de listas
- Controles de texto ricos
- Barras de desplazamiento
- Controles estáticos
- Barras de herramientas
- Servicio de herramientas
- Barras de pista
- Vistas de la lista de árboles
- Procesamiento de mensajes
- Mensajes específicos
- Notificaciones
- Construcción y destrucción de ventanas
- Mensajes de geometría de la ventana
- Mensajes de pintura de ventanas
- Mensajes de enfoque de ventana
- Mensajes de teclado
- Mensajes de ratón
- Mensajes de diálogo
- Otros mensajes de ventana
- Mensajes del sistema
- GDI
- Cursores
- Pincel
- Plumas
- Mapas de bits
- Dib
-
LockWindowUpdate()
- Pintura de elementos estándar
-
UXTHEME.DLL
- Monitores múltiples
- Accesibilidad
- Comunicarse
- Declarando interfaces com
- COM Apartamentos
- Inicialización
- Tienda de comástica
- Com marshalización
- COM Manejo de errores
- Com interfaces asíncronas
- Guía
- CON CIBLAS COM
- Variantes com
-
IUnknown
-
IMoniker
-
ICallback
-
IContextMenu
-
IFileDialog
-
IMultiLanguage
-
INamespaceWalk
-
IStream
-
IVirtualDesktopManager
- Portapapeles
- Arrastrar y soltar
- Enumeración
- Caparazón
- Cosas no categorizadas
- Memoria
- Entrada y salida
- Entrada y salida asíncrona
- Archivos y directorios
- LCA
- Permisos de seguridad, atributos e identificadores
- Registro
- Hilos y locales
- Servicios NT
- Sin categoría
Procesos e hilos
Procesos
-
CreateProcess
no espera a que comience el proceso - ¿Por qué la función
CreateProcess
modifica su línea de comando de entrada? - ¿Por qué la gente se está cerrando las llamadas
CreateProcess
? - Deshabilitar el cuadro de diálogo de bloqueo del programa
- ¿Cómo paso muchos datos a un proceso cuando se inicia?
- ¿Cuál fue el propósito del parámetro
hPrevInstance
para WinMain
? - ¿Es
RunAsInvoker
una configuración secreta de UAC, incluso más alta? - ¿Cómo evito que un proceso infantil muestre el diálogo de informes de errores de Windows?
- ¿Cómo es que
WriteProcessMemory
logra por escrito a la memoria de solo lectura? - ¿Es una buena idea dejar que
WriteProcessMemory
administre la protección de la página para mí? - ¿Cómo puedo lanzar un proceso no elegido desde mi proceso elevado, Redux?
- ¿Cómo puedo verificar el nivel de integridad de mi proceso?
- ¿Es cierto que aumentar una excepción estructurada de un controlador de excepción estructurado termina el proceso?
- Una forma más directa y sin errores de crear un proceso en un objeto de trabajo
Trapos
- ID de hilo y proceso no válidos
- ¿Por qué mi mango de hilo de repente va mal? ¡Todo lo que hice fue esperarlo!
- ¿Qué sucede si simplemente regresa de la devolución de llamada del hilo pasada a
_beginthread
y _beginthreadex
? - Por qué nunca debes suspender un hilo
- Los peligros de dormir en un hilo de la interfaz de usuario
- En busca de la cola de mensajes
- Enumerando hilos en un proceso
- El trabajo de interfaz de usuario de Win32 es inherentemente uniforme
- ¿Qué tan malo es retrasar el cierre de un mango de hilo durante mucho tiempo después de que el hilo haya salido?
- Si llamo
GetExitCodeThread
para un hilo que sé con certeza, ¿por qué todavía dice STILL_ACTIVE
? - ¿Hay algún problema con
CreateRemoteThread
en sistemas de 64 bits? - ¿Es la función
TerminateThread
sincrónica? - Eliminar la
TerminateThread
del código que espera a que un objeto de trabajo se vacíe - ¿Cuál es el punto de
FreeLibraryAndExitThread
? - ¿Qué sucede si doy valores contradictorios para la reserva de pila y reserva de pila?
Piscinas de hilos
- ¿Qué significa exactamente el parámetro
msWindowLength
para SetThreadpoolTimer
? - ¿Cuál es la diferencia entre
CreateTimerQueueTimer
y SetThreadpoolTimer
? - Cómo evitar acceder a la memoria liberada al cancelar una devolución de llamada de la piscina de subprocesos
- Evitar los estlocks al cancelar una devolución de llamada de la piscina de subprocesos, Parte 1: Datos de devolución de llamada externas
- Evitar los estlocks al cancelar una devolución de llamada de la piscina de subprocesos, Parte 2: Refiriéndose al objeto que contiene
- Gotcha: un temporizador periódico de Threadpool no esperará a que complete el tic anterior
- ¿Por qué obtengo una excepción del grupo de subprocesos durante el cierre del proceso?
- ¿Qué sucede con el valor devuelto de la función pasada a
QueueUserWorkItem
? - El modelo mental para
StartThreadpoolIo
- ¿Cómo puedo detectar que un elemento de trabajo de la piscina de hilos está tomando demasiado tiempo?
- ¿Cómo puedo cerrar un grupo de hilos y cancelar todo el trabajo que se haya colocado en cola?
Afinidad de hilo de los objetos
- Afinidad de hilo de los objetos de la interfaz de usuario, Parte 1: Manijas de la ventana
- Afinidad de hilo de los objetos de la interfaz de usuario, Parte 2: Contextos del dispositivo
- Afinidad de hilo de los objetos de la interfaz de usuario, Parte 3: menús, iconos, cursores y tablas de acelerador
- Afinidad de hilo de los objetos de la interfaz de usuario, Parte 4: Objetos GDI y otras notas sobre Affinity
- Afinidad de hilo de los objetos de la interfaz de usuario, Parte 5: Limpieza de objetos
- Afinidad de hilo de los objetos de la interfaz de usuario: Anexo
Pila
- ¿Cómo puedo expandir la pila de mi hilo en tiempo de ejecución?
- Usando fibras para expandir la pila de un hilo en tiempo de ejecución, parte 1
- Usando fibras para expandir la pila de un hilo en tiempo de ejecución, parte 2
- Usando fibras para expandir la pila de un hilo en tiempo de ejecución, parte 3
- Usando fibras para expandir la pila de un hilo en tiempo de ejecución, parte 4
- Usando fibras para expandir la pila de un hilo en tiempo de ejecución, Parte 5
- Usando fibras para expandir la pila de un hilo en tiempo de ejecución, parte 6
- Comparación de fibras con hilos con el fin de expandir la pila de un hilo en tiempo de ejecución
- Determinar aproximadamente cuánto espacio de pila está disponible, Parte 1
- Determinar aproximadamente cuánto espacio de pila está disponible, Parte 2
Fibras
- ¿Qué sucede con las fibras que se ejecutaban en un hilo cuando sale el hilo?
- Está bien usar fibras, pero todos tienen que estar a bordo del plan.
- Las fibras ya no son útiles para mucho; Solo hay un rincón que sigue siendo útil por una razón no relacionada con las fibras
Sincronización
- Comprender las consecuencias de
WAIT_ABANDONED
- Eventos con llave de Windows, secciones críticas y nuevas funciones de sincronización de Vista
- Combinando la cola de trabajo de eventos distintos, el orden no es importante, con un evento de reinicio automático
- ¿Qué tan justos son las cerraduras de SRW, particularmente cuando hay lectores y escritores?
- También puede usar un archivo como objeto de sincronización
- ¿Puedo esperar a que un evento de núcleo no se firme ?
- Si el Slim Reader/Writer Lock (
SRWLOCK
) no recuerda quién es el propietario de la cerradura compartida, ¿eso significa que está bien adquirirlo de manera recursiva?
WaitOnAddress()
-
WaitOnAddress
le permite crear un objeto de sincronización a partir de cualquier variable de datos, incluso un byte - Implementación de una barrera de sincronización en términos de
WaitOnAddress
- Implementación de una sección crítica en términos de
WaitOnAddress
- Extender nuestra sección crítica basada en
WaitOnAddress
para admitir tiempos de espera - Comparación de
WaitOnAddress
con futexes (¿futexi? Futexen?) - Creando un semáforo de
WaitOnAddress
- Creación de un semáforo con un recuento máximo de
WaitOnAddress
- Creación de un evento de reinicio manual de
WaitOnAddress
- Creación de un evento de reinicio automático de
WaitOnAddress
WaitForMultipleObjects()
y parientes
-
MsgWaitForMultipleObjects
y el estado de la cola - Puede llamar
MsgWaitForMultipleObjects
con manijas cero - Bombear mensajes mientras espera un período de tiempo
- Esperar todas las manijas con
MsgWaitForMultipleObjects
es un error que espera que suceda - ¿Por qué
WaitForMultipleObjects
return ERROR_INVALID_PARAMETER
cuando todos los parámetros me parecen válidos? - Si más de un objeto hace que regresen un
WaitForMultipleObjects
, ¿cómo me entero de los otros? - ¿Cuál es el punto de transmitir un evento nunca firmado a
MsgWaitForMultipleObjects
?
Patrones sin bloqueo
- Bloquear patrones gratuitos de muchos productores/un solo consumidor: una cola de trabajo con tareas fusionscing
- Bloquear patrones de muchos productores/solo consumidores: una cola de trabajo donde gana la última
- Bloquear patrones de muchos productores/consumidores sin bloqueo: una cola de trabajo de eventos idénticos no coalcatables
- Bloquear patrones de muchos productores/solo consumidores: una cola de trabajo de eventos distintos, ordenar no es importante
- Bloquear patrones de muchos productores/solo consumidores: una cola de trabajo de eventos distintos, FIFO
- Bloquear patrones de muchos productores/solo consumidores: una cola de trabajo de eventos distintos, orden no importante, pregunta de seguimiento
Dlls
- No confíe en la dirección de devolución
- ¿Por qué no puedo
GetProcAddress
una función que DLExport'ed? - ¿Cuál es la diferencia entre
HINSTANCE
y HMODULE
? - Acceder a la
HINSTANCE
del módulo actual desde una biblioteca estática -
LoadLibraryEx(DONT_RESOLVE_DLL_REFERENCES)
es fundamentalmente defectuoso - ¿Por qué los DLL están descargados en el orden "incorrecto"?
- ¿Cómo se exportan las funciones de DLL en ventanas de 32 bits?
- Funciones exportadas que son realmente reenviadores
- Repensar la forma en que las exportaciones de DLL se resuelven para ventanas de 32 bits
- Los nombres en la biblioteca de importación están decorados por una razón
- ¿Qué sucede cuando te equivocas Dllimport?
- Problemas relacionados con forzar un trozo que se creará para una función importada
- Asignar y liberar memoria a través de los límites del módulo
- El reenvío de DLL no es lo mismo que la carga de retraso
- ¿Qué es la importación de DLL que sugiere?
- ¿Qué es el enlace de importación de DLL?
- ¿Cuál es el punto de
FreeLibraryAndExitThread
? - Una biblioteca cargada a través de
LOAD_LIBRARY_AS_DATAFILE
(o banderas similares) no puede jugar en ningún juego de módulos de reno - ¿Podría haber algún problema para llamar
GetModuleFileNameEx
en su propio proceso? - ¿Cómo puedo especificar que mi DLL debería resolver una dependencia de DLL del mismo directorio en el que se encuentra la DLL?
- Después de que hice mi DLL retraso-cargar otra DLL, mi DLL ha comenzado a bloquearse en su código de desparaste de proceso
- Los diferentes tipos de plantación de DLL
- ¿Por qué
GetModuleInfo
no puede producir un punto de entrada para ejecutables? - ¿Qué significa el
SizeOfImage
en la estructura de MODULEINFO
? - ¿Cómo suprimo el cuadro de error que aparece cuando falla una
LoadLibrary
?
DllMain()
- Algunas razones para no hacer nada aterrador en tu
DllMain
- Otra razón para no hacer nada aterrador en tu
DllMain
: punto muerto inadvertido - Algunas razones para no hacer nada aterrador en tu
DllMain
, Parte 3 - El hilo que recibe la notificación
DLL_PROCESS_DETACH
no es necesariamente el que recibió la DLL_PROCESS_ATTACH notification
- Cómo podría estar cargando una dll durante
DLL_PROCESS_DETACH
sin siquiera darse cuenta - Cuando
DLL_PROCESS_DETACH
le dice que el proceso está saliendo, su mejor opción es volver sin hacer nada
Recursos
- El compilador de recursos predeterminado es
CP_ACP
, incluso ante sugerencias sutiles de que el archivo es UTF-8 - La relación entre los recursos del módulo y los objetos derivados de recursos en Windows de 32 bits
- ¿Cuál es la diferencia entre
FreeResource
y, por ejemplo, DestroyAcceleratorTable
- Los recursos de PE deben estar alineados con 4 bytes, pero eso no impide que las personas prueben otras alineaciones
- ¿Cómo puedo decir que alguien usó la macro
MAKEINTRESOURCE
para contrabandear un entero dentro de un puntero? - Horricídy Nasty Gotcha:
FindResource
y FindResourceEx
Recursos de mapa de bits e icono
- ¿Por qué los mapas de bits independientes del dispositivo están al revés?
- El formato de recursos de mapa de bits
- El formato de recursos de iconos
- El formato de recursos de icono, revisitado
- La evolución del formato de archivo ICO, Parte 1: Monocrome Beginnings
- La evolución del formato de archivo ICO, Parte 2: ¡ahora en color!
- La evolución del formato de archivo ICO, Parte 3: Imágenes de mezcla alfa
- La evolución del formato de archivo ICO, Parte 4: Imágenes PNG
- ¿Cómo configura el canal alfa de un mapa de bits GDI en 255?
Recursos de cadena de mensajes
- ¿Por qué
FormatMessage
dice que %0
termina el mensaje sin una nueva línea de salida? ¿Está agregando secretamente nuevas líneas?
Plantillas de diálogo
- Sobre la dificultad de obtener el diseño de píxel-perfecto en las plantillas de diálogo Win32
- La evolución de las plantillas de diálogo: plantillas clásicas de 32 bits
- La evolución de las plantillas de diálogo: plantillas extendidas de 32 bits
- La evolución de las plantillas de diálogo - Resumen
- El compilador de recursos le agregará útiles estilos de ventana, pero si está creando una plantilla de diálogo, no obtiene esa ayuda
Plantillas de menú y recursos del acelerador
- La evolución de las plantillas de menú: introducción
- La evolución de las plantillas de menú: menús clásicos de 32 bits
- La evolución de las plantillas de menú: menús extendidos de 32 bits
- El formato de recursos de la tabla de aceleradores
Recursos de cadena
- El formato de recursos de cadena
-
LoadString
puede cargar cadenas con nulos integrados, pero es posible que su función de envoltorio no
Plantillas de versión
- La evolución de los recursos de la versión: recursos de versión de 32 bits
- La evolución de los recursos de la versión: recursos de versión corruptos de 32 bits
Datos y recursos personalizados
- El formato de datos y recursos personalizados
Aplicación (en su conjunto)
- ¿Qué ventanas aparecen en la lista
Alt+Tab
? - Windows Vista cambió ligeramente el orden
Alt+Tab
- El trabajo de interfaz de usuario de Win32 es inherentemente uniforme
- ¿Cuándo anula
STARTF_USESHOWWINDOW
el parámetro pasado a ShowWindow
? -
WaitForInputIdle
realmente debería llamarse WaitForProcessStartupComplete
-
WaitForInputIdle
espera cualquier hilo, que podría no ser el hilo que le importa - ¿Cuáles son las convenciones para gestionar las manijas estándar?
- Las manijas estándar están realmente destinadas a los programas de un solo subproceso
- Si solo los DLLS pueden recibir notificaciones
DllMain
, ¿cómo puede un EXE recibir una notificación cuando se crea un hilo (por ejemplo)?
Línea de comando
- La primera palabra en la línea de comando es el nombre del programa solo por convención
- ¿Cómo se pretende usar la función
CommandLineToArgvW
? - ¿Qué pasa con el extraño tratamiento de las comillas y las versas de backsflass por
CommandLineToArgvW
Barra de tareas
- ¿Cómo evito que los usuarios sujeten mi programa a la barra de tareas?
- En lugar de crear algo y luego tratar de ocultarlo, simplemente no lo cree en primer lugar (ícono de la bandeja)
- ¿Qué pasa si mi aplicación es realmente dos aplicaciones inclinadas en un solo archivo, y quiero que se recopilen en dos grupos en la barra de tareas en Windows 7?
- ¿Cómo personalizo cómo se agrupan las ventanas de mi aplicación en la barra de tareas?
- Muestra una superposición en el botón de la barra de tareas
- Mostrar botones de control en la ventana de vista previa de la barra de tareas
- Muestre una miniatura personalizada para su aplicación (y mientras lo hace, una vista previa en vivo personalizada)
- ¿Cómo puedo consultar la ubicación de la barra de tareas en monitores secundarios?
- ¿Cómo se las arregló ese programa para fijarse en mi barra de tareas cuando lo instalé?
- ¿Qué pasa si tengo dos programas que son lógicamente una sola aplicación, y quiero que sean tratados como un grupo único en la barra de tareas?
- ¿Por qué el icono de la barra de tareas para ventanas agrupadas cambia a algo extraño?
HWND
(punto de vista general)
- ¿Qué significa que una ventana sea unicode?
- ¿Cómo puedo obtener la dirección de procedimiento de ventana real y no un thunk?
- ¿Cuáles son estos valores extraños devueltos de
GWLP_WNDPROC
? - La ventana de bonificación bytes en
GWLP_USERDATA
- ¿Cuál es la diferencia entre
WM_DESTROY
y WM_NCDESTROY
? - Enviar una ventana un mensaje
WM_DESTROY
es como una broma llamar a alguien que finge ser la policía - La vida secreta de
GetWindowText
- ¿Por qué las reglas para
GetWindowText
son tan raras? - Pintar solo cuando su ventana es visible en la pantalla
- Determinar si su ventana está cubierta
- Obtener el tamaño y la posición de una ventana mientras se minimiza
- ¿Por qué llamar
SetForegroundWindow
seguido inmediatamente por GetForegroundWindow
no devuelve la misma ventana hacia atrás? - ¿Cómo decide Windows si una ventana recién creada debe usar el diseño LTR o RTL?
Jerarquía de Windows
- ¿Qué tiene de especial la ventana de escritorio?
- ¿Cuál es el límite de anidación de la ventana?
- ¿Cuál es la diferencia entre
HWND_TOP
y HWND_TOPMOST
? - Una ventana puede tener un padre o un propietario, pero no ambos
- ¿Por qué mi control envía sus notificaciones a la ventana incorrecta después de que lo reparé?
-
WindowFromPoint
, ChildWindowFromPoint
, RealChildWindowFromPoint
, ¿cuándo terminará todo? -
GetParent
, tan confuso como EnumClaw
, ¡pero es una función real! ( GetAncestor()
, GetWindow()
) - Tener una ventana del propietario de otro proceso es complicado, pero a veces es lo correcto
- ¿Cuál es la documentación para
SetParent
tratando de decirme sobre la sincronización del estado de la interfaz de usuario? - Demostrando lo que sucede cuando un padre e hijos tienen diferentes estados de interfaz de usuario
- Hacer que una ventana de padres e hijos tenga los mismos estados de interfaz de usuario
Estilos de ventana
- ¿Qué bits de estilo de ventana pertenecen a quién?
- ¿Cómo indico que quiero que mi ventana siga reglas de diseño de derecha a izquierda?
- ¿Por qué no es transparente mi control estático transparente? (
WS_EX_TRANSPARENT
) - Al igual que el pastel,
WS_EX_TRANSPARENT
es una mentira, o al menos no toda la verdad - Usé
WS_EX_COMPOSITED
para deshacerme de mi parpadeo de redibujado, pero resultó en una respuesta lenta - ¿Cómo puedo usar
WS_CLIPCHILDREN
y aún poder dibujar un control con un fondo transparente?
Clases de ventana
- ¿Para qué se pasa la
HINSTANCE
a CreateWindow
y RegisterClass
? - Usar la
HINSTANCE
incorrecta en RegisterClass
es como el robo de identidad - Si la función
RegisterClass
toma posesión del cepillo de fondo personalizado, ¿por qué se está filtrando? - Cambiar una clase de ventana afecta a todas las ventanas que pertenecen a esa clase
- ¿Qué hacen
CS_SAVEBITS
? - ¿Qué hace el estilo de clase
CS_OWNDC
? - ¿Qué hace el estilo de clase
CS_CLASSDC
? - La modificación del estilo
CS_NOCLOSE
afecta a todas las ventanas de la clase, simplemente no necesariamente de una manera notable inmediatamente notable - ¿Por qué
PrintWindow
odia CS_PARENTDC
? ¡Porque todos odian CS_PARENTDC
! - ¿Por qué
PrintWindow
odia CS_PARENTDC
? Redux - Subclases más seguros
- Clases privadas, superclasificación y subclases globales
- ¿Qué hace que
RealGetWindowClass
sea mucho más real que GetClassName
? - ¿Por qué
CreateWindowEx
toma el parámetro de estilo extendido como su primer parámetro en lugar de su último? - ¿Cuándo debo usar
CS_GLOBALCLASS
? - ¿Qué tan único debe ser el parámetro UIDSubClass cuando llamo a
SetWindowSubclass
?
Ventanas de nivel superior
Marco y subtítulo de la ventana
- Obtener un menú personalizado de clic derecho para el icono de subtítulos
- Dibujar un título de aspecto activo incluso cuando no está activo
- ¿Cómo suprimo el arrastre/cambio de tamaño de la ventana completa para una sola ventana?
- ¿Cómo cambio una ventana entre la pantalla normal y completa?
- ¿Cómo habilito y deshabilito los botones minimizar, maximizar y cerrar en mi barra de subtítulos?
- Obtener la ubicación del botón Cerrar en la barra de título
- Obtener la ubicación del botón Cerrar en la barra de título, desde Windows 2000 o Windows XP
- ¿Por qué son las dimensiones de una ventana maximizada más grandes que el monitor?
- Crear una ventana que se pueda cambiar el tamaño en una sola dirección
- ¿Por qué no reenvía
WM_GETMINMAXINFO
y sujetas los resultados?
DWM
- ¿Por qué mi programa no recibe el mensaje
WM_DWMSENDICONICTHUMBNAIL
cuando pido una representación icónica? - El parámetro
MARGINS
al DwmExtendFrameIntoClientArea
Controla hasta qué punto el marco se extiende en el área del cliente - ¿Cómo suprimo la animación predeterminada que ocurre cuando escucho o muestro una ventana?
- Muestre una miniatura personalizada para su aplicación (y mientras lo hace, una vista previa en vivo personalizada)
- ¿Cómo puedo detectar que mi ventana ha sido suprimida de la pantalla por la cubierta? ("Cloaje de ventana")
Diálogo
- ¿Por qué no puedo crear mi cuadro de diálogo? Error de novato #1
- ¿Por qué no puedo crear mi cuadro de diálogo? Error de novato #2
- Valores de devolución de un procedimiento de diálogo
- Un tipo diferente de procedimiento de diálogo
- Otro tipo diferente de procedimiento de diálogo
- La respuesta predeterminada a cada cuadro de diálogo es "Cancelar"
- Girando el orden z
- Uso de la tecla
TAB
para navegar en no dialogs - Uso de la tecla
TAB
para navegar en no dialogs, Redux - Pediendo que editar el texto de control se elija automáticamente en un cuadro de diálogo
- Aquellos que no entienden el administrador de diálogo están condenados a reimplegarlo, mal
- Otros trucos con
WM_GETDLGCODE
-
GetDialogBaseUnits
es un barro - ¿Por qué no son los rectángulos de diálogo
MapDialogRect
? - ¿Por qué se crean inicialmente los cuadros de diálogo?
- ¿Cuál es el trato con la bandera
DS_SHELLFONT
? - ¿Por qué
DS_SHELLFONT = DS_FIXEDSYS | DS_SETFONT
? - Cómo establecer Focus en un cuadro de diálogo
- Nunca deje el enfoque en un control discapacitado
- Una sutileza para restaurar la posición anterior de la ventana
- Cosas que ya sabes: ¿Cómo espero hasta que se muestre mi cuadro de diálogo antes de hacer algo?
- ¿Qué hace
TranslateAccelerator
? - Si tengo un cuadro de diálogo sin modificación con aceleradores personalizados, que debería llamar primero:
IsDialogMessage
o TranslateAccelerator
- Recordatorio suave: en un cuadro de diálogo, no das bien y cancele aceleradores
- ¿Por qué los aceleradores para los controles ocultos aún están activos?
- ¿Cómo hago que mis aceleradores se apliquen solo cuando se usan en la ventana principal y no cuando el usuario está usando un diálogo sin modificar?
- ¿Por qué la tecla
TAB
no funciona en los controles que he marcado como WS_TABSTOP
? - No puede usar el mensaje
WM_USER
en un cuadro de diálogo - ¿Cómo puedo hacer un cuadro de diálogo de derecha a izquierda en tiempo de ejecución?
- ¿Cómo calcula el administrador de diálogo el ancho promedio de un carácter?
Diálogos anidados e incrustados
- ¿Para qué sirve el estilo
DS_CONTROL
? - Más notas sobre el uso del estilo
DS_CONTROL
- No es una buena idea dar múltiples controles en un cuadro de diálogo la misma identificación
- Al incrustar un diálogo dentro de otro, asegúrese de no crear accidentalmente ID de control duplicados
- Cuando se invoca el botón de empuje predeterminado, el Invoke va al cuadro de diálogo de nivel superior
Diálogo comunes
- ¿Por qué no se envuelve mi
MessageBox
en la ubicación correcta? - ¿Cómo personalizo la sección de enlaces favoritos del cuadro de diálogo Abierto de archivo?
- ¿Por qué el diálogo de archivo común cambia el directorio actual?
- Puede filtrar el cuadro de diálogo de archivo común con comodines
- ¿Cómo muestro el cuadro de diálogo Buscar impresoras programáticamente?
- ¿Por qué la lista de archivos abiertos en las carpetas compartidas Snap-In muestra todos mis archivos abiertos?
- Un control común para asociar extensiones está muy atrasado
- Filtrando las carpetas que aparecen en el cuadro de diálogo Examinar para la carpeta
- Abrir el cuadro de diálogo del navegador de carpeta clásica con una carpeta específica preseleccionada
- ¿Por qué el diálogo Guardar de archivo común crea un archivo temporal y luego lo elimina?
- Personalización del cuadro de diálogo Estándar en color
- ¿Cómo configura el directorio inicial del diálogo Abrir archivo en un directorio virtual?
- Cuando selecciono varios archivos en el cuadro de diálogo Abierto de archivo, ¿por qué el último elemento llega primero?
- Establecí la opción
OFN_NONETWORKBUTTON
en la estructura OPENFILENAME
, pero no tiene ningún efecto en el elemento de red en el panel de navegación - ¿Cómo agrego controles personalizados a los diálogos de Abrir o guardar archivo de archivo?
- ¿Cómo puedo hacer que mi
FileSavePicker
se abra en la misma carpeta que fue elegida por FileOpenPicker
o FolderPicker
? (Win32/com equivalente mencionado al final de la publicación)
Navegación de control
- Uso de la tecla
TAB
para navegar en no dialogs - Uso de la tecla
TAB
para navegar en no dialogs, Redux - Gestión del estado de la UI de aceleradores y rectángulos de enfoque
- Navegación personalizada en cuadros de diálogo, Redux
- Los cuadros de diálogo devuelven el enfoque al control que tenía un enfoque cuando se cambió por última vez; ¿Cómo entro en esa acción para mis propias ventanas?
- ¿Cómo puedo crear un pedido de pestañas no circular, o algún otro tipo de pedido personalizado en mi diálogo Win32?
Administrador de diálogo
- El administrador de diálogo, Parte 1: Calentamientos
- El administrador de diálogo, Parte 2: Creación de la ventana de cuadro
- El administrador de diálogo, Parte 3: Creación de controles
- El administrador de diálogo, parte 4: el bucle de diálogo
- El administrador de diálogo, Parte 5: Convertir un cuadro de diálogo no modal a modal
- El administrador de diálogo, Parte 6: Subtletas en bucles de mensajes
- El administrador de diálogo, Parte 7: Más sutilezas en los bucles de mensajes
- El administrador de diálogo, Parte 8: Navegación personalizada en los cuadros de diálogo
- El administrador de diálogo, Parte 9: Aceleradores personalizados en los cuadros de diálogo
Modalidad
- El orden correcto para deshabilitar y habilitar Windows
- Modalidad, Parte 1: Modalidad de UI vs Modalidad de código
- Modalidad, Parte 2: Code-Modality vs UI-Modality
- Modalidad, Parte 3: El mensaje
WM_QUIT
- Modalidad, Parte 4: La importancia de establecer el propietario correcto para la interfaz de usuario modal
- Modalidad, Parte 5: Configurar el propietario correcto para la interfaz de usuario modal
- Modalidad, Parte 6: Interactuar con un programa que se ha vuelto modal
- Modalidad, Parte 7: Un
MessageBox
cronometrado, la versión barata - Modalidad, Parte 8: un
MessageBox
cronometrado, la mejor versión - Modalidad, Parte 9: Establecer el propietario correcto para la interfaz de usuario modal, examen práctico
- Los mensajes de hilo son comidos por bucles modales
- Rescatar mensajes de hilo de bucles modales a través de filtros de mensajes
Hojas de propiedad
- ¿Qué otros efectos tiene
DS_SHELLFONT
en las páginas de la hoja de propiedades? -
PSM_ISDIALOGMESSAGE
es a hojas de propiedades modernas, ya que IsDialogMessage
es a cuadros de diálogo sin modificación - Puede extender la estructura
PROPSHEETPAGE
con sus propios datos de bonificación - La notificación
PSN_SETACTIVE
se envía cada vez que se activa su página del Asistente - Agregar carga útil adicional a una estructura de
PROPSHEETPAGE
- ¿Cómo paso una matriz de estructuras
PROPSHEETPAGE
de tamaño variable a la hoja de propiedades?
Control
- El hecho de que eres un control no significa que estés necesariamente dentro de un cuadro de diálogo
Controles de animación
- Limitaciones del control de animación de shell
- ¿Por qué el control de animación de la versión 6 no usa un hilo de fondo?
Botones
- ¿Para qué sirve el estilo de botón
BS_PUSHLIKE
? (No lo use, es completamente obsoleto hoy en día. Use la casilla de verificación o el botón de radio).
Cajas combinadas
- Acelerar la adición de elementos a un Combobox o ListBox (
WM_SETREDRAW
)
Editar controles
- ¿Cuál es el trato con el mensaje
EM_SETHILITE
? - Pediendo que editar el texto de control se elija automáticamente en un cuadro de diálogo
- ¿Cómo suprimo la advertencia
CapsLock
en los controles de edición de contraseña? - La historia temprana del estilo de control de edición
ES_NUMBER
- ¿Cómo permito los números negativos con el estilo de control de edición
ES_NUMBER
? - ¿Cómo permito que se ingrese un signo menos en mi control de edición, pero solo si es el primer personaje?
Vistas de listas
- Vistas de ListView posicionadas versus no posicionadas
- Mostrando Infotips para elementos de ListView plegados y desplegados
- Informática ListView Infotips en segundo plano
- ¿Cuál es la diferencia entre
LVM_HITTEST
y LVM_INSERTMARKHITTEST
? - ¿Por qué hay una notificación
LVN_ODSTATECHANGED
cuando ya hay una notificación perfectamente buena LVN_ITEMCHANGED
? - Creación de una vista de lista con casillas de verificación en algunos elementos pero no en otros
- ¿Cómo puedo cambiar el tamaño programado de una columna ListView para que se ajuste a su contenido?
- ¿Cómo creo una casilla de verificación deshabilitada para un elemento ListView?
- Acelerar la adición de elementos a un Combobox o ListBox (
WM_SETREDRAW
)
Controles de texto ricos
La historia del control de RichEdit de Murray Sargent (La publicación es solo un enlace (roto) a https://blogs.msdn.microsoft.com/murrays/2006/10/19/some-richedit-history/)- ¿Cómo cargo un archivo completo en un rico control de texto?
- ¿Cómo pongo más de 32,000 caracteres en un rico control de texto?
- ¿Cómo imprimo el contenido de un rico control de texto?
Barras de desplazamiento
- El programa Scratch
- Barras de desplazamiento, parte 2
- Barras de desplazamiento, Parte 3: Optimización del ciclo de pintura
- Barras de desplazamiento, Parte 4: Agregar una barra de desplazamiento proporcional
- Probable Parte 5: Accesibilidad al teclado para barras de desplazamiento
- Anexo a la Parte 5: una sutileza en el código del teclado
- Barras de desplazamiento Parte 6 - la rueda
- Barras de desplazamiento Parte 7 - Integralidad
- Barras de desplazamiento Parte 8 - Cambio de tamaño interactivo integral
- Barras de desplazamiento Parte 9 - Mantener la metáfora
- Barras de desplazamiento Parte 10 - Hacia una comprensión más profunda del mensaje
WM_NCCALCSIZE
- Barras de desplazamiento Parte 11: Hacia una comprensión aún más profunda del mensaje
WM_NCCALCSIZE
- Respuestas al ejercicio de las barras de desplazamiento Parte 11
- Barras de desplazamiento Parte 12: Aplicando
WM_NCCALCSIZE
a nuestra muestra de barra de desplazamiento - Barras de desplazamiento Redux: Parte 12
- Hay dos tipos de barras de desplazamiento
- ¿Por qué se eligió
WHEEL_DELTA
para tener 120 años en lugar de un valor mucho más conveniente como 100 o incluso 10? - ¿Por qué establecer el rango de barras de desplazamiento horizontal por primera vez también establece el rango vertical y viceversa?
- AutoScrolling on Drag, Parte 1: Implementación básica
- AutoScrolling en la resistencia, Parte 2: ¿Por qué el desplazamiento va más rápido si muevo el mouse?
- AutoScrolling on Drag, Parte 3: AutoScroll dinámico basado en la posición del mouse
- AutoScrolling On Drag, Parte 4: AutoScroll dinámico basado en la velocidad de escape
- AutoScrolling on Drag, Parte 5: Agregar Wiggle-to Scroll para escapar de la velocidad
Controles estáticos
- ¿Cuándo el control estático eliminará automáticamente la imagen cargada en ella y cuándo es responsabilidad de la aplicación?
Controles de pestañas
- ¿Cómo debo crear controles en mi cuadro de diálogo que tenga un control de pestañas?
- ¿Cómo se supone que debo crear hijos del control de la pestaña Win32?
Barras de herramientas
- ¿Por qué hay tanto
TBSTYLE_EX_VERTICAL
y CCS_VERT
? - ¿Cómo creo una barra de herramientas que se encuentra en la barra de tareas?
- ¿Cómo creo un botón de la barra de herramientas alineado con la derecha?
- Creación de tareas personalizadas en una lista de saltos
Servicio de herramientas
- Codificación de información sobre herramientas en el lugar
- Uso de personalizados personalizados en información sobre herramientas para ajustar la fuente
- Multiplexar múltiples herramientas en una en una información sobre herramientas
- Generar el texto de información sobre herramientas dinámicamente
- ¿Por qué no puedo mostrar una información sobre herramientas para una ventana deshabilitada?
-
TTM_RELAYEVENT
sobre el documento excesivo y por qué resulta en un temporizador periódico de un segundo siempre que la información sobre herramientas sea visible
Barras de pista
- Agregar un acelerador de flecha
Ctrl
+para mover la barra de seguimiento por solo una unidad, Parte 1: inmersión inicial - Agregar un acelerador de flecha
Ctrl
+para mover la barra de seguimiento por solo una unidad, parte 2: segundo intento - ¿Cómo evito que los usuarios usen el mouse para arrastrar el pulgar Trackbar a posiciones que no son múltiplos de cinco? Parte 1: Replantear el problema
- ¿Cómo evito que los usuarios usen el mouse para arrastrar el pulgar Trackbar a posiciones que no son múltiplos de cinco? Parte 2: empujando la posición del pulgar
Vistas de la lista de árboles
- El estilo
TVS_CHECKBOXES
es peculiar, lo cual es una forma educada de decir que es una locura - Tenga cuidado con la lista de imágenes filtradas cuando use el estilo
TVS_CHECKBOXES
- Creación de casillas de verificación Vista de árboles manualmente: una lista de imágenes de estado simple
- Creación de casillas de verificación de vista de árbol manualmente: Responder a los clics
- Creación de casillas de verificación de vista de árbol manualmente: casillas de verificación temática
- Casillas de verificación Vista de árbol: una historia sórdida
- Casillas de verificación de la vista de árbol: los estados de la casilla de verificación extendida
Procesamiento de mensajes
- ¿Qué números de mensaje pertenecen a quién?
- Las diversas formas de enviar un mensaje
- Transmisión de mensajes definidos por el usuario
- ¿Cuándo puede un hilo recibir mensajes de ventana?
- ¿Cuál es la diferencia entre
GetKeyState
y GetAsyncKeyState
? - Los mensajes de hilo son comidos por bucles modales
- Rescatar mensajes de hilo de bucles modales a través de filtros de mensajes
- Los peligros de filtrar mensajes de ventana
- No puede simular la entrada del teclado con
PostMessage
- Bombear mensajes mientras espera un período de tiempo
- En busca de la cola de mensajes
- No, realmente, debes transmitir todos los mensajes no controlados a
DefWindowProc
- Incluso si tiene código para manejar un mensaje, se le permite llamar
DefWindowProc
, porque lo estaba haciendo de todos modos después de todo - ¿Para qué se usó
Get/SetMessageExtraInfo
? - ¿Por qué
GetWindowLongPtr
devuelve un valor de basura en ventanas de 64 bits? -
TrackMouseEvent
Tracks Mouse Events en su ventana, pero solo si los eventos pertenecen a su ventana - No olvide incluir la cola de mensajes en su jerarquía de bloqueo
- ¿Qué le sucede a un mensaje enviado cuando
SendMessageTimeout
alcanza su tiempo de espera? - ¿Por qué no puedo
PostMessage
el mensaje WM_COPYDATA
, pero puedo SendMessageTimeout
con un pequeño tiempo de espera? - Aunque los mensajes de mouse, pintura y temporizador se generan a pedido, todavía es posible que uno termine en su cola
- Los mensajes publicados se procesan antes de los mensajes de entrada, incluso si se publicaron más tarde
- ¿Qué tipo de mensajes puede recibir una ventana de solo mensaje?
- Si los prototipos de
DispatchMessageA
y DispatchMessageW
son idénticos, ¿por qué han sido ambos? - Aquellos que no entienden el administrador de diálogo están condenados a reimplegarlo, mal
- ¿Cómo puedo activar un recalcamiento del cursor del mouse después de que cambié parte de mi estado de aplicación interna?
- ¿Cómo puedo activar un recalcamiento del cursor del mouse después de que cambié parte de mi estado de aplicación interna?, Seguimiento
-
GetQueueStatus
y el estado de la cola
Enganche
- ¿Para qué se usa la
HINSTANCE
a SetWindowsHookEx
? - ¿Cómo puedo notificar cuando cambia el cursor?
- What does the thread parameter to
SetWindowsHookEx
actually mean? - Why does
SetFocus
fail without telling me why?
Specific Messages
Notificaciones
- What's the difference between the
wParam
of the WM_NOTIFY
message and the idFrom
in the NMHDR
structure. - Restating the obvious about the
WM_COMMAND
message - Restating the obvious about the
WM_NOTIFY
message
Window Construction and Destruction
- What is the difference between
WM_DESTROY
and WM_NCDESTROY
? - How can I determine the reason why my window is closing? (
WM_CLOSE
)
Window Geometry Messages
- Use
WM_WINDOWPOSCHANGED
to react to window state changes - Use
WM_WINDOWPOSCHANGING
to intercept window state changes
Window Painting Messages
- Paint messages will come in as fast as you let them (
WM_PAINT
) - What happens if I don't paint when I get a
WM_PAINT
message? - What is the implementation of
WM_PRINTCLIENT
? - There's a default implementation for
WM_SETREDRAW
, but you might be able to do better - Speeding up adding items to a combobox or listbox (
WM_SETREDRAW
) - Using
WM_SETREDRAW
to speed up adding a lot of elements to a control
Window Focus Messages
-
WM_KILLFOCUS
is the wrong time to do field validation - The dangers of playing focus games when handling a
WM_KILLFOCUS
message - Why doesn't the
MoveWindow
function generate the WM_GETMINMAXINFO
message?
Keyboard Messages
- How do I respond to the
WM_MENUCHAR
message?
Mouse Messages
- Why is there no
WM_MOUSEENTER
message? - Why do I get spurious
WM_MOUSEMOVE
messages? - Sure, I can get spurious
WM_MOUSEMOVE
messages, but why do they keep streaming in? - How do I get mouse messages faster than
WM_MOUSEMOVE
? - Logical consequences of the way Windows converts single-clicks into double-clicks
- Implementing higher-order clicks
- How slow do you have to slow-double-click for it to be a rename?
- How can I prevent the mouse from moving in response to touch input?
Dialog Messages
- Those who do not understand the dialog manager are doomed to reimplement it, badly
- Managing the UI state of accelerators and focus rectangles (
WM_CHANGEUISTATE
, WM_QUERYUISTATE
and WM_UPDATEUISTATE
) - Untangling the confusingly-named
WM_UPDATEUISTATE
and WM_CHANGEUISTATE
messages - Who sends the initial
WM_UPDATEUISTATE
message? - How can I prevent the keyboard focus rectangle from appearing on a control I created?
- Other tricks with
WM_GETDLGCODE
- How do I prevent multi-line edit controls from eating the Enter key?
- Why do
DLGC_WANTALLKEYS
and DLGC_WANTMESSAGE
have the same value?
Other Window Messages
- The dangers of messing with activation when handling a
WM_ACTIVATE
message - Why does my window get a
WM_ACTIVATE
message when it isn't active? - A timed context menu (
WM_CANCELMODE
) - Pitfalls in handling the
WM_CONTEXTMENU
message ( WM_CONTEXTMENU
) -
WM_NCHITTEST
is for hit-testing, and hit-testing can happen for reasons other than the mouse being over your window - How likely is it that a window will receive a
WM_NULL
message out of the blue? ( WM_NULL
) - Why is there a special
PostQuitMessage
function? ( WM_QUIT
) - How does
PostQuitMessage
know which thread to post the quit message to? ( WM_QUIT
) - Who is responsible for destroying the font passed in the
WM_SETFONT
message? ( WM_SETFONT
) - When I send a
WM_GETFONT
message to a window, why don't I get a font? ( WM_GETFONT
) - If my
WM_TIMER
handler takes longer than the timer period, will my queue fill up with WM_TIMER
messages? - Killing a window timer prevents the
WM_TIMER
message from being generated for that timer, but it doesn't retroactively remove ones that were already generated
System Messages
- If one program blocks shutdown, then all programs block shutdown (
WM_QUERYENDSESSION
, WM_ENDSESSION
) - Why do I have to return this goofy value for
WM_DEVICECHANGE
? ( WM_DEVICECHANGE
) - Windows doesn't close windows when a user logs off; that's your call (
WM_ENDSESSION
) - Once you return from the
WM_ENDSESSION
message, your process can be terminated at any time ( WM_ENDSESSION
)
GDI
- Why are
RECT
s endpoint-exclusive? - Can you create an information context for the display?
- What does the
CS_OWNDC
class style do? - What does the
CS_CLASSDC
class style do? - How do you detect "Large Fonts"? (DPI)
- Drawing a monochrome bitmap with transparency
- Let GDI do your RLE compression for you
- The mysterious stock bitmap: There's no way to summon it, but it shows up in various places
- Why is my icon being drawn at the wrong size when I call
DrawIcon
? - You must flush GDI operations when switching between direct access and GDI access, and direct access includes other parts of GDI
- How do I get the dimensions of a cursor or icon?
- What are the dire consequences of not selecting objects out of my DC?
- Of what use is the
RDW_INTERNALPAINT
flag? - Functions that return GDI regions rarely actually return regions
- Color-aware ClearType requires access to fixed background pixels, which is a problem if you don't know what the background pixels are, or if they aren't fixed
- What is the correct way of using
SaveDC
and RestoreDC
? - How are
BitBlt
raster opcodes calculated? - Notes on
DrawText
and tab stops - Why doesn't
GetTextExtentPoint
return the correct extent for strings containing tabs? - Why are there trivial functions like
CopyRect
and EqualRect
? - More on trivial functions like
CopyRect
and EqualRect
- What are the consequences of increasing the per-process GDI handle limit?
- The focus rectangle says, “I'm not orange. I'm just drawn that way.”
Cursors
- The effect of
SetCursor
lasts only until the next SetCursor
- What can or should I do with the cursor handle returned by
SetCursor
? - What is the deal with the
SM_CXCURSOR
system metric? - How do I find out the size of the mouse cursor?
Pincel
- The hollow brush
- Other uses for bitmap brushes
- What is the DC brush good for?
- I know I can change the color of the DC pen, but what about the other attributes?
- How can I extract the color from a solid color GDI brush?
Pens
- Is there a difference between creating a null pen with
CreatePen
and just using the stock null pen?
Bitmaps
- How do I set the alpha channel of a GDI bitmap to 255?
DIB
- A survey of the various ways of creating GDI bitmaps with predefined data
- Blitting between color and monochrome DCs
- Manipulating the DIB color table for fun and profit
- Using DIB sections to perform bulk color mapping
- The fun and profit of manipulating the DIB color table can be done without having to modify it
- Separating the metadata from the DIB pixels: Precalculating the
BITMAPINFO
- Separating the metadata from the DIB pixels: Changing the raster operation
- The disembodiment of DIBs from the DIB section
- What is the
hSection
parameter to CreateDIBSection
for?
LockWindowUpdate()
- What does
LockWindowUpdate
do? - How is
LockWindowUpdate
meant to be used? - With what operations is
LockWindowUpdate
meant to be used? - With what operations is
LockWindowUpdate
not meant to be used? - Final remarks on
LockWindowUpdate
Painting Standard Elements
- Rendering standard Windows elements
- Rendering menu glyphs is slightly trickier
- What states are possible in a
DRAWITEMSTRUCT
structure?
UXTHEME.DLL
-
BeginBufferedPaint
: It's not just for buffered painting any more - How do
IsThemeActive
, IsAppThemed
, and IsCompositionActive
differ? - How do I get the tabbed dialog effect on my own custom tabbed dialog?
- How do I revert a control back to its default theme?
Multiple Monitors
- For better performance, set all your monitors to the same color format
- How do I get a handle to the primary monitor?
- Why does the primary monitor have
(0,0)
as its upper left coordinate? - How do I get the color depth of the screen?
- How does the window manager adjust
ptMaxSize
and ptMaxPosition
for multiple monitors?
Accesibilidad
- Accessibility is not just for people with disabilities
- How to retrieve text under the cursor (mouse pointer)
- How do I set an accessible name on an unlabeled control?
- How can I get notified when some other window is destroyed?
- Using accessibility to monitor windows as they come and go
- How can I write a program that monitors another window for a title change?
- How can I write a program that monitors another window for a change in size or position?
Comunicarse
Declaring COM Interfaces
- The macros for declaring COM interfaces, revisited: C version
- The macros for declaring COM interfaces, revisited: C++ version
- The macros for declaring COM interfaces, revisited: C++ implementation
- The oracle always tells the truth, even when it is wrong: COM method calls with a user-defined type as a return value (on problems of COM interfaces called from C code)
- The COM interface contract rules exist for a reason
- Giving a single object multiple COM identities, part 1
- Giving a single object multiple COM identities, part 2
- Giving a single object multiple COM identities, part 3
- Giving a single object multiple COM identities, part 4
- How do I consume raw COM interfaces from a Windows Runtime metadata file?
COM Apartments
- The dreaded "main" threading model
- A slightly less brief introduction to COM apartments (but it's still brief)
- Yo dawg, I hear you like COM apartments, so I put a COM apartment in your COM apartment so you can COM apartment while you COM apartment
- What kind of apartment is the private apartment I created via
CLSID_ContextSwitcher
? - Setting up private COM contexts to allow yourself to unload cleanly
- How do you get into a context via
IContextCallback::ContextCallback
? - Using contexts to return to a COM apartment later
- What do the output values from
CoGetApartmentType
mean? - User interface code + multi-threaded apartment = death
- Other problems traced to violating COM single-threaded apartment rules in the shell
- What's the point of
APTTYPE_CURRENT
? I mean, of course I'm current. - How do I get a foothold in the neutral apartment?
- What is so special about the Application STA?
- What does it mean when a call fails with
0x8000001F = RO_E_BLOCKED_CROSS_ASTA_CALL
?
COM Initialization
- What does the
COINIT_SPEED_OVER_MEMORY
flag to CoInitializeEx
do? - Crashing in COM after I call
CoUninitialize
, how can COM be running after it is uninitalized?
COM Static Store
- The COM static store, part 1: Introduction
- The COM static store, part 2: Race conditions in setting a singleton
- The COM static store, part 3: Avoiding creation of an expensive temporary when setting a singleton
- The COM static store, part 4: Aggregating into a single object
- The COM static store, part 5: Using COM weak references
- The COM static store, part 6: Using C++ weak references
COM Marshaling
- What is COM marshaling and how do I use it?
- On proper handling of buffers in COM and RPC methods
- What are the rules for
CoMarshalInterThreadInterfaceInStream
and CoGetInterfaceAndReleaseStream
? - What are the rules for
CoMarshalInterface
and CoUnmarshalInterface
? -
CoGetInterfaceAndReleaseStream
does not mix with smart pointers - The COM marshaller uses the COM task allocator to allocate and free memory
- Why do I get a
QueryInterface(IID_IMarshal)
and then nothing? - We batched up our COM requests and return a single stream of results, but the performance is still slow
- What are the various usage patterns for manually-marshaled interfaces?
- An initial look at the mechanics of how COM marshaling is performed
- https://devblogs.microsoft.com/oldnewthing/20220616-00/?p=106757
- Writing a marshal-by-value marshaler, part 1
- Writing a marshal-by-value marshaler, part 2
- Writing a compound marshaler
- Understanding the marshaling flags: The free-threaded marshaler
COM Error Handling
- What happens to my COM server-side object when clients die unexpectedly?
- Why does COM require output pointers to be initialized even on failure?
- How do I convert an
HRESULT
to a Win32 error code? - How can I tell the WIL
RETURN_IF_FAILED
macro that some errors are ignorable? - Do not overload the
E_NOINTERFACE
error - What does it mean when a call fails with
0x8000001F = RO_E_BLOCKED_CROSS_ASTA_CALL
? - What does it mean when my cross-thread COM call fails with
RPC_E_SYS_CALL_FAILED
? - Understanding a mysterious
RPC_E_WRONGTHREAD
exception when we're on the right thread
COM Asynchronous Interfaces
- COM asynchronous interfaces, part 1: The basic pattern
- COM asynchronous interfaces, part 2: Abandoning the operation
- COM asynchronous interfaces, part 3: Abandoning the operation after a timeout
- COM asynchronous interfaces, part 4: Doing work while waiting for the asynchronous operation
- COM asynchronous interfaces, part 5: The unreliable server
- COM asynchronous interfaces, part 6: Learning about completion without polling
- COM asynchronous interfaces, part 7: Being called directly when the operation completes
- COM asynchronous interfaces, part 8: Asynchronous release, the problems
- COM asynchronous interfaces, part 9: Asynchronous release, assembling a solution
GUIDs
- What's the difference between
UuidFromString
, IIDFromString
, CLSIDFromString
, GUIDFromString
... - What is the difference between
UuidToString
, StringFromCLSID
, StringFromIID
, and StringFromGUID2
? - Why are there four functions for parsing strings into GUIDs, and why are they in three different DLLs?
- Why does COM express GUIDs in a mix of big-endian and little-endian? Why can't it just pick a side and stick with it?
COM Strings
- Why is there a
BSTR
cache anyway? - Raymond's complete guide to
HSTRING
semantics - What is the correct way of using the string buffer returned by the
WindowsPreallocateStringBuffer
function?
COM Variants
- What's the difference between
VARIANT
and VARIANTARG
? - Nasty gotcha:
VarCmp
vs VariantCompare
- Why can't
VarDateFromStr
parse back a Hungarian date that was generated by VarBstrFromDate
?
IUnknown
- The layout of a COM object
- Under what conditions will the
IUnknown::AddRef
method return 0? - The ways people mess up
IUnknown::QueryInterface
- The ways people mess up
IUnknown::QueryInterface
, episode 2 - The ways people mess up
IUnknown::QueryInterface
, episode 3 - The ways people mess up
IUnknown::QueryInterface
, episode 4 - COM object destructors are very sensitive functions
- Avoiding double-destruction when an object is released
- I'd like an
IUnknown
, I know you have many, I'll take any of them - A very brief introduction to patterns for implementing a COM object that hands out references to itself
- Giving a single object multiple COM identities, part 1
- Giving a single object multiple COM identities, part 2
- Giving a single object multiple COM identities, part 3
- Giving a single object multiple COM identities, part 4
- Reducing chattiness by querying for multiple interfaces at once, part 1
- Reducing chattiness by querying for multiple interfaces at once, part 2
IMoniker
- Pidls and monikers do roughly the same thing, just backwards
ICallback
- A very brief introduction to patterns for implementing a COM object that hands out references to itself
IContextMenu
- Why an object cannot be its own enumerator
- How to host an
IContextMenu
, part 1 - Initial foray - How to host an
IContextMenu
, part 2 - Displaying the context menu - How to host an
IContextMenu
, part 3 - Invocation location - How to host an
IContextMenu
, part 4 - Key context - How to host an
IContextMenu
, part 5 - Handling menu messages - How to host an
IContextMenu
, part 6 - Displaying menu help - How to host an
IContextMenu
, part 7 - Invoking the default verb - How to host an
IContextMenu
, part 8 - Optimizing for the default command - How to host an
IContextMenu
, part 9 - Adding custom commands - How to host an
IContextMenu
, part 10 - Composite extensions - groundwork - How to host an
IContextMenu
, part 11 - Composite extensions - composition - Simplifying context menu extensions with
IExecuteCommand
- How do I launch a file as if it were a text file, even though its extension is not
.txt
? - Do not access the disk in your
IContextMenu
handler, no really, don't do it - Sure, we do that: Context menu edition
- Psychic debugging: Why your
IContextMenu::InvokeCommand
doesn't get called even though you returned success from IContextMenu::QueryContextMenu
- Don't forget to implement canonical names for verbs in your shell context menu extension
IFileDialog
- The
SetClientGuid
method of the common file and folder dialogs lets you give names to those dialogs, too (multiple contexts for open/save dialogs) - How can I get my
FileSavePicker
to open in the same folder that was picked by the FileOpenPicker
or FolderPicker
? (win32/COM equivalent mentioned at the end of the post) - Why does IFileDialog still show non-filesystem folders when I pass
FOS_FORCEFILESYSTEM
?
IMultiLanguage
- Converting between
LCID
s and RFC 1766 language codes - Feel free to stop using
IMultiLanguage2::DetectInputCodepage
INamespaceWalk
- How can I control which parts of the shell namespace the
INamespaceWalk::Walk
operation will walk into? - How can I cancel the
INamespaceWalk::Walk
operation? - Cancelling the
INamespaceWalk::Walk
operation a little faster
IStream
- The subtleties of
CreateStreamOnHGlobal
, part 1: Introduction and basic usage - The subtleties of
CreateStreamOnHGlobal
, part 2: Suppressing the deletion of an unknown HGLOBAL
- The subtleties of
CreateStreamOnHGlobal
, part 3: Suppressing the deletion of a shared HGLOBAL
- The subtleties of
CreateStreamOnHGlobal
, part 4: Non-movable memory - A practical use for
GetHGlobalFromStream
when sharing was never your intention
IVirtualDesktopManager
- Virtual desktops are an end-user window management feature, not a programmatic one
Portapapeles
- How ownership of the Windows clipboard is tracked in Win32
- What happens when applications try to copy text by sending
Ctrl+C
- How do I make it so that users can copy static text on a dialog box to the clipboard easily?
- What is the proper handling of
WM_RENDERFORMAT
and WM_RENDERALLFORMATS
? - Copying a file to the clipboard so you can paste it into Explorer or an email message or whatever
- Printing the contents of the clipboard as text to
stdout
- Improving the performance of
CF_HDROP
by providing file attribute information - What's up with the
CF_SYLK
and CF_DIF
clipboard formats? - How can I wait more than 30 seconds for a delay-rendered clipboard format to become rendered?
Drag and Drop
- What a drag: Dragging text
- What a drag: Dragging a Uniform Resource Locator (URL)
- What a drag: Dragging a Uniform Resource Locator (URL) and text
- What a drag: Dragging a virtual file (
HGLOBAL
edition) - What a drag: Dragging a virtual file (
IStream
edition) - What a drag: Dragging a virtual file (
IStorage
edition) - You can drag multiple virtual objects, you know
- Reading a contract from the other side: Simulating a drop
- Simulating a drop, part two
- What happens if I drag the mouse by exactly the amount specified by
SM_CXDRAG
? - How do I accept files to be opened via
IDropTarget
instead of on the command line? - How do I accept files to be opened via
IDropTarget
instead of on the command line? - bonus content - Using Explorer's fancy drag/drop effects in your own programs
- Drag/drop effects: The little drop information box
- Why isn't my shell namespace extension getting every single
DragOver
mouse message? - Why doesn't my program get fancy drag/drop effects in high contrast mode with
CLSID_DragDropHelper
?
Enumeración
- Using fibers to simplify enumerators, part 1: When life is easier for the enumerator
- Using fibers to simplify enumerators, part 2: When life is easier for the caller
- Using fibers to simplify enumerators, part 3: Having it both ways
- Using fibers to simplify enumerators, part 4: Filtering
- Using fibers to simplify enumerators, part 5: Composition
Caparazón
- When does
SHLoadInProc
unload a DLL? - What does
SHGFI_USEFILEATTRIBUTES
mean? - What's the difference between
SHGetMalloc
, SHAlloc
, CoGetMalloc
, and CoTaskMemAlloc
- Querying information from an Explorer window
- Execute a file as if it were a program, even though its extension is not
EXE
- How do I launch a file as if it were a text file, even though its extension is not
.txt
? - What does the
SEE_MASK_UNICODE
flag in ShellExecuteEx
actually do? - Simple things you can do with the
ShellExecuteEx
function - What were
ShellExecute
hooks designed for? - Why does
ShellExecute
return SE_ERR_ACCESSDENIED
for nearly everything? - How do I
ShellExecute
a file, but with a specific program instead of the default program? - What is the difference between
CSIDL_DESKTOP
and CSIDL_DESKTOPDIRECTORY
? -
SHCIDS_CANONICALONLY
is the moral equivalent in the shell namespace of the Unicode ordinal comparison - Don't forget to double-null-terminate those strings you pass to
SHFileOperation
- Why does
SHFileOperation
have internal error codes for DVD? - Why do non-folders in my shell namespace extension show up in the folder tree view?
-
SHAutoComplete
giveth, and SHAutoComplete
taketh away - What is the
lpClass
member of SHELLEXECUTEINFO
used for? - Some known folders cannot be moved, but others can, and you'll just have to accept that
- One possible reason why
ShellExecute
returns SE_ERR_ACCESSDENIED
and ShellExecuteEx
returns ERROR_ACCESS_DENIED
- Why does
SHGetSpecialFolderPath
take such a long time before returning a network error? - How do you obtain the icon for a shortcut without the shortcut overlay? (
SHGetFileInfo()
) - How can I get information about the items in the Recycle Bin?
- Modernizing our simple program that retrieves information about the items in the Recycle Bin
- Invoking commands on items in the Recycle Bin
- How do I perform shell file operations while avoiding shell copy hooks?
- Command line tool to manage Windows 7 Libraries, with source code (
IShellLibrary
) -
IShellFolder::BindToObject
is a high-traffic method; don't do any heavy lifting - Obtaining the parsing name (and pidl) for a random shell object
- Creating a simple pidl: For the times you care enough to send the very fake
- Creating a simple shell item, just as fake as a simple pidl
- Displaying a property sheet for multiple files
- How do I get a high resolution icon for a file?
- How do I extract an icon at a nonstandard size if
IExtractIcon::Extract
tells me to go jump in a lake? - How do I read the "Double-click to open an item (single-click to select)" setting in Folder Options?
- The wonderful world of shell bind context strings
- Helper functions to make shell bind contexts slightly more manageable
- Customizing item enumeration with
IShellItem
- Customizing item enumeration with
IShellItem
, the old-fashioned way - How do I create an
IShellItemArray
from a bunch of file paths? - How do I invoke a verb on an
IShellItemArray
? - How does a shell namespace extension provide icons for virtual items that track the standard icons set by the user's file associations?
- How do I get the user-customed name of My Computer or Recycle Bin?
- How do I get the user-customized name of a mapped network drive?
- Enumerating all the programs that can open a particular file extension
- Enumerating all the programs that can launch a particular protocol
- How do I register a command on the desktop background context menu? (And how do I remove one I don't like?)
- How can I get the canonical name for a known folder?
- Peeking inside an
IShellItem
to see what it's made of - Why does
SHGetKnownFolderPath
return E_FAIL
for a known folder? - Why does
SHGetKnownFolderPath
fail when impersonating? - Why can't I use
SHSetKnownFolderPath
to change the location of FOLDERID_LocalAppData
? - How do I programmatically add a folder to my Documents library?
- Why doesn't
SHGetFileInfo
give me customized folder icons? - How can I detect that a shell item refers to a virtual folder, or to a file system inside a file?
- Why is there a limit of 15 shell icon overlays?
- The case of the
SHGetFolderPath(CSIDL_COMMON_DOCUMENTS)
that returned ERROR_PATH_NOT_FOUND
- Why is the
HSHELL_WINDOWDESTROYED
notification raised when a window is hidden, even if it hasn't been destroyed? - Why am I receiving
HCNE_UPDATEDIR
notifications that my code never generates? - Why am I receiving
SHCNE_UPDATEDIR
notifications that my code never generates? - How can I get the original target of a shortcut without applying any 32-bit adjustments?
- How does Explorer calculate the “Date” of a file?
Uncategorized COM Stuff
- The macros for declaring and implementing COM interfaces
- An introduction to COM connection points
- Dispatch interfaces as connection point interfaces
- Adjustor thunks
- What is the underlying object behind a COM interface pointer?
- How to turn off the exception handler that COM "helpfully" wraps around your server
- Shortcuts are serializable objects, which means that they can be stored in places other than just a file
- Why does
IFileOperation
skip junctions even though I passed FOFX_NOSKIPJUNCTIONS
? - Nasty gotcha:
STGM_READ | STGM_WRITE
does not grant read/write access - How can I get the list of programs the same way that Programs and Features gets it?
- How do I obtain the computer manufacturer's name via C++? (
IWbemClassObject
) - The stream pointer position in
IDataObject::GetData
and IDataObject::GetDataHere
is significant - The sad implementation history of COM component categories and why it means you have to click twice to see your newly-installed taskbar toolbar
- How do I request that my out-of-process COM server run unelevated?
- How can a desktop app use a Windows Runtime object that infers UI context from its thread? The
IInitializeWithWindow
pattern ( IInitializeWithWindow
) - How do I protect myself against a COM call that can hang? I'm already running the server out-of-process.
- What can I do about timer build-up when waiting for COM outbound calls to complete?
- Manipulating the positions of desktop icons
- A reminder about the correct way of accessing and manipulating the position of icons on the desktop
- The oracle always tells the truth, even when it is wrong: COM method calls with a user-defined type as a return value (on problems of COM interfaces called from C code)
- Notes on COM aggregation: Obtaining a pointer to your aggregated partner without introducing a reference cycle
- Notes on COM aggregation: How do you implement tear-offs in an aggregated object?
- The theory behind the
IHttpFilter
interface
Memoria
- Stupid memory-mapping tricks
- Creating a shared memory block that can grow in size
- Why do I have to pass a valid page protection value to
VirtualAlloc
even if it ignores it? - How can I include/exclude specific memory blocks in user-mode crash dumps?
-
IsBadXxxPtr
should really be called CrashProgramRandomly ( IsBadWritePtr()
et al.) - A closer look at the stack guard page
- The case of the stack overflow exception when the stack is nowhere near overflowing
- How to allocate address space with a custom alignment or in a custom address region
Input and Output
- Mount points, volumes, and physical drives, oh my!
- What's the difference between an asynchronous
PIPE_WAIT
pipe and a PIPE_NOWAIT
pipe? - Be careful when redirecting both a process's
stdin
and stdout
to pipes, for you can easily deadlock - Looking at the problem at the wrong level: Closing a process's
stdin
-
ReadDirectoryChangesW
reads directory changes, but what if the directory doesn't change? - How do
FILE_FLAG_SEQUENTIAL_SCAN
and FILE_FLAG_RANDOM_ACCESS
affect how the operating system treats my file? - I used
FILE_FLAG_SEQUENTIAL_SCAN
but it didn't seem to speed up my sequential scanning - You can use an
OVERLAPPED
structure with synchronous I/O, too - We're currently using
FILE_FLAG_NO_BUFFERING
and FILE_FLAG_WRITE_THROUGH
, but we would like our WriteFile
to go even faster - On using
ILE_FLAG_WRITE_THROUGH
and FILE_FLAG_NO_BUFFERING
for memory-mapped files - On the interaction between the
FILE_FLAG_NO_BUFFERING
and FILE_FLAG_WRITE_THROUGH
flags - Why does my synchronous overlapped
ReadFile
return FALSE
when the end of the file is reached? - Why does
SetFileValidData
fail even though I enabled the SE_MANAGE_VOLUME_NAME
privilege? - Is
GENERIC_ALL
equivalent to GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE
? -
CancelIoEx
can cancel I/O on console input, which is kind of nice -
CancelIoEx
can cancel synchronous I/O, which is kind of nice - Why does
IsPathRelative
return FALSE
for paths that are drive-relative? - The security check happens at the acquisition of the handle
- Taking a shortcut: You can query properties from a volume, and it will forward to the physical drive
- https://devblogs.microsoft.com/oldnewthing/20201023-00/?p=104395
- How do I disassociate a thread from an I/O completion port?
- Is it okay to call
MapViewOfFile
on the same mapping handle simultaneously from different threads? - What are these dire multithreading consequences that the
GetFullPathName
documentation is trying to warn me about? - How can I force a
WriteFile
or ReadFile
to complete synchronously or hang, in order to test something? - How can I perform a
CopyFile
, but also flush the file buffers before the destination handle is closed?
Asynchronous Input and Output
- Developing the method for taking advantage of the fact that the
OVERLAPPED
associated with asynchronous I/O is passed by address - Ready... cancel... wait for it! (part 1)
- Ready... cancel... wait for it! (part 2)
- Ready... cancel... wait for it! (part 3)
- If you're waiting for I/O to complete, it helps if you actually have an I/O to begin with
- Why does my asynchronous I/O complete synchronously?
- If an asynchronous I/O completes synchronously, is the
hEvent
in the OVERLAPPED
structure signaled anyway? - You can use an
OVERLAPPED
structure with synchronous I/O, too - Why does my synchronous overlapped
ReadFile
return FALSE
when the end of the file is reached? - If I issue a second overlapped I/O operation without waiting for the first one to complete, are they still guaranteed to complete in order?
- Why are my file write operations synchronous, even though I opened the file as
FILE_FLAG_OVERLAPPED
? - File-extending writes are not always synchronous, which is entirely within the contract
- Why you might need additional control over the secret event hiding inside the file object
- Why doesn't my asynchronous read operation complete when I close the handle?
- The mental model for
StartThreadpoolIo
- How can I force a
WriteFile
or ReadFile
to complete synchronously or hang, in order to test something? - If I issue multiple overlapped I/O requests against the same region of a file, will they execute in the order I issued them?
- What are the potentially-erroneous results if you don't pass
NULL
as the lpNumberOfBytesRead
when issuing overlapped I/O?
Files and Directories
- The Definitive Guide on Win32 to NT Path Conversion
- How can I tell that a directory is really a recycle bin?
- How can I tell that a directory is weird and should be excluded from the user interface?
- How do I get information about the target of a symbolic link?
- How do I access a file without updating its last-access time?
- How do I show the contents of a directory while respecting the user's preferences for hidden and super-hidden files as well as the user's language preferences?
- You can use a file as a synchronization object, too
- How can I append to a file and know where it got written, even if the file is being updated by multiple processes?
- The
FILE_FLAG_DELETE_ON_CLOSE
flag applies to the handle, also known as the file object, which is not the same as the file - How long do I have to keep the
SECURITY_ATTRIBUTES
and SECURITY_DESCRIPTOR
structures valid after using them to create a file? - How do I create a directory where people can create subdirectories but cannot mess with those created by other users?
- How can I tell whether a file is on a removable drive, a fixed drive, or a remote drive?
- How can I tell whether a file is on an SSD?
- Why does a non-recursive
ReadDirectoryChangesW
still report files created inside subdirectories? - The early history of Windows file attributes, and why there is a gap between System and Directory
- Even if you open a file with GUID, you can still get its name, or at least one of its names (
GetFinalPathNameByHandle()
) - How do I get from a file path to the volume that holds it?
- How do I get from a volume to the physical disk that holds it?
- Renaming a file is a multi-step process, only one of which is changing the name of the file
- How can I recognize file systems that don't support 64-bit unique file identifiers?
- How can I recognize whether two handles refer to the same underlying file?
ACL
- The
MoveSecurityAttributes
policy affects only how Explorer recalculates ACLs when a file is moved; everybody else is on their own - How to create a folder that inherits its parent's ACL, and then overrides part of it
Security Permissions, Attributes and Identifiers
- The security check happens at the acquisition of the handle
- What is the default security descriptor?
- How do I convert a SID between binary and string forms?
- What are these SIDs of the form
S-1-15-2-xxx
? - What are these SIDs of the form
S-1-15-3-xxx
? - An easy way to determine whether you have a particular file permission
- What are the access rights and privileges that control changing ownership of an object?
- How do the names in the file security dialog map to access control masks?
- If you ask for
STANDARD_RIGHTS_REQUIRED
, you may as well ask for the moon - A user's SID can change, so make sure to check the SID history
- Detecting whether a SID is well-known SID
- SIDs are really just another a fancy way of creating unique IDs in a decentralized way
- What's the point of giving my unnamed object proper security attributes since unnamed objects aren't accessible outside the process anyway (or are they?)
- Is a SID with zero subauthorities a valid SID? It depends whom you ask
- What's the difference between duplicating the handle to a token and duplicating a token?
- I called
AdjustTokenPrivileges
, but I was still told that a necessary privilege was not held - I called
AdjustTokenPrivileges
, but I was still told that a necessary privilege was not held, redux - The history of the
EncodePointer
function for obfuscating pointers - Additional helpful pseudo-handles: The process token, the thread token, and the effective token
- How can I tell whether my process is running as SYSTEM?
- A brief summary of the various versions of the Security Descriptor Definition Language (SDDL)
- How do I free the pointers returned by functions like
GetTokenInformation
? - A clarification on the multithreading constraints of the
EncryptMessage
function
Registro
- Beware of non-null-terminated registry strings
- The performance cost of reading a registry key
- So how bad is it that I'm calling
RegOpenKey
instead of RegOpenKeyEx
? - If I simply want to create a registry key but don't intend to do anything else with it, what security access mask should I ask for?
- How can I programmatically inspect and manipulate a registry hive file without mounting it?
- Why doesn't
RegSetKeySecurity
propagate inheritable ACEs, but SetSecurityInfo
does? - Why does
RegNotifyChangeKeyValue
stop notifying once the key is deleted? - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don't support it? part 1 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don't support it? part 2 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don't support it? part 3 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don't support it? part 4 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don't support it? part 5 - The history of passing a null pointer as the key name to
RegOpenKeyEx
- On the failed unrealized promise of
RegOverridePredefKey
(ie don't use it.)
Strings and Locales
-
TEXT
vs. _TEXT
vs. _T
, and UNICODE
vs. _UNICODE
- The sad history of Unicode
printf
-style format specifiers in Visual C++ - Nasty gotcha:
SetThreadUILanguage
cannot be used to restore the thread UI language - How can
CharUpper
and CharLower
guarantee that the uppercase version of a string is the same length as the lowercase version? (use LCMapStringEx()
in any new code) - Is there a code page that matches ASCII and can round trip arbitrary bytes through Unicode?
- A consequence of being the first to adopt a standard is that you may end up being the only one to adopt it: The sad story of Korean jamo
- The
activeCodePage
manifest element can be used for more than just setting UTF-8 as the active code page - Feel free to stop using
IMultiLanguage2::DetectInputCodepage
- On the proper care and feeding of the enigmatic
GetDistanceOfClosestLanguageInList
function - How can I get
WideCharToMultiByte
to convert strings encoded in UTF-16BE?
NT Services
- Calling
ShutdownBlockReasonCreate
from my service doesn't stop the user from shutting down - What does it mean when my attempt to stop a Windows NT service fails with
ERROR_BROKEN_PIPE
? - How can I configure my Windows NT service to autostart when the system gains Internet access?
- On the confusing names for the Windows service SID types
Sin categoría
- How do I determine the processor's cache line size? (
GetLogicalProcessorInformation()
) - Why are structure sizes checked strictly?
- What's the difference between
CreateMenu
and CreatePopupMenu
? - Why are
HANDLE
return values so inconsistent? - How to retrieve text under the cursor (mouse pointer)
- How to detect programmatically whether you are running on 64-bit Windows
- A timed context menu
- The importance of passing the
WT_EXECUTELONGFUNCTION
flag to QueueUserWorkItem
- If your callback fails, it's your responsibility to set the error code
- The double-click time tells the window manager how good your reflexes are
- The cursor isn't associated with a window or a window class; it's associated with a thread group
- Menu item states are not reliable until they are shown because they aren't needed until then
- How can I display a live screenshot of a piece of another application?
- Converting from a UTC-based
SYSTEMTIME
directly to a local-time-based SYSTEMTIME
- Programmatically uploading a file to an FTP site
- How can you use both versions 5 and 6 of the common controls within the same module?
- How can I tell if Windows Update is waiting for the system to reboot?
- How do I call
SetTimer
with a timer ID that is guaranteed not to conflict with any other timer ID? - A window can't have two timers with the same ID, so how do I assign an ID that nobody else is using?
- What does it mean when a display change is temporary?
- How do I obtain the comment for a share?
- How accurate are the various Windows time-querying functions?
- How can I detect whether the user is logging off?
- Why are timer IDs and dialog control IDs 64-bit values on 64-bit Windows? Did you really expect people to create more than 4 billion timers or dialog controls?
- If you suppress GDI+ background thread, then you are expected to pump messages yourself
- If one program blocks shutdown, then all programs block shutdown (
WM_QUERYENDSESSION
, WM_ENDSESSION
) - When I ask the
GetIpAddrTable
function to sort the results, how are they sorted? - How can I detect that the system is no longer showing a UAC prompt? (
EVENT_SYSTEM_DESKTOPSWITCH
) - How can I get the number of processors in the system, when there are more than 64?
- Why are some system functions exported as stubs instead as forwarders?
- How can I check whether the user has disconnected from the session?
- Why does
PF_VIRT_FIRMWARE_ENABLED
return false even when virtualization is enabled in the firmware? - How can I convert between IANA time zones and Windows registry-based time zones?
- The focus rectangle says, “I'm not orange. I'm just drawn that way.”
- Why does the precise point at which I get a stack overflow exception change from run to run? (structured exception handling aka SEH)
- How do I programmatically reposition monitors in a multiple-monitor system? (
ChangeDisplaySettingsEx()
) - How do I upgrade a 32-bit tick count to a 64-bit one?
- The error code you get might not be the one you want
- How can I find out which processor architectures are supported via emulation by the current system?
- How can I detect whether the system has a keyboard attached? On the
GetRawInputDeviceList
function - Filtering out fake keyboards from the
GetRawInputDeviceList
function - How expensive is
PssCaptureSnapshot
? How fast is it? How much memory does it consume? - What is the
CreateExplorerShellUnelevatedTask
scheduled task? - Under what conditions can I modify the memory that I received in the form a
STGMEDIUM
? - Is it true that raising a structured exception from a structured exception handler terminates the process?
- Why are many Windows user interface elements positioned at multiples of 4 or 8 pixels? (DPI,
DEVICE_SCALE_FACTOR
) - A history of the
fd_set
, FD_SETSIZE
, and how it relates to WinSock - How can I detect programmatically whether Windows is an N or KN version?
- How should I interpret the various values of
NLM_CONNECTIVITY
? - How can I find out the last time a user logged on from C++?
- How can I specify icons for my app to use on the Start menu in high contrast mode?
- How can I add an environment variable to a process launched via
ShellExecuteEx
or IContextMenu
? - Functions that return the size of a required buffer generally return upper bounds, not tight bounds