问题
I am dealing with some old drawing code used to draw parts of styled system controls in a WinFroms app. One of the core routines that does this work looks like the following:
private bool DrawTheme(Graphics graphics, XPThemeClasses themeClass, int themePart, int themeState, int x, int y, int width, int height)
{
bool myResult;
IntPtr myHdc = graphics.GetHdc();
try
{
NativeMethods.RECT myRect = new NativeMethods.RECT(x, y, width, height);
IntPtr myThemeData = GetThemeData(themeClass);
if (NativeMethods.IsThemeBackgroundPartiallyTransparent(myThemeData, themePart, themeState))
{
IntPtr hwnd = NativeMethods.WindowFromDC(myHdc);
int res = NativeMethods.DrawThemeParentBackground(hwnd, myHdc, ref myRect);
}
myResult = (0 <= NativeMethods.DrawThemeBackground(
myThemeData,
myHdc,
themePart,
themeState,
ref myRect, ref myRect));
}
catch
{
myResult = false;
}
finally
{
graphics.ReleaseHdc(myHdc);
}
return myResult;
}
It turned out that the DrawThemeParentBackground function fails. It returns the error code 0x80070006 (E_HANDLE), which means 'Handle that is not valid'. It seems, this occurs because of the zero window handle retrieved with the prior WindowFromDC API call.
Is there a way to obtain the correct hwnd from the Graphics object passed to this function to pass it to DrawThemeParentBackground
? I know I can pass the handle of the window to draw in from the outer calling code, but this would require rewriting of a big part of the infrastructure of this project. So I am searching for a simple solution of this problem without rewriting much code.
来源:https://stackoverflow.com/questions/56393760/getting-hwnd-for-uxtheme-dll-drawthemeparentbackground-from-a-graphics-object