More cautious image creation

This commit is contained in:
Robinson 2021-02-07 00:14:43 +01:00
parent e09faaf491
commit 1b3f66703f
2 changed files with 57 additions and 43 deletions

View File

@ -34,6 +34,8 @@ import com.sun.jna.ptr.PointerByReference;
public class HBITMAPWrap extends HBITMAP { public class HBITMAPWrap extends HBITMAP {
private static final Object lockObject = new Object();
// NOTE: This is a field (instead of private) so that GC does not try to collect this object // NOTE: This is a field (instead of private) so that GC does not try to collect this object
private HBITMAP bitmap; private HBITMAP bitmap;
@ -42,6 +44,9 @@ public class HBITMAPWrap extends HBITMAP {
HBITMAP createBitmap(BufferedImage image) { HBITMAP createBitmap(BufferedImage image) {
int w = image.getWidth(null); int w = image.getWidth(null);
int h = image.getHeight(null); int h = image.getHeight(null);
// all sorts of issues occur if this is called quickly from different threads!
synchronized(lockObject) {
HDC screenDC = User32.GetDC(null); HDC screenDC = User32.GetDC(null);
HDC memDC = GDI32.CreateCompatibleDC(screenDC); HDC memDC = GDI32.CreateCompatibleDC(screenDC);
HBITMAP hBitmap = null; HBITMAP hBitmap = null;
@ -92,6 +97,7 @@ public class HBITMAPWrap extends HBITMAP {
GDI32.DeleteDC(memDC); GDI32.DeleteDC(memDC);
} }
} }
}
BufferedImage img; BufferedImage img;

View File

@ -27,6 +27,7 @@ import dorkbox.jna.windows.structs.ICONINFO;
* http://www.pinvoke.net/default.aspx/user32.createiconindirect * http://www.pinvoke.net/default.aspx/user32.createiconindirect
*/ */
public class HICONWrap extends HICON { public class HICONWrap extends HICON {
private static final Object lockObject = new Object();
static HICON createIconIndirect(HBITMAP bm) { static HICON createIconIndirect(HBITMAP bm) {
ICONINFO info = new ICONINFO(); ICONINFO info = new ICONINFO();
@ -35,9 +36,16 @@ public class HICONWrap extends HICON {
info.ColorBitmap = bm; info.ColorBitmap = bm;
HICON hicon = User32.CreateIconIndirect(info); HICON hicon = User32.CreateIconIndirect(info);
if (hicon == null) {
// something weird is going on! Try again but more carefully!
synchronized(lockObject) {
hicon = User32.CreateIconIndirect(info);
}
if (hicon == null) { if (hicon == null) {
throw new GetLastErrorException(); throw new GetLastErrorException();
} }
}
return hicon; return hicon;
} }