使用的是vs2017和matlab2017a,解決方案平臺是x64。MCR和環境變數都配置好了。
撰寫了一個簡單的.m檔案繪圖,按照網上的教程生成dll檔案進行參考,并且把figure嵌套在c#表單的panel控制元件里顯示。
但是運行的時候一直沒有顯示figure影像,表單還變得很小,也沒有報錯。設定了斷點發現matlab的函式是可以正常呼叫的。
把程式貼在下方,求大佬解答
#region //Windows API
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);//
[DllImport("user32.dll")]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool BRePaint);
const int GWL_STYLE = -16;
const int WS_CAPTION = 0x00C00000;
const int WS_THICKFRAME = 0x00040000;
const int WS_SYSMENU = 0X00080000;
[DllImport("user32")]
private static extern int GetWindowLong(System.IntPtr hwnd, int nIndex);
[DllImport("user32")]
private static extern int SetWindowLong(System.IntPtr hwnd, int index, int newLong);
/// <summary>最大化視窗,最小化視窗,正常大小視窗
/// nCmdShow:0隱藏,3最大化,6最小化,5正常顯示
/// </summary>
//[DllImport("user32.dll", EntryPoint = "ShowWindow")]
//public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
#endregion
public Form1()
{
InitializeComponent();
}
public delegate void UpdateUI();//委托用于更新UI
Thread startload;//執行緒用于matlab表單處理
Class1 cl;
IntPtr figure1;//影像句柄
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
startload = new Thread(new ThreadStart(startload_run));
startload.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
void startload_run()
{
int count50ms = 0;
//實體化matlab物件
cl = new Class1();
cl.drew();
//回圈查找figure1表單
while (figure1 == IntPtr.Zero)
{
//查找matlab的Figure 1表單
figure1 = FindWindow("SunAwtFrame", "Figure 1");
//延時50ms
Thread.Sleep(50);
count50ms++;
//20s超時設定
//if (count50ms >= 400)
//{
// label1.Text = "matlab資源加載時間過長!";
// return;
//}
}
//跨執行緒,用委托方式執行
UpdateUI update = delegate
{
//隱藏標簽
label1.Visible = false;
//設定matlab影像表單的父表單為panel
SetParent(figure1, panel1.Handle);
//獲取表單原來的風格
var style = GetWindowLong(figure1, GWL_STYLE);
//設定新風格,去掉標題,不能通過邊框改變尺寸
SetWindowLong(figure1, GWL_STYLE, style & ~WS_CAPTION & ~WS_THICKFRAME);
//移動到panel里合適的位置并重繪
MoveWindow(figure1, 0, 0, panel1.Width + 20, panel1.Height + 40, true);
//呼叫顯示表單函式,隱藏再顯示相當于重繪一下表單
};
panel1.Invoke(update);
//再移動一次,防止顯示錯誤
Thread.Sleep(100);
MoveWindow(figure1, 0, 0, panel1.Width + 20, panel1.Height + 40, true);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/63482.html
標籤:C#
上一篇:求解答呀
