Форум программистов, компьютерный форум, киберфорум
C++/CLI Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
3 / 3 / 0
Регистрация: 10.06.2012
Сообщений: 31

Изменение цвета listBox в событии Drag and Drop

14.06.2013, 18:07. Показов 1368. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Help me,please!!!))
Суть в чем:
Создайте проект, содержащий 2 списка ListBox и обеспечивающий решение следующих задач:
3. перенос выделенных строк из первого списка и обратно методом DragDrop:
- с клавишами Alt + C происходит копирование строк;
- при переносе из одного списка в другой источник меняет цвет на красный, по окончании переноса на белый;
- при копировании цвет источника меняется на зелёный, по окончании копирования на белый.

Проблема с цветом. Думаю может в MouseDown прописать что при нажатии клавиши CTRL источник закрашивается в зеленый, иначе в красный. А в MouseUp сделать источник снова белым.
C MouseDown проблем не возникло,а вот с MouseUp не знаю что делать,думала просто прописать что listBox становится белым, но не работает. Подскажите,может вообще другой метод есть с изменением цвета,более легкий!
C++
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#pragma once
 
namespace laba8 {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Collections::Generic;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace System::IO;
    using namespace System::Text;
 
    /// <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;
            }
        }
    private: System::Windows::Forms::ListBox^  listBox1;
    protected: 
    private: System::Windows::Forms::ListBox^  listBox2;
    private: System::Windows::Forms::Button^  button1;
    private: System::Windows::Forms::Button^  button2;
    private: System::Windows::Forms::SaveFileDialog^  saveFileDialog1;
    private: System::Windows::Forms::OpenFileDialog^  openFileDialog1;
 
 
 
    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->listBox1 = (gcnew System::Windows::Forms::ListBox());
            this->listBox2 = (gcnew System::Windows::Forms::ListBox());
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->button2 = (gcnew System::Windows::Forms::Button());
            this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog());
            this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog());
            this->SuspendLayout();
            // 
            // listBox1
            // 
            this->listBox1->AllowDrop = true;
            this->listBox1->BackColor = System::Drawing::Color::White;
            this->listBox1->FormattingEnabled = true;
            this->listBox1->Items->AddRange(gcnew cli::array< System::Object^  >(5) {L"Vvjv", L"cjvj", L"wjffvgekjge", L"vfjvjkvkgj", 
                L"rjnfkjfkio"});
            this->listBox1->Location = System::Drawing::Point(12, 60);
            this->listBox1->Name = L"listBox1";
            this->listBox1->Size = System::Drawing::Size(181, 147);
            this->listBox1->TabIndex = 0;
            this->listBox1->DragDrop += gcnew System::Windows::Forms::DragEventHandler(this, &Form1::listBox1_DragDrop);
            this->listBox1->DragEnter += gcnew System::Windows::Forms::DragEventHandler(this, &Form1::listBox1_DragEnter);
            this->listBox1->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &Form1::listBox1_KeyDown);
            this->listBox1->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::listBox1_MouseDown);
            this->listBox1->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::listBox1_MouseUp);
            // 
            // listBox2
            // 
            this->listBox2->AllowDrop = true;
            this->listBox2->FormattingEnabled = true;
            this->listBox2->Location = System::Drawing::Point(274, 60);
            this->listBox2->Name = L"listBox2";
            this->listBox2->Size = System::Drawing::Size(181, 147);
            this->listBox2->TabIndex = 1;
            this->listBox2->DragDrop += gcnew System::Windows::Forms::DragEventHandler(this, &Form1::listBox2_DragDrop);
            this->listBox2->DragEnter += gcnew System::Windows::Forms::DragEventHandler(this, &Form1::listBox2_DragEnter);
            this->listBox2->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &Form1::listBox2_KeyDown);
            this->listBox2->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::listBox2_MouseDown);
            this->listBox2->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::listBox2_MouseUp);
            // 
            // button1
            // 
            this->button1->Location = System::Drawing::Point(195, 60);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(75, 23);
            this->button1->TabIndex = 2;
            this->button1->Text = L"Сохранить";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
            // 
            // button2
            // 
            this->button2->Location = System::Drawing::Point(195, 89);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(75, 23);
            this->button2->TabIndex = 3;
            this->button2->Text = L"Открыть";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
            // 
            // openFileDialog1
            // 
            this->openFileDialog1->FileName = L"openFileDialog1";
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(489, 262);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->button1);
            this->Controls->Add(this->listBox2);
            this->Controls->Add(this->listBox1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->ResumeLayout(false);
 
        }
#pragma endregion
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
             {
                 SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;
                 if(saveFileDialog1->ShowDialog() == Windows::Forms::DialogResult::OK) 
                 {
                     List<System::String^>^ lines = gcnew List<System::String^>();
 
                     for each (System::String^ s in listBox1->Items)
                     {
                         lines->Add(s);
                     }
 
                     File::WriteAllLines("d:\sda.txt", lines);
                 } 
             }
    private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) 
             {
                 listBox2->Items->Clear();            
                 if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
                 {
                     try
                     {
                         StreamReader^ text_r = gcnew StreamReader(openFileDialog1->FileName, Encoding::GetEncoding(1251));
                         while (!text_r->EndOfStream)
                         { listBox2->Items->Add(text_r->ReadLine()); }
                         text_r->Close();
                     }
                     catch (FileLoadException^ q)
                     {
                         MessageBox::Show("Ошибка:\n" + q->Message, "Ошибки Закгрузки", MessageBoxButtons::OK, MessageBoxIcon::Error);
                     }
                 }
             }
    private: System::Void listBox1_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) 
             {
                 listBox2->AllowDrop=true;
                 listBox1->AllowDrop=true;
                 if (listBox1->ModifierKeys == Keys::Control)
                 {
                 this->listBox1->BackColor = System::Drawing::Color::Green;
                 }
                 else
                 {
                     this->listBox1->BackColor = System::Drawing::Color::Red;
                 }
                 
                 if(listBox1->SelectedIndex==-1)
                 {
                     listBox2->AllowDrop=false;
                 }
                 ((ListBox^)sender)->AllowDrop=false;
                 DoDragDrop(((ListBox^)sender)->Text, DragDropEffects::Copy|DragDropEffects::Move);
             }
    private: System::Void listBox2_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) 
             {
                 listBox2->AllowDrop=true;
                 listBox1->AllowDrop=true;
                 if (listBox2->ModifierKeys == Keys::Control)
                 {
                 this->listBox2->BackColor = System::Drawing::Color::Green;
                 }
                 else
                 {
                     this->listBox2->BackColor = System::Drawing::Color::Red;
                 }
                 
                 if(listBox2->SelectedIndex==-1)
                 {
                     listBox1->AllowDrop=false;
                 }
                 ((ListBox^)sender)->AllowDrop=false;
                 DoDragDrop(((ListBox^)sender)->Text, DragDropEffects::Copy|DragDropEffects::Move);
             }
    private: System::Void listBox1_DragEnter(System::Object^  sender, System::Windows::Forms::DragEventArgs^  e) 
             {
                 e->Effect=DragDropEffects::None;
                 if(e->Data->GetDataPresent(DataFormats::StringFormat))
                 {
                     if((e->KeyState&8)==8)
                     {
                         e->Effect=DragDropEffects::Copy;
                     }
                     else
                     {
                         e->Effect=DragDropEffects::Move;
                     }
                 }
             }
    private: System::Void listBox2_DragEnter(System::Object^  sender, System::Windows::Forms::DragEventArgs^  e) 
             {
                 e->Effect=DragDropEffects::None;
                 if(e->Data->GetDataPresent(DataFormats::StringFormat))
                 {
                     if((e->KeyState&8)==8)
                     {
                         e->Effect=DragDropEffects::Copy;
                     }
                     else
                     {
                         e->Effect=DragDropEffects::Move;
                     }
                 }
             }
    private: System::Void listBox1_DragDrop(System::Object^  sender, System::Windows::Forms::DragEventArgs^  e) 
             {
                 listBox1->Items->Add(e->Data->GetData(DataFormats::StringFormat)->ToString());
                 if((e->Effect & DragDropEffects::Move)==DragDropEffects::Move)
                 {
                     if(((ListBox^)sender)->Name=="listBox1")
                     {
                         this->listBox1->BackColor = System::Drawing::Color::White;
                         if(this->listBox2->SelectedIndex!=-1) 
                         {
                             this->listBox2->Items->Remove(this->listBox2->SelectedItem);
                         }
                     }
                     else 
                     {
                         if(this->listBox1->SelectedIndex!=-1) 
                         {
                             this->listBox1->Items->Remove(this->listBox1->SelectedItem);
                         }
                     }
                 }
                 this->listBox1->BackColor = System::Drawing::Color::White;
                this->listBox2->BackColor = System::Drawing::Color::White;
             }
    private: System::Void listBox2_DragDrop(System::Object^  sender, System::Windows::Forms::DragEventArgs^  e) 
             {
                 listBox2->Items->Add(e->Data->GetData(DataFormats::StringFormat)->ToString());
 
                 if((e->Effect & DragDropEffects::Move)==DragDropEffects::Move)
                 {
                     if(((ListBox^)sender)->Name=="listBox2")
                     { 
                         if(this->listBox1->SelectedIndex!=-1) 
                         {
                             this->listBox1->Items->Remove(this->listBox1->SelectedItem);
                         }
                     }
                     else 
                     {
                         if(this->listBox2->SelectedIndex!=-1) 
                         {
                             this->listBox2->Items->Remove(this->listBox2->SelectedItem);
                         }
                     }
                 }
                 this->listBox1->BackColor = System::Drawing::Color::White;
                this->listBox2->BackColor = System::Drawing::Color::White;
              }
    private: System::Void listBox1_KeyDown(System::Object^  sender, System::Windows::Forms::KeyEventArgs^  e) 
         {
             if(this->listBox1->SelectedIndex!=-1) 
                 {
                     if(e->KeyValue ==46) 
                 {
                     this->listBox1->Items->Remove(this->listBox1->SelectedItem);
                 }
                 }
         }
    private: System::Void listBox2_KeyDown(System::Object^  sender, System::Windows::Forms::KeyEventArgs^  e) 
         {
             if(this->listBox2->SelectedIndex!=-1) 
                 {
                     if(e->KeyValue ==46) 
                 {
                     this->listBox2->Items->Remove(this->listBox2->SelectedItem);
                 }
                 }
         }
    private: System::Void listBox1_MouseUp(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) 
         {
              this->listBox1->BackColor = System::Drawing::Color::White;
                this->listBox2->BackColor = System::Drawing::Color::White;
         }
    private: System::Void listBox2_MouseUp(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) 
         {
              this->listBox1->BackColor = System::Drawing::Color::White;
                this->listBox2->BackColor = System::Drawing::Color::White;
         }
};
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
14.06.2013, 18:07
Ответы с готовыми решениями:

Drag&Drop в MS Visual Studio
Есть задача. Нужно создать игровое поле 4х4, и реализировать перетаскивание обэктов(игрових фишек). В кого какие идеи???

Событие Drag and Drop в Windows forms C++
Help me,please!!!)) Суть в чем: Создайте проект, содержащий 2 списка ListBox и две кнопки Button и обеспечивающий решение следующих...

Drag&Drop, возможность перемещать элементы по форме
Здравствуйте, я вот столкнулся с такой проблемой: мне в программе надо сделать так, чтобы можно было перемещать элементы, например кнопки....

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
14.06.2013, 18:07
Помогаю со студенческими работами здесь

Возможно ли перетаскивание элементов (drag/drop) внутри listbox и между двумя listbox?
Подскажите возможно ли перетаскивание элементов внутри listbox и между двумя listbox, если возможно то как осуществить dragndrop, если нет...

Drag and drop в listbox
Здравствуйте! есть такая процедура procedure TForm1.DropFiles(var Msg: TWMDropFiles); var dropFileName : array of Char; begin ...

ListBox и Drag'n'Drop
Не ругайте сразу, Дельфи только начал... Есть вопрос: &quot;Если я в одном ListBox'e (Пусть будет ListBox1) выделил какой-нибудь элемент и...

Drag and Drop в ListBox
Реализовать перенос строк между компонентами TListBox. Два режима работы:копирование и перенос. Переносить(копировать) только выбранные...

ListBox с мультивыбором, Drag and Drop
Написал код для перетаскивания строк из одного Listbox в другой...не пойму почему выбивает ошибку в этой строчке for ( int i=0;...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
модель ЗдравоСохранения 8. Подготовка к разному выполнению заданий
anaschu 08.04.2026
https:/ / github. com/ shumilovas/ med2. git main ветка * содержимое блока дэлэй из старой модели теперь внутри зайца новой модели 8ATzM_2aurI
Блокировка документа от изменений, если он открыт у другого пользователя
Maks 08.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа, разработанного в конфигурации КА2. Задача: запретить редактирование документа, если он открыт у другого пользователя. / / . . .
Система безопасности+живучести для сервера-слоя интернета (сети). Двойная привязка.
Hrethgir 08.04.2026
Далее были размышления о системе безопасности. Сообщения с наклонным текстом - мои. А как нам будет можно проверить, что ссылка наша, а не подделана хулиганами, которая выбросит на другую ветку и. . .
Модель ЗдрввоСохранения 7: больше работников, больше ресурсов.
anaschu 08.04.2026
работников и заданий может быть сколько угодно, но настроено всё так, что используется пока что только 20% kYBz3eJf3jQ
Дальние перспективы сервера - слоя сети с космологическим дизайном интефейса карты и логики.
Hrethgir 07.04.2026
Дальнейшее ближайшее планирование вывело к размышлениям над дальними перспективами. И вот тут может быть даже будут нужны оценки специалистов, так как в дальних перспективах всё может очень сильно. . .
Горе от ума
kumehtar 07.04.2026
Эта мне ментальная установка, что вот прямо сейчас, мол, мне для полного счастья не хватает (нужное вписать), и когда я этого достигну - тогда и полный кайф. Одна из самых сильных ловушек на пути. . . .
Использование значений реквизитов справочника в документе, с определенными условиями и правами
Maks 07.04.2026
1. Контроль срока действия договора Алгоритм из решения ниже реализован на примере нетипового документа "ЗаявкаНаРаботу", разработанного в конфигурации КА2. Задача: уведомлять пользователя, если. . .
Доступность команды формы по условию
Maks 07.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: сделать доступной кнопку (команда формы "ЗавершитьСписание") при. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru