CSDN博客

img HighTech

一个典型的例子解决常见的高级Windows程序设计问题

发表于2003/3/6 9:10:00  675人阅读


//#######################################################################################
// Copyright(c) Vision Technologies 2002 All Rights Reserved.
//
// Project Name:  FileInspector RT
// Software Version 1.0
//
// ----------------------------------------------------------
//
// File Name:   FileInspector.h
// Function:   Define of Classes
// Created Time:  28th Dec, 2002
//  Author:    HighTech Young
//
// ----------------------------------------------------------
//
//  Revidion Time:  
//  Revision By:  
// Revision Contents: 
//
//#######################################################################################

#include "resource.h"
#include "stdafx.h"
#include "afxmt.h"

//---------------------------------------------------------------------------------------
//
// COMMENTS: Define of applacation class 
//
//---------------------------------------------------------------------------------------

class CMyApp : public CWinApp
{
public:
    virtual BOOL InitInstance ();
};

//---------------------------------------------------------------------------------------
//
// COMMENTS: Define of mainwindow class
//
//---------------------------------------------------------------------------------------

class CMainWindow : public CWnd
{
 //
 // Declare all objects of interface
 //
private:
 CStatic    m_FiTip;
 CButton    m_GroupBoxFI;
 CEdit    m_ObjectPath;
 CButton    m_Browse;

 CButton    m_GroupBoxFS;
 CStatic    m_FsTip;
 CEdit    m_ObjectSize;
 CButton    m_GB;
 CButton    m_MB;
 CButton    m_KB;
 CButton    m_Byte;

 CButton    m_OK;
 CButton    m_Cancel;
 CButton    m_Exit;

public:
    CMainWindow ();

 BOOL boolWndHadShow; // Window display indicator

protected:
 CEvent m_eventStopWatch;// CEvent object for synchonize thread

 virtual void PostNcDestroy();

 //
 // Message handler declare
 //
 afx_msg int OnCreate(LPCREATESTRUCT lpcs);
    afx_msg void OnSysCommand(UINT nID, LPARAM lParam);

    afx_msg LRESULT OnMyIconNotify(WPARAM wParam, LPARAM lParam);
 afx_msg LRESULT OnShowAppIconic(WPARAM wParam, LPARAM lParam);
 afx_msg void OnClose();

 afx_msg void OnBrowseButonClicked();
 afx_msg void OnObjectPathChanged();
 afx_msg void OnOkButtonClicked();
 afx_msg void OnCancelButtonClicked();
 afx_msg void OnExitButtonClicked();

 afx_msg LONG OnFileChanged(WPARAM wParam, LPARAM lParam);
    DECLARE_MESSAGE_MAP ()
};

//##################################### End of File #######################################

 

//#######################################################################################
// Copyright(c) Vision Technologies 2002 All Rights Reserved.
//
// Project Name:  FileInspector RT
// Software Version 1.0
//
// ----------------------------------------------------------
//
// File Name:   FileInspector.cpp
// Function:   Implementation of the class
// Created Time:  28th Dec, 2002
//  Created by:   HighTech Young
//
// ----------------------------------------------------------
//
//  Revidion Time:  
//  Revision By:  
// Revision Contents: 
//
//#######################################################################################

#include "FileInspector.h"

//---------------------------------------------------------------------------------------
//
// COMMENTS:  GLOBE DEFINATION AREA
//
//---------------------------------------------------------------------------------------

//
// User defined message for callback function
//

#define USER_WM_NOTIFYICON    WM_USER + 0x001

//
// User defined message for display icon on statue bar of windows
//

#define USER_WM_SHOWAPPICONIC   WM_USER + 0x002 

//
// User defined message for file change notification
//

#define WM_USER_THREAD_FILE_CHANGED  WM_USER + 0x003

//
// The structure was defined for the input of thread function parameters
//

typedef struct tagTHREADPARAM
{
 HWND hWnd;
 CEvent *pEvent;
}THREADPARAM;

//
// Worker thread function declare
//

UINT ThreadFunction(LPVOID pParam);

//---------------------------------------------------------------------------------------
//
// COMMENTS: MESSAGE MAP of CMainWindow class
//
//---------------------------------------------------------------------------------------

BEGIN_MESSAGE_MAP (CMainWindow, CWnd)
 ON_WM_CREATE()
 ON_MESSAGE(USER_WM_NOTIFYICON,OnMyIconNotify)
 ON_MESSAGE(USER_WM_SHOWAPPICONIC,OnShowAppIconic)
 ON_WM_SYSCOMMAND()
 ON_WM_CLOSE()

 ON_BN_CLICKED(IDC_BROWSE,OnBrowseButonClicked)
 ON_EN_CHANGE(IDE_OBJ_PATH,OnObjectPathChanged)
 
 ON_BN_CLICKED(IDC_OK,OnOkButtonClicked)
 ON_BN_CLICKED(IDE_OBJ_PATH,OnObjectPathChanged)
 ON_BN_CLICKED(IDC_EXIT_FI,OnExitButtonClicked)

 ON_MESSAGE(WM_USER_THREAD_FILE_CHANGED,OnFileChanged)
END_MESSAGE_MAP ()

//
// defination of application object
//

CMyApp myApp;

//---------------------------------------------------------------------------------------
//
// FUNCTION: BOOL CMyApp::InitInstance ()
// PURPOSE:  CMyApp member functions
// COMMENTS:
//
//---------------------------------------------------------------------------------------

BOOL CMyApp::InitInstance ()
{
    m_pMainWnd = new CMainWindow;

   m_pMainWnd->ShowWindow (m_nCmdShow);
    m_pMainWnd->UpdateWindow ();

 //
 // Send MYWM_SHOWAPPICONIC so that the window can be
 // hide after programe runed and the icon should be
 // displayed on the statue area of task bar
 //

 m_pMainWnd -> PostMessage( USER_WM_SHOWAPPICONIC );
    return TRUE;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: CMainWindow::CMainWindow ()
// PURPOSE:  The constructor of the CMainWindow class
// COMMENTS:
//
//---------------------------------------------------------------------------------------

CMainWindow::CMainWindow ():
 m_eventStopWatch(FALSE,TRUE)
{
 //
 // Register a WNDCLASS.
 //

 CString strWndClass = AfxRegisterWndClass (
        CS_DBLCLKS,          // Class style
        AfxGetApp ()->LoadStandardCursor (IDC_ARROW),   // Class cursor
        (HBRUSH) (COLOR_3DFACE + 1),     // Background brush
  AfxGetApp ()->LoadIcon( IDR_FILE_INSPECTOR)  // Class icon
    );

 //
 // Create a window.
 //

 CreateEx (0, strWndClass, _T ("File/Folder Supervisor"),
        WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
        NULL, NULL);

 //
 // Size the window.
 //
  
 CRect rect (80,70, 452, 400);
    CalcWindowRect (&rect);

    SetWindowPos (NULL, 0, 0, rect.Width (), rect.Height (),
        SWP_NOZORDER | SWP_NOMOVE | SWP_NOREDRAW);

}

//---------------------------------------------------------------------------------------
//
// FUNCTION: int CMainWindow::OnCreate(LPCREATESTRUCT lpcs)
// PURPOSE:  Create GUI of Programe
// COMMENTS:
//
//---------------------------------------------------------------------------------------

int CMainWindow::OnCreate(LPCREATESTRUCT lpcs)
{
 if(CWnd::OnCreate(lpcs) == -1)
  return -1;

 //
 // Object selected groupe box
 //

 m_GroupBoxFI.Create (_T (" Supervised Target:"),
      WS_CHILD|BS_GROUPBOX| WS_VISIBLE,
      CRect(10,10,360,115),
      this,
      IDC_GROUPBOX_FI);
 m_FiTip.Create(_T("Please select the file or folder which you want to ask the File/Folder Supervisor supervise."),
       WS_CHILD|WS_VISIBLE,
       CRect(25,35,350,75),
       this,
       IDS_FI_TIP);
 m_ObjectPath.Create(WS_CHILD|WS_VISIBLE|WS_BORDER|ES_AUTOHSCROLL,
      CRect(25,80,260,100),
      this,
      IDE_OBJ_PATH);
 m_Browse.Create(_T("Browse.."),
     WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,
     CRect(265,80,350,100),
     this,
     IDC_BROWSE);
 //
 // File size limitation config box
 //

 m_GroupBoxFS.Create (_T ("File Size Limitation:"),
      WS_CHILD |BS_GROUPBOX| WS_VISIBLE,
      CRect(10,120,360,280),
      this,
      IDC_GROUPBOX_FS);
 m_FsTip.Create( _T("The Folder or File size must be less than:"),
     WS_CHILD|WS_VISIBLE,
       CRect(25,145,350,165),
       this,
       IDS_FS_TIP);
 m_ObjectSize.Create(WS_CHILD|WS_VISIBLE|WS_BORDER|ES_AUTOHSCROLL,
      CRect(30,170,100,190),
      this,
      IDE_OBJ_SIZE);

 m_GB.Create (_T("GB"),
    WS_CHILD|WS_GROUP|WS_VISIBLE|BS_AUTORADIOBUTTON,
    CRect(110,170,150,190),
    this,
    IDC_GB);
 m_MB.Create (_T("MB"),
   WS_CHILD|WS_VISIBLE|BS_AUTORADIOBUTTON,
   CRect(155,170,195,190),
   this,
   IDC_MB);
 m_KB.Create (_T("KB"),
   WS_CHILD|WS_VISIBLE|BS_AUTORADIOBUTTON,
   CRect(200,170,240,190),
   this,
   IDC_GB);
 m_Byte.Create (_T("Byte"),
   WS_CHILD|WS_VISIBLE|BS_AUTORADIOBUTTON,
   CRect(245,170,325,190),
   this,
   IDC_BYTE);
 m_KB.SetCheck (BST_CHECKED);

 //
 // Buttons
 //

 m_OK.Create(_T("Start"),
  WS_CHILD|WS_GROUP|BS_DEFPUSHBUTTON| WS_VISIBLE,
  CRect(50,290,150,315),
  this,
  IDC_OK);
 m_Cancel.Create(_T("Cancel"),
  WS_CHILD|BS_PUSHBUTTON| WS_VISIBLE,
  CRect(155,290,255,315),
  this,
  IDC_CANCEL);
 
 m_Cancel.EnableWindow(FALSE);

 m_Exit.Create(_T("Stop"),
  WS_CHILD|BS_PUSHBUTTON| WS_VISIBLE,
  CRect(260,290,360,315),
  this,
  IDC_EXIT_FI);

 return 0;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: void CMainWindow::PostNcDestroy()
// PURPOSE:  PostNcDestroy will be used for delete the window
// COMMENTS:
//
//---------------------------------------------------------------------------------------

void CMainWindow::PostNcDestroy()
{
 delete this;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: BOOL MyTaskBarAddIcon(HWND hwnd,UINT uID, HICON hicon, LPSTR lpszTip)
// PURPOSE:  Add icon in the statu area on the task bar
// COMMENTS:
//
//---------------------------------------------------------------------------------------

BOOL MyTaskBarAddIcon(HWND hwnd,UINT uID, HICON hicon, LPSTR lpszTip)
{
    BOOL bResult;
 
 NOTIFYICONDATA tnid;
  tnid.cbSize = sizeof(NOTIFYICONDATA);
  tnid.hWnd = hwnd;
  tnid.uID = uID;    
  tnid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
  tnid.uCallbackMessage = USER_WM_NOTIFYICON;  // Callback message
  tnid.hIcon = hicon;        // Icon used
   
 if (lpszTip)
  lstrcpyn(tnid.szTip, lpszTip, sizeof(tnid.szTip));
    else        
  tnid.szTip[0] = '/0'; 

 //
 // Send NIM_ADD to create icon
 //

 bResult = Shell_NotifyIcon(NIM_ADD, &tnid);
 
 if (hicon) DestroyIcon(hicon);

 return bResult;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: BOOL MyTaskBarDeleteIcon(HWND hwnd, UINT uID)
// PURPOSE:  DELETE icon in the statu area on the task bar
// COMMENTS:
//
//---------------------------------------------------------------------------------------

BOOL MyTaskBarDeleteIcon(HWND hwnd, UINT uID)

 BOOL bResult;
    NOTIFYICONDATA tnid;
  tnid.cbSize = sizeof(NOTIFYICONDATA);
  tnid.hWnd = hwnd;
  tnid.uID = uID;

 //
 //Send NIM_DELETE to create icon
 //

 bResult = Shell_NotifyIcon(NIM_DELETE, &tnid);

 return bResult;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: LRESULT CMainWindow::OnMyIconNotify( WPARAM wParam, LPARAM lParam )
// PURPOSE:  Call back function of message MYWM_NOTIFYICON
// COMMENTS:
//
//---------------------------------------------------------------------------------------

LRESULT CMainWindow::OnMyIconNotify( WPARAM wParam, LPARAM lParam )
{
    UINT nID;
 UINT uMouseMsg;
 nID = (UINT)wParam;
    uMouseMsg = (UINT) lParam;
 
 //
 // Show or hide window
 //
 
 if (uMouseMsg == WM_LBUTTONDOWN) // Click on icon
 {
  if ( boolWndHadShow )
   ShowWindow( SW_HIDE );
  else
   ShowWindow( SW_SHOWNORMAL );
  
  boolWndHadShow = ~boolWndHadShow;
 }
 return TRUE;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION:
//   LRESULT CMainWindow::OnShowAppIconic( WPARAM wParam, LPARAM lParam )
// PURPOSE:
//   Message handler of show icon on statu bar
//   and hide the window when programe run
// COMMENTS:
//   Call back function of message MYWM_SHOWAPPICONIC
//
//---------------------------------------------------------------------------------------

LRESULT CMainWindow::OnShowAppIconic( WPARAM wParam, LPARAM lParam )
{
 HICON theIcon = LoadIcon(AfxGetInstanceHandle(),
       MAKEINTRESOURCE(IDR_FILE_INSPECTOR) );
 MyTaskBarAddIcon(GetSafeHwnd(),
      100,
      theIcon,
      _T("File/Folder Supervisor"));
 ShowWindow( SW_HIDE );
 boolWndHadShow = FALSE;
 return 1;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: void CMainWindow::OnClose()
// PURPOSE:
//   When you want to close programe, the icon should
//   be delete from statue area on task bar,
//   We can use WM_CLOSE message and message handler to do this
// COMMENTS:
//
//---------------------------------------------------------------------------------------

void CMainWindow::OnClose()
{
 //
 // Add your message handler code here and/or call default
 //
 
 MyTaskBarDeleteIcon( GetSafeHwnd(), 100 );
 CWnd::OnClose();
}

//---------------------------------------------------------------------------------------
//
// FUNCTION:
//  void CMainWindow::OnSysCommand( UINT nID, LPARAM lParam )
// PURPOSE:
//  When window were minimumized, the window should be hide,
//  we use ON_SYSCOMMAND message and message handle to do this
// COMMENTS:
//
//---------------------------------------------------------------------------------------
void CMainWindow::OnSysCommand( UINT nID, LPARAM lParam )
{
 if ( nID==SC_MINIMIZE  )
 {
  ShowWindow( SW_HIDE );
  boolWndHadShow = FALSE;
 }
 else
  CWnd::OnSysCommand( nID, lParam );
}


//---------------------------------------------------------------------------------------
//
// FUNCTION: void CMainWindow::OnBrowseButonClicked ()
// PURPOSE:  Message handler of OK button
// COMMENTS:
//
//---------------------------------------------------------------------------------------
void CMainWindow::OnBrowseButonClicked ()
{

 //
 //  Must call IMalloc::Free to free the memory by this pointer
 //
 
 LPMALLOC pMalloc;
 BROWSEINFO bi;
 char pszDirName[MAX_PATH];// Save the directory name
 LPITEMIDLIST pidl;

 //
 // If retrieve a handle to the Shell allocator's IMalloc interface sucessfuly
 //
 
 if (SUCCEEDED(SHGetMalloc(&pMalloc)))
 {
  ZeroMemory(&bi,sizeof(bi));
  bi.hwndOwner = GetSafeHwnd();
  bi.pidlRoot = NULL;
  bi.pszDisplayName = pszDirName;
  bi.lpszTitle = _T("Select the file or folder which will be Supervised:");
  bi.ulFlags = BIF_BROWSEINCLUDEFILES;
  bi.lpfn = NULL;
  bi.lParam = 0;
  if ((pidl = ::SHBrowseForFolder(&bi)) != NULL)
  {
   //
   // Get full path user selected
   //
   
   if (::SHGetPathFromIDList(pidl, pszDirName))
   m_ObjectPath.SetWindowText(pszDirName);
  }
  pMalloc->Free(pidl);
  pMalloc->Release();
 }
  
  //
  // Try to detect the inspect object is directory or file
  // Can also use:
  // DWORD GetFileAttributes(LPCTSTR lpFileName);
  //
  
  DWORD ObjectType;  
  ObjectType = GetFileAttributes(pszDirName);
  if(ObjectType & FILE_ATTRIBUTE_DIRECTORY)
  {
   m_GroupBoxFI.SetWindowText (_T("Folder Supervised:"));
   m_GroupBoxFS.SetWindowText (_T("Folder Size Limitation"));
  }
  else
  {
   m_GroupBoxFI.SetWindowText (_T("File Supervised:"));
   m_GroupBoxFS.SetWindowText (_T("File Size Limitation"));
  }
  
  //
  //Enable the Cancel button
  //
   m_Cancel.EnableWindow(TRUE);
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: void CMainWindow::OnOkButtonClicked ()
// PURPOSE:  Message handler of OK button
// COMMENTS:
//  This function transfer a structure's pointer
//  as a LPVOID parameter to worker thread. this is the normal way
//  to handle the worker thread parameters. Besides, you can also
//  input a address of an object directly.
//
//---------------------------------------------------------------------------------------

void CMainWindow::OnOkButtonClicked ()
{
  m_Cancel.EnableWindow( FALSE );
  ShowWindow( SW_HIDE );
  boolWndHadShow = FALSE;
  
  //
  // Reset the manual event object before start worker thread
  //

  m_eventStopWatch.ResetEvent ();

  //
  // Prepare the parameter for worker thread
  // sometimes if you only need m_hWnd, you can also
  // input &m_hWnd directly there
  //

  THREADPARAM * pThreadParam=new THREADPARAM;
  pThreadParam->hWnd= m_hWnd;     // Message target
  pThreadParam->pEvent = &m_eventStopWatch; // Event to stop thread
  
  //
  // Start File Inspector thread.
  //
  
  AfxBeginThread(ThreadFunction, pThreadParam);
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: void CMainWindow::OnCancelButtonClicked ()
// PURPOSE:  Message handler of Cancel button
// COMMENTS:
//
//---------------------------------------------------------------------------------------

void CMainWindow::OnCancelButtonClicked ()
{
  ShowWindow( SW_HIDE );
  boolWndHadShow = FALSE;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: void CMainWindow::OnExitButtonClicked ()
// PURPOSE:  Message handler of Exit button
// COMMENTS:
//
//---------------------------------------------------------------------------------------

void CMainWindow::OnExitButtonClicked ()
{
  ShowWindow( SW_HIDE );
  boolWndHadShow = FALSE;
  
  m_eventStopWatch.SetEvent();

  //
  // Close the window
  //
  
  PostMessage (WM_CLOSE,0,0);
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: void CMainWindow::OnObjectPathChanged ()
// PURPOSE:  Message handler of Object Path changed
// COMMENTS:
//
//---------------------------------------------------------------------------------------

void CMainWindow::OnObjectPathChanged ()
{
 m_Cancel.EnableWindow(TRUE);
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: UINT ThreadFunction(LPVOID pParam)
// PURPOSE:  Worker thread Function
// COMMENTS:
//
//---------------------------------------------------------------------------------------

UINT ThreadFunction(LPVOID pParam)
{
 //
 // Unbound the parameters
 //

 THREADPARAM *pThreadParam = (THREADPARAM * ) pParam;
 HWND  hWnd = pThreadParam -> hWnd;
 CEvent  *pEvent = pThreadParam -> pEvent;
 
 //delete pThreadParam;
 delete pThreadParam;

 DWORD dwWaitStatus;  
 HANDLE *dwChangeHandles=new HANDLE[3];

 //
 // Use this event handle to stop the thread
 //

 dwChangeHandles[2] = pEvent->m_hObject;

 //
 // Watch the C:/ directory for file creation and deletion.
 //
 
 dwChangeHandles[0] = FindFirstChangeNotification(
      "C://",       // directory to watch
      FALSE,       // do not watch the subtree
      FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes

 //
 // Watch the D:/ subtree for directory creation and deletion.
 //
 
 dwChangeHandles[1] = FindFirstChangeNotification(
      "D://",                        // directory to watch
      TRUE,                          // watch the subtree
      FILE_NOTIFY_CHANGE_DIR_NAME);  // watch dir. name changes

 while (TRUE)
 {
 
 /*--------------------------------------------------------------------------
  Examples:
   Here is the examples if you want to use WaitForSingleObject
   to imply the function.
  
  //
  // Check if user want to Exit File Inspector.
  // Please make sure that the second parameter of
  // WaitForSingleObject is 0, and in this case the
  // first parameter must be manual event.
  // WaitForSingleObject will check the first parameter,
  // if it is signaled,the loop will break.
  //
  
  if(WaitForSingleObject(pEvent->m_hObject,0)==WAIT_OBJECT_0)
   return (UINT) -1;

  WaitForSingleObject(dwChangeHandles[1],INFINITE);
  PostMessage (hWnd,WM_USER_THREAD_FILE_CHANGED,0,0);
  FindNextChangeNotification(dwChangeHandles);
 ---------------------------------------------------------------------------*/
  
  //
  // Wait for notification.
  //
  
  dwWaitStatus = WaitForMultipleObjects(3, dwChangeHandles,
             FALSE, INFINITE);
  if (dwWaitStatus == WAIT_OBJECT_0 + 2) return (UINT) -1;          

  switch (dwWaitStatus)
   {
   case WAIT_OBJECT_0:
   
    //
    // A file was created or deleted in C:/WINDOWS.
    // Refresh this directory and restart the
    // change notification. RefreshDirectory is an
    // application-defined function.
    //
    
    PostMessage (hWnd,WM_USER_THREAD_FILE_CHANGED,0,0);
    FindNextChangeNotification(dwChangeHandles[0]);
    break;

   case WAIT_OBJECT_0 + 1:
   
    //
    // A directory was created or deleted in C:/.
    // Refresh the directory tree and restart the
    // change notification. RefreshTree is an
    // application-defined function.
    //

     PostMessage (hWnd,WM_USER_THREAD_FILE_CHANGED,0,0);
    FindNextChangeNotification( dwChangeHandles[1]);
    break;
   }
  }
 

 delete[] dwChangeHandles;
 return 0;
}

//---------------------------------------------------------------------------------------
//
// FUNCTION: LONG CMainWindow::OnFileChanged(WPARAM wParam, LPARAM lParam)
// PURPOSE:
// COMMENTS:
//---------------------------------------------------------------------------------------

LONG CMainWindow::OnFileChanged(WPARAM wParam, LPARAM lParam)
{
 //
 // Add process sentence if file changed here.
 //

 return 0;
}

//##################################### End of File #######################################

阅读全文
0 0

相关文章推荐

img
取 消
img