Вопрос

I have an unmanaged DLL which I am communicating with. There is a function that needs a window handle to draw on. However, after some MDI manipulation, form hiding and showing, the handle changes. Unfortunately, I can't give a new handle to the DLL and then System.AccessViolationException raises. Can I use some method to prevent the handle from recreating?

Это было полезно?

Решение

I have an unmanaged DLL which I am communicating with. There is a function that needs a window handle to draw on. However, after some MDI manipulation, form hiding and showing, the handle changes. Unfortunately, I can't give a new handle to the DLL and then System.AccessViolationException raises.

The proper solution would be to handle the HandleCreated event and inform the DLL that the handle has changed. But you say that you can't give a new handle to the DLL. (Why not?)

Can I use some method to prevent the handle from recreating?

No, there is no such method.

The problem is that setting certain properties of the form cause the framework to recreate the underlying window internally, which of course results in your form being associated with a different handle. But this is not a bug, it's working around the fact that certain window style attributes are cached at creation and there is no way to force them to be updated without recreating the window.

So if you want to ensure that the window handle never changes, you have to make sure that you never change any of the properties of the form that cause the framework to recreate its handle.

Armed with something like ILSpy, you can find out exactly which properties/methods those are. The culprits will generally call a method named RecreateHandle (which you could even call yourself in certain cases to achieve a similar effect).

I can't think of another workaround. There's no way to tell Windows to recreate the object with the same handle as the old object.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top