Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Как взять выделенные файлы из listBox? / 7 сообщений из 7, страница 1 из 1
08.01.2013, 14:17
    #38102152
tur91
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как взять выделенные файлы из listBox?
В listBox я вывожу файлы, которые нужно затем выбирать произвольными группами.
Свойство SelectionMode у listBox поставил в MultiExtended чтобы можно было собирать их через Ctrl+MouseLeft. Событие у listBox выставлено Click. Но обратиться к выделенным файлам не удается, т.к. Selected оказывается только первый файл, хотя закрашена группа. Что делать?

Есть свойство SelectedItems, но неясно как его использовать, т.к. выделенным оказывается всегда только первый item. Может быть я что то не так делаю..
...
Рейтинг: 0 / 0
08.01.2013, 14:29
    #38102164
vkg
vkg
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как взять выделенные файлы из listBox?
tur91,

Код: c#
1.
2.
3.
4.
5.
6.
string s_CurentItem;

for (int i = 0; i < MylistBox.SelectedItems.Count; i++)
  {
     s_CurentItem = MylistBox.SelectedItems[i].ToString();
  }
...
Рейтинг: 0 / 0
08.01.2013, 16:44
    #38102280
tur91
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как взять выделенные файлы из listBox?
vkg,

В Form1_Load так выставляю MultiExtended

this->listBox1->SelectionMode = SelectionMode::MultiExtended;

В событии под листбоксом

private: System::Void listBox1_Click(System::Object^ sender, System::EventArgs^ e) {
int sel_items = listBox1->SelectedItems->Count;
}

при этом как бы я не выделял айтемы (выделение реально, видимо) sel_items всегда равно 1
...
Рейтинг: 0 / 0
08.01.2013, 17:14
    #38102301
vkg
vkg
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как взять выделенные файлы из listBox?
tur91vkg,

В Form1_Load так выставляю MultiExtended

this->listBox1->SelectionMode = SelectionMode::MultiExtended;

В событии под листбоксом

private: System::Void listBox1_Click(System::Object^ sender, System::EventArgs^ e) {
int sel_items = listBox1->SelectedItems->Count;
}

при этом как бы я не выделял айтемы (выделение реально, видимо) sel_items всегда равно 1

1. как бы не выделял или не выделал??? :)

2. может расскажешь толком что тебе надо?
...
Рейтинг: 0 / 0
08.01.2013, 18:24
    #38102363
tur91
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как взять выделенные файлы из listBox?
vkg, спасибо за отклик.

У меня в листбоксе много файлов, которые надо выделять группами, ну и запускать дальше.
Я на С++ пишу, не на C#

Я сделал для листбокса событие Click, думал так лучше будет, но тогда в нем, т.е. в этой процедуре события

Код: plaintext
1.
2.
3.
private: System::Void listBox1_Click(System::Object^  sender, System::EventArgs^  e) {
	       int sel_items = listBox1->SelectedItems->Count;
}



sel_items всегда равен 1. Т.е. при любых выделениях мышкой групп файлов. Понятно? Т.е. не реагирует SelectedItems на выделение, выдает всегда только первый элемент группы.

Проблему решил так: перешел на событие SelectedIndexChanged, тогда все работает и sel_items соответствует числу выделенных файлов.

Также все работает под кликом кнопки. Не работает только под кликом листбокса.
Ну кто бы мог подумать что такое возможно.

Еще раз спасибо за отклик.

А вообще у меня еще есть вопросы и мне очень нужна помощь. Для меня это первая программа на WF С++. А опыт программирования только в матлабе, так что я ноль.

Наверное завтра задам свои вопросы.
...
Рейтинг: 0 / 0
09.01.2013, 21:44
    #38104146
tur91
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как взять выделенные файлы из listBox?
Сделал я на WF C++ первую простую программку мини-эксплорер
http://www.radikal.ru][IMG] http://s13.radikal.ru/i186/1301/0b/36dfff885b91.png [/IMG]
Весь код в Form1.h, ну и еще при клике на файле (или группе файлов) вызывается openfile.cpp
Весь код прилагаю в конце, может кому-нибудь интересно.

А вопрос у меня такой.
Когда я программировал на матлабе, то вначале каждой программки писал
h = miniexplorer(ver, [2033 880 180 600 50], flagtools);
т.е. вызывал это окошко с файлами и кнопками. Имена всех событий известны, т.е. далее создавал файл с именем события и писал в нем что надо. Это все. Кода эксплорера скрыт, все события открыты под листом файлов и каждой кнопкой. Все было удобно.
Теперь в С++ хотелось бы иметь нечто подобное, т.е. одной строчкой вызывать этот мини-эксплорер. Т.е. желательно это делать кодом, без обращения к дизайнеру формы.
Вроде бы теперь нужно весь мой код свернуть в ActiveX, но я не нашел в своем VC 2010 года возможность открыть ActiveX библиотеки MFC
Вот здесь http://msdn.microsoft.com/ru-ru/library/yc13as7d.aspx
авторВ диалоговом окне Новый проект выберите значок Элемент управления ActiveX библиотеки MFC
У меня стандартный VC 2010, но этого в диалоговом окне не нахожу. В чем дело?
Может быть можно обойтись без ActiveX? Скажем будет где то лежать этот код и я его просто буду вызывать одной строчкой, но как это сделать?

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
// openfile.cpp
#include "stdafx.h"

using namespace System;

public ref class open_files
{
  public: static void openfiles(array<String^>^ mypath)
  {

  }
};

// Form1.h
#pragma once
#include "openfile.cpp"

namespace miniexp {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
	using namespace System::IO;

	/// <summary>
	/// Summary for Form1
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: Add the constructor code here
			//
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}
	//========= 1 ====================================================================
	private: Microsoft::VisualBasic::Compatibility::VB6::DriveListBox^  driveListBox1;
	private: Microsoft::VisualBasic::Compatibility::VB6::DirListBox^  dirListBox1;	
	private: System::Windows::Forms::ListBox^  listBox1;						
	private: System::Windows::Forms::Button^  button1;									
	private: System::Windows::Forms::Button^  button2;							
	private: System::Windows::Forms::Button^  button3;								
	private: System::Windows::Forms::Button^  button4;								
	//========= 2 ====================================================================
	protected: 
		String^ readini()
		{
			String^ progpath = this->dirListBox1->Path + "\\inipath.txt";
			StreamReader^ din = File::OpenText(progpath);
			String^ inipath = din->ReadLine();
			din->Close();
			return inipath;
		}
		void writeini(String^ dirpath)
		{
		   String^ progpath = Directory::GetCurrentDirectory() + "\\inipath.txt";
		   StreamWriter^ sw = gcnew StreamWriter(progpath);
		   sw->WriteLine(dirpath);
		   sw->Close();
		}
		String^ getshortname(String^ fullpath)
		{
		int i, n = fullpath->Length-1;
		for(i = n; i > 0; i--)
			if(fullpath[i] == '\\')
				break;

		String^ temp = fullpath->Substring(i+1,n-i);

		return temp;
		}
		array<String^>^ getshortnames(array<String^>^ arraypath)
		{
			array<String^>^ shortnames = gcnew array<String^>(arraypath->Length);
			for (int i = 0; i < arraypath->Length; i++)
				shortnames[i] = getshortname(arraypath[i]);
			return shortnames;
		}
		String^ getnewpath(String^ strpath, int index)
		{
			int i(0), ind(-1), n = strpath->Length-1;
			for(i = 0; i < n; i++)
			  if(strpath[i] == '\\')
			  {
				  ind++;
				  if (ind == index)
					  break;
			  }

			String^ newpath = strpath->Substring(0,i+1);
			return newpath;
		}
		int indlastopen(String^ strpath)
		{
			int i(0), ind(0), n = strpath->Length-1;
			for(i = 0; i < n; i++)
			  if(strpath[i] == '\\')
				  ind++;

			return ind;
		}
		String^ dirlist_after_click(array<String^>^ folders, int SelectedIndex, String^ currentpath)
		{
			int ind = indlastopen(currentpath);
			String^ newpath;
			if (ind < SelectedIndex)
				newpath = currentpath + "\\" + folders[SelectedIndex];
			else
				if (ind == SelectedIndex)
					newpath = currentpath;
				else
					newpath = getnewpath(currentpath, SelectedIndex);

			return newpath;
		}
		array<String^>^ get_list_fullpath_selected_files()
		{
			 int nfiles = this->listBox1->SelectedItems->Count;
			 array<String^>^ files = gcnew array<String^>(nfiles);
			 array<String^>^ pathfiles = gcnew array<String^>(nfiles);
			 for (int i = 0; i < nfiles; i++)
			 {
			   files[i] = this->listBox1->SelectedItems[i]->ToString();
			   pathfiles[i] = this->dirListBox1->Path + "\\" + files[i];
			 }
			 return pathfiles;
		}
	//========= end 2 ===============================================================
	
	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			this->driveListBox1 = (gcnew Microsoft::VisualBasic::Compatibility::VB6::DriveListBox());
			this->dirListBox1 = (gcnew Microsoft::VisualBasic::Compatibility::VB6::DirListBox());
			this->listBox1 = (gcnew System::Windows::Forms::ListBox());
			this->button1 = (gcnew System::Windows::Forms::Button());
			this->button2 = (gcnew System::Windows::Forms::Button());
			this->button3 = (gcnew System::Windows::Forms::Button());
			this->button4 = (gcnew System::Windows::Forms::Button());
			this->SuspendLayout();
			// 
			// driveListBox1
			// 
			this->driveListBox1->FormattingEnabled = true;
			this->driveListBox1->Location = System::Drawing::Point(0, 1);
			this->driveListBox1->Name = L"driveListBox1";
			this->driveListBox1->Size = System::Drawing::Size(175, 21);
			this->driveListBox1->TabIndex = 2;
			this->driveListBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::driveListBox1_SelectedIndexChanged);
			this->driveListBox1->Click += gcnew System::EventHandler(this, &Form1::driveListBox1_SelectedIndexChanged);
			// 
			// dirListBox1
			// 
			this->dirListBox1->FormattingEnabled = true;
			this->dirListBox1->IntegralHeight = false;
			this->dirListBox1->Location = System::Drawing::Point(0, 25);
			this->dirListBox1->Name = L"dirListBox1";
			this->dirListBox1->Size = System::Drawing::Size(175, 240);
			this->dirListBox1->TabIndex = 1;
			this->dirListBox1->Click += gcnew System::EventHandler(this, &Form1::dirListBox1_Click);
			// 
			// listBox1
			// 
			this->listBox1->FormattingEnabled = true;
			this->listBox1->Location = System::Drawing::Point(0, 268);
			this->listBox1->Name = L"listBox1";
			this->listBox1->SelectionMode = System::Windows::Forms::SelectionMode::MultiExtended;
			this->listBox1->Size = System::Drawing::Size(175, 446);
			this->listBox1->TabIndex = 5;
			this->listBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::listBox1_SelectedIndexChanged);
			// 
			// button1
			// 
			this->button1->Location = System::Drawing::Point(3, 719);
			this->button1->Name = L"button1";
			this->button1->Size = System::Drawing::Size(39, 23);
			this->button1->TabIndex = 0;
			this->button1->Text = L"= 1 =";
			this->button1->UseVisualStyleBackColor = true;
			this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
			// 
			// button2
			// 
			this->button2->Location = System::Drawing::Point(48, 719);
			this->button2->Name = L"button2";
			this->button2->Size = System::Drawing::Size(39, 23);
			this->button2->TabIndex = 6;
			this->button2->Text = L"= 2 =";
			this->button2->UseVisualStyleBackColor = true;
			this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
			// 
			// button3
			// 
			this->button3->Location = System::Drawing::Point(92, 719);
			this->button3->Name = L"button3";
			this->button3->Size = System::Drawing::Size(39, 23);
			this->button3->TabIndex = 7;
			this->button3->Text = L"= 3 =";
			this->button3->UseVisualStyleBackColor = true;
			this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
			// 
			// button4
			// 
			this->button4->Location = System::Drawing::Point(137, 719);
			this->button4->Name = L"button4";
			this->button4->Size = System::Drawing::Size(39, 23);
			this->button4->TabIndex = 8;
			this->button4->Text = L"= 4 =";
			this->button4->UseVisualStyleBackColor = true;
			this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(177, 743);
			this->Controls->Add(this->button4);
			this->Controls->Add(this->driveListBox1);
			this->Controls->Add(this->dirListBox1);
			this->Controls->Add(this->listBox1);
			this->Controls->Add(this->button1);
			this->Controls->Add(this->button2);
			this->Controls->Add(this->button3);
			this->Location = System::Drawing::Point(50, 313);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);

		}
#pragma endregion
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
				this->listBox1->SelectionMode = SelectionMode::MultiExtended;
		 		this->Text = "ViewRaw";
				this->StartPosition = FormStartPosition::Manual;
				this->Left = 2370; this->Top = 100; this->Width = 185; this->Height = 770;
				
				String^ inipath = readini(); dirListBox1->Path = inipath; 

				array<String^>^ pathfiles = Directory::GetFiles(inipath);
				array<String^>^ shortnamefiles = getshortnames(pathfiles);
				listBox1->Items->Clear(); listBox1->Items->AddRange(shortnamefiles);
			 }
	private: System::Void driveListBox1_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e) {
			 String^ drivepath = driveListBox1->Text->Substring(0,2) + "\\";
			 this->dirListBox1->Path = drivepath;
			 array<String^>^ pathfiles = Directory::GetFiles(drivepath);
				array<String^>^ shortnamefiles = getshortnames(pathfiles);
				this->listBox1->Items->Clear();
				this->listBox1->Items->AddRange(shortnamefiles);
		 }
	private: System::Void dirListBox1_Click(System::Object^  sender, System::EventArgs^  e) {
		   int nitems = this->dirListBox1->Items->Count;
		   array<String^>^ folders = gcnew array<String^>(nitems);
		   for (int i = 0; i < nitems; i++)
		     folders[i] = this->dirListBox1->Items[i]->ToString();

		   int SelectedIndex = this->dirListBox1->SelectedIndex;
		   String^ currentpath = dirListBox1->Path;
		   String^ dirpath = dirlist_after_click(folders, SelectedIndex, currentpath);
		   dirListBox1->Path = dirpath; writeini(dirpath);

		   array<String^>^ arraypath = Directory::GetFiles(dirpath);
		   array<String^>^ shortnames = getshortnames(arraypath);
		   listBox1->Items->Clear(); listBox1->Items->AddRange(shortnames);
		 }
	private: System::Void listBox1_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e) {
			 array<String^>^ pathfiles = get_list_fullpath_selected_files();
			 open_files::openfiles(pathfiles);
		 }
	private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
			 }
	private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
		 }
	private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
		 }
	private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e) {
		 }
	};
}
...
Рейтинг: 0 / 0
09.01.2013, 21:49
    #38104148
tur91
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как взять выделенные файлы из listBox?
Забыл добавить картинку
...
Рейтинг: 0 / 0
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Как взять выделенные файлы из listBox? / 7 сообщений из 7, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]