顯示具有 MFC 標籤的文章。 顯示所有文章
顯示具有 MFC 標籤的文章。 顯示所有文章

2016年6月29日 星期三

MFC AfxBeginThread 使用方法

1.在主要functino的class中使用CWinThread宣告Thread指標。
class CMFCApplication1Dlg : public CDialogEx
{
public:
   CMFCApplication1Dlg(CWnd* pParent = NULL); // 標準建構函式
   CWinThread* pThread;
// 對話方塊資料
#ifdef AFX_DESIGN_TIME
   enum { IDD = IDD_MFCAPPLICATION1_DIALOG };
#endif

   protected:
   virtual void DoDataExchange(CDataExchange* pDX);
   ...
// 程式碼實作
protected:
   ...
}

2.定義MyThread(),必將要執行的工作寫在裡面,可搭配
在 MFC 上使用lusb-win32】一文中提到的Console _cprintf來觀察是否有進入MyThread()。
UINT MyThread(LPVOID LParam)
{
   _cprintf("Start MyThread...\n");
   ...
   while(1){
      _cprintf("Hello World!\n");
   }
   return(0);
}

3.在欲開啟MyThread的Dialog按鈕程式碼中創建Thread
void CMFCApplication1Dlg::OnBnClickedButton1()
{
   pThread = AfxBeginThread(MyThread, NULL);
   ...
}

4.使用TerminateThread關閉MyThread
void CMFCApplication1Dlg::OnBnClickedButton2()
{
   // TODO: 在此加入控制項告知處理常式程式碼
   TerminateThread(pThread->m_hThread, 0);
   _cprintf("Close MyThread............\n");

}


執行結果:
當按下Button1後,會一直執行MyThread()中的「_cprintf("Hello World!\n");」,按下Button2後可以看到確實將MyThread()給關掉,Console不再印出Hello World!!字串。

在 MFC 上使用lusb-win32

將lusb-win32導入MFC專案步驟:
1.建立MFC專案後,將"libusb.lib"與"libusb0.dll"丟到所建立的專案目錄下。
2.在標頭檔中加入"lusb0_usb.h"檔案,加入"#pragma comment(lib, "libusb")"至"lusb0_usb.h"或是專案主程式XXX.cpp中來link libusb.lib。
3.在專案主程式XXX.cpp中include "lusb0_usb.h"後,就可以開始撰寫你要的功能了。


MFC(VS2015 Community)中的Console printf
1.添加標頭檔
#include "io.h"
#include "fcntl.h"
#include "conio.h"

2.新增InitConsoleWindow()至主程式中
void InitConsoleWindow()
{
  int nCrt = 0;
  FILE* fp;
  AllocConsole();
  nCrt = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE),   _O_TEXT);
  fp = _fdopen(nCrt, "w");
  *stdout = *fp;
  setvbuf(stdout, NULL, _IONBF, 0);
}

3.在::OnInitDialog()初始化函數中添加InitConsoleWindow()
BOOL CUsbXSTM32F4xxDlg::OnInitDialog()
{
  CDialog::OnInitDialog();

  ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
  ASSERT(IDM_ABOUTBOX < 0xF000);

  CMenu* pSysMenu = GetSystemMenu(FALSE);
  if (pSysMenu != NULL)
  {
    ...
  }

  SetIcon(m_hIcon, TRUE); // 設定大圖示
  SetIcon(m_hIcon, FALSE); // 設定小圖示
  InitConsoleWindow();

  return TRUE; // 傳回 TRUE,除非您對控制項設定焦點
}

4.由於VS2015使用網路上printf的方式無法輸出到console上,有另外找到解決方法,加入"conio.h"用_cprintf可以解決無法輸出到console上的問題。