2012-02-21 28 views
0

我爲Windows創建了一個文件選擇器,它返回給我一個選定的文件路徑。我想讀取給定的文件,但我不知道如何將文件路徑傳遞給正確的函數。如何將文件路徑(文本框值)傳遞給C++中的文件讀取函數?

文件Form1.h我有一個按鈕動作和它裏面我可以得到openFileDialog1->FileName但我不知道怎麼這個變量傳遞給readFile()功能main.cpp文件裏。

我創建了一個方法返回的路徑:

System::String^ filePath; 
....  
    private: System::String^ getPath() { return filePath; } 

這裏是文件拾荒者代碼:

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { 
       Stream^ myStream; 
       OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog; 

       openFileDialog1->InitialDirectory = "c:\\"; 
       openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
       openFileDialog1->FilterIndex = 2; 
       openFileDialog1->RestoreDirectory = true; 

       if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK){ 
       if ((myStream = openFileDialog1->OpenFile()) != nullptr){ 
       // Insert code to read the stream here. 
       textBox1->Text = openFileDialog1->FileName; //text box displays the chosen path 

        myStream->Close(); 
       } 
       } 
     } 

變量被設置按鈕點擊:

private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { 
      filePath = textBox1->Text; 
     } 

如何在我的main.cpp中調用返回方法:

#include "stdafx.h" 
#include "Form1.h" 

using namespace main; 
using namespace std; 

[STAThreadAttribute] 
int main(array<System::String ^> ^args) 
{ 
    // Enabling Windows XP visual effects before any controls are created 
    Application::EnableVisualStyles(); 
    Application::SetCompatibleTextRenderingDefault(false); 

    // Create the main window and run it 
    Application::Run(gcnew Form1()); 

    System::String^ p1 = /*Something missing her?*/getPath1(); //I am guessing it should look like this... 
    return 0; 
} 

回答

1

在一個公共屬性在Form1類把文件名(公共領域,如果這是你喜歡什麼)(或者讓你的getPath()方法public),則:

Form1^ form = gcnew Form1(); 
Application::Run(form); 
String^ p1 = form->FileName; 
相關問題