Wednesday, March 23, 2011

How to embed a Java control on a C# winforms control?

Can I put a Java control (SWT, Swing, ...) on a C# control?

I know it's possible with web controls but I don't like this way.

From stackoverflow
  • Check out the IKVM project. Its a Java Virtual Machine implemented in .net which allows java and .net interoperability.

    Not sure exactly how complete it is and if it enables the functionality you require buts its worth a look.

  • I've rechecked that, looks like IKVM currently hasn't enough support in it's AFT assembly. I think the only way to do what you need is run you java control inside separate process with hidden main window and pass handle of that control to your C# application somehow.

    Original answer:

    I'm not sure if you can just "add" it, but you can try this direction:

    It would be necessary to convert java classes to .Net assemblies via IKVM.

    1. First of all you need to get handle of java control. You can look at this post if you need info on how to do this. I failed at this step because I haven't found Win32DrawingSurface and DrawingSurfaces in IKVM's libraries, maybe it's enough to just create some static getHandle() method on the java side.

    2. Get handle of your parent C# control. It's simple since Control have its Handle property.

    3. After obtaining both handles you can set one of the as parent to another. To do this you need to call SetParent function from the WINAPI.

      [DllImport("user32.dll")] private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

  • If the control is not a custom control and is just something in swing you may find it available in Microsoft's Visual J# (either Version 2.0 or the supplemental add in for 1.1

    Note that a J# Swing control will not play ball dropped in a WinForms app directly, you may need to provide a host control which delegates all painting to copying the image from a hidden J# Control placed within a simple j# Form (also hidden where the form's view area is resized to match the view area of the host control. This would at least remove the need for a separate process. This usage has several limitations, I suspect that the control you want to use is complex (or you would just have reimplemented it).

    Note that J# is officially dying (no more serious maintenance) and will officially not bother to support it at all in 2015. Expect using it to cause you considerable pain in the long term but if you really need some part of it this might help.

  • I wrote examples:
    - Java component embedding in .NET GUI,
    - .NET WinForm Component embedding in Java GUI.
    You can find them in the products:[id]95126[SiteID][id]98653[SiteID]

  • You can use JNBridge to do it.


Post a Comment