首页 > 解决方案 > 将 Matplotlib 嵌入 HWND

问题描述

在网上搜索了一段时间之后,似乎可以将 Python 嵌入到 tkinter、qt5 等中。但是,我想知道是否可以简单地将其嵌入到 Windows 应用程序中。与 Jupyter 嵌入的方式类似%matplotlib inline,我想知道 Window 应用程序是否可以使用类似的功能。

#include <Windows.h>
#include <stdio.h>
#include <python.h>

LPARAM CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
  switch (msg) {
  default:
    return DefWindowProc(hwnd, msg, wparam, lparam);
  }
}

#pragma comment(linker, "/SUBSYSTEM:CONSOLE /ENTRY:WinMainCRTStartup")
#pragma warning(suppress: 28251) // Inconsistent Annotation Suppression
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR lpCmdLine, int nCmdShow)
{
  WNDCLASSEX wc = {};

  wc.lpszClassName = "customWindow";
  wc.hInstance = hInstance;
  wc.lpfnWndProc = WndProc;
  wc.cbSize = sizeof(WNDCLASSEX);
  wc.hCursor = LoadCursor(NULL, IDC_ARROW);

  RegisterClassEx(&wc);

  HWND hwnd = CreateWindow("customWindow", "Testing embedded matplotlib", WS_OVERLAPPEDWINDOW, 100, 100, 1000, 1000, NULL, NULL, hInstance, NULL);
  UpdateWindow(hwnd);
  ShowWindow(hwnd, SW_SHOW);

  Py_Initialize();

  const char* code =
    R"(
import matplotlib.pyplot as plt
import numpy as np

plt.plot(np.sin(np.linspace(0, 100, 1000)))
plt.show()
)";

  PyRun_SimpleString(code);

  Py_Finalize();

  MSG message;
  while (GetMessage(&message, NULL, 0, 0) > 0)
  {
    TranslateMessage(&message);
    DispatchMessage(&message);
  }

  return static_cast<int>(message.wParam);
}

在这个不完整的示例中(单独的 matplotlib 窗口单独打开),我想弄清楚是否可以将 matplotlib 的窗口重新设置为主 hwnd。理想情况下,我希望仍然具有 matplotlib 的交互性,因此尝试从内部 matplotlib 缓冲区执行 bitblt 对我来说是不可行的。

标签: pythonc++matplotlibwinapiembed

解决方案


推荐阅读