Win32 C++: метод создания и вызова из отдельного файла C++

Я новичок в программировании Win32 на С++, и мне нужна помощь, чтобы выяснить, как включать методы в другие файлы в мое приложение Win32 на С++. Я хочу написать методы в других файлах и включить их в свой код. Я хочу, чтобы отдельный файл openFile, содержащий метод, который вызывается из OpenWordGUI, возвращал бы путь к файлу. Это возможно?

В настоящее время мой код выглядит следующим образом:

// OpenWordDocGUI.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "OpenWordDocGUI.h"

#define MAX_LOADSTRING 100
//Defines for buttons
#define TSP_BUTTON 1
#define PCM_BUTTON 2
#define GO_BUTTON 3
//Defines Text boxes
#define TSP_BOX 101
#define PCM_BOX 102

//For text box
HWND TSPBox;
HWND PCMBox;


// Global Variables:
HINSTANCE hInst;                                // current instance
TCHAR szTitle[MAX_LOADSTRING];                  // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name

//Globals for 
TCHAR szFilters[] = _T("Input files (*.*)\0*.*\0\0");
TCHAR szFilePathName[_MAX_PATH] = _T("");
//Store file paths in separate variables
TCHAR TSPFilePath[_MAX_PATH] = _T("");
TCHAR PCMFilePath[_MAX_PATH] = _T("");

int textBoxStat = 0;
TCHAR szInputBoxPathName[_MAX_PATH];

// Forward declarations of functions included in this code module:
ATOM                MyRegisterClass(HINSTANCE hInstance);
BOOL                InitInstance(HINSTANCE, int);
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: Place code here.
    MSG msg;
    HACCEL hAccelTable;

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInstance, IDC_OPENWORDDOCGUI, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow))
    {
        return FALSE;
    }

    hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OPENWORDDOCGUI));

    // Main message loop:
    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_OPENWORDDOCGUI));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = MAKEINTRESOURCE(IDC_OPENWORDDOCGUI);
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND  - process the application menu
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    //Default
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

    // Fill the OPENFILENAME structure for use in
    // TSP/PCM buttons

    OPENFILENAME ofn = {0};
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = hWnd;
    ofn.lpstrFilter = szFilters;
    ofn.lpstrFile = szFilePathName;  // This will hold the file name    
    ofn.lpstrDefExt = _T("dat");
    ofn.nMaxFile = _MAX_PATH;
    ofn.lpstrTitle = _T("Open File");
    ofn.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    //////   
    switch (message)
    {
    case WM_CREATE:
        //TSP MOA Button Creation
        //Will bring up open file dialog when clicked
        CreateWindow(TEXT("button"), TEXT("TSP MOA"),
            WS_VISIBLE | WS_CHILD, 
            10, 10, 80, 25,
            hWnd, (HMENU) TSP_BUTTON, NULL, NULL
            );
        //Window to show Selected TSP MOA
        TSPBox = CreateWindow(TEXT("edit"), TEXT(""), 
            WS_BORDER | WS_CHILD | WS_VISIBLE,
            100, 10, 400, 25,
            hWnd, (HMENU) TSP_BOX,
            NULL, NULL);
        //PCM File Button Creation
        //Will bring up open file dialog when clicked
        CreateWindow(TEXT("button"), TEXT("PCM File"),
            WS_VISIBLE | WS_CHILD, 
            10, 50, 80, 25,
            hWnd, (HMENU) PCM_BUTTON, NULL, NULL
            );
        //Text box for PCM file creation
        PCMBox = CreateWindow(TEXT("edit"), TEXT(""), 
            WS_BORDER | WS_CHILD | WS_VISIBLE,
            100, 50, 400, 25,
            hWnd, (HMENU) PCM_BOX,
            NULL, NULL);
        //Execute compare button
        CreateWindow(TEXT("button"), TEXT("Compare"),
            WS_VISIBLE | WS_CHILD,
            10, 90, 80, 25,
            hWnd, (HMENU) GO_BUTTON, NULL, NULL
            );
    case WM_COMMAND:
        wmId    = LOWORD(wParam);
        wmEvent = HIWORD(wParam);
        // Parse the menu selections:
        switch (wmId)
        {
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        case TSP_BUTTON:
            //TSP Button clicked
            //Open file dialog to select TSP MOA - done
            //
            TSPFilePath = openFile(TSP);
            break;
        case PCM_BUTTON:
            //PCM Button clicked
            //Open file dialog to select PCM file
            PCMFilePath = openFile(PCM);
            break;
        case GO_BUTTON:
            //Execute the following
            //Read TSP MOA
            //TSP MOA to Excel
            //PCM to Excel
            //compare TSP Excel to PCM

            //Do data check
            //Get data from TSP Text box




            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        break;
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        // TODO: Add any drawing code here...
        EndPaint(hWnd, &ps);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}

Openfile будет выглядеть примерно так:

#include <Commdlg.h>
#include <windows.h>

TCHAR* openFile(systemSel)
{
    if (systemSel == "TSP")
        {
            //Set filter for openfile to word docs
        } else {
            //set filter for openfile to excel files
        }
OPENFILENAME ofn ;
TCHAR szFile[MAX_PATH] ;
// open a file name
ZeroMemory( &ofn , sizeof( ofn));
ofn.lStructSize = sizeof ( ofn );
ofn.hwndOwner = NULL  ;
ofn.lpstrFile = szFile ;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof( szFile );
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex =1;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0 ;
ofn.lpstrInitialDir=NULL ;
ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ;
GetOpenFileName( &ofn )
return szFile
}

person user2430267    schedule 19.08.2015    source источник
comment
Конечно, это возможно. С какими проблемами вы на самом деле застряли? Уточните в своем вопросе, пожалуйста.   -  person πάντα ῥεῖ    schedule 19.08.2015
comment
Нам нужно знать, что вы используете для компиляции кода. Вам нужно, чтобы компилятор знал об обоих файлах одновременно.   -  person Jerry Jeremiah    schedule 19.08.2015
comment
Я использую MS Visual Studio 2008.   -  person user2430267    schedule 19.08.2015
comment
Я делал это раньше на С++ и понимаю, что мне нужно использовать заголовочный файл. Думаю, я просто немного запутался в том, как реализовать это в Win32 API. Я пробовал пару раз и не могу заставить его работать.   -  person user2430267    schedule 19.08.2015


Ответы (1)


У вас должен быть заголовочный файл, в котором объявляется функция openFile. Включение этого заголовка в OpenWordDocGUI.cpp делает работу.

В Интернете есть множество руководств, показывающих, как писать собственные файлы заголовков для доступа к функциям в другом файле .cpp.

Например, попробуйте этот: http://www.learncpp.com/cpp-tutorial/19-header-files

person Lukas Thomsen    schedule 19.08.2015