Ошибка при вызове диалога выбора файла - C#
Формулировка задачи:
Всем доброго времени суток.
Столкнулся с такой ошибкой:
в программе
Подскажите как исправить.
System.Threading.ThreadStateException не обработано
Message: Текущий поток должен быть задан как поток однопоточного контейнера (STA), чтобы вызовы OLE стали возможны. Проверьте, что ваша функция Main помечена атрибутом STAThreadAttribute. Данное исключение создается, только если к процессу подключен отладчик.
using System;
using System.Windows.Forms;
using gma.System.Windows;
using System.IO;
namespace GlobalHookDemo
{
class MainForm : System.Windows.Forms.Form
{
//==================================
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.Button buttonStop;
private System.Windows.Forms.Label labelMousePosition;
private Button button1;
private Button button2;
private TextBox time;
private Timer timer1;
private System.ComponentModel.IContainer components;
private OpenFileDialog openFileDialog1;
private TextBox st_fold;
private TextBox end_fold;
private TextBox file_name;
private TabControl tabControl1;
private TabPage tabPage1;
private TabPage tabPage2;
private TextBox end_fold_fold;
private TextBox st_fold_fold;
private Button button4;
private Button button3;
private System.Windows.Forms.TextBox textBox;
//==================================
public MainForm()
{
InitializeComponent();
}
void InitializeComponent() {
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.textBox = new System.Windows.Forms.TextBox();
this.labelMousePosition = new System.Windows.Forms.Label();
this.buttonStop = new System.Windows.Forms.Button();
this.buttonStart = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.time = new System.Windows.Forms.TextBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.st_fold = new System.Windows.Forms.TextBox();
this.end_fold = new System.Windows.Forms.TextBox();
this.file_name = new System.Windows.Forms.TextBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.end_fold_fold = new System.Windows.Forms.TextBox();
this.st_fold_fold = new System.Windows.Forms.TextBox();
this.button4 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// textBox
//
this.textBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox.Font = new System.Drawing.Font("Courier New", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.textBox.Location = new System.Drawing.Point(4, 159);
this.textBox.Multiline = true;
this.textBox.Name = "textBox";
this.textBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox.Size = new System.Drawing.Size(510, 236);
this.textBox.TabIndex = 3;
//
// labelMousePosition
//
this.labelMousePosition.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelMousePosition.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelMousePosition.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.labelMousePosition.Location = new System.Drawing.Point(4, 133);
this.labelMousePosition.Name = "labelMousePosition";
this.labelMousePosition.Size = new System.Drawing.Size(510, 23);
this.labelMousePosition.TabIndex = 2;
this.labelMousePosition.Text = "labelMousePosition";
this.labelMousePosition.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// buttonStop
//
this.buttonStop.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonStop.Location = new System.Drawing.Point(85, 3);
this.buttonStop.Name = "buttonStop";
this.buttonStop.Size = new System.Drawing.Size(75, 23);
this.buttonStop.TabIndex = 1;
this.buttonStop.Text = "Stop";
this.buttonStop.Click += new System.EventHandler(this.ButtonStopClick);
//
// buttonStart
//
this.buttonStart.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonStart.Location = new System.Drawing.Point(4, 3);
this.buttonStart.Name = "buttonStart";
this.buttonStart.Size = new System.Drawing.Size(75, 23);
this.buttonStart.TabIndex = 4;
this.buttonStart.Text = "Start";
this.buttonStart.Click += new System.EventHandler(this.ButtonStartClick);
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(413, 6);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(65, 22);
this.button1.TabIndex = 4;
this.button1.Text = "Файл";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button2.Location = new System.Drawing.Point(413, 36);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(65, 23);
this.button2.TabIndex = 5;
this.button2.Text = "Папка";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// time
//
this.time.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.time.Location = new System.Drawing.Point(166, 5);
this.time.Name = "time";
this.time.Size = new System.Drawing.Size(348, 20);
this.time.TabIndex = 6;
//
// timer1
//
this.timer1.Interval = 1;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// st_fold
//
this.st_fold.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.st_fold.Location = new System.Drawing.Point(6, 6);
this.st_fold.Name = "st_fold";
this.st_fold.Size = new System.Drawing.Size(300, 20);
this.st_fold.TabIndex = 2;
//
// end_fold
//
this.end_fold.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.end_fold.Location = new System.Drawing.Point(6, 36);
this.end_fold.Name = "end_fold";
this.end_fold.Size = new System.Drawing.Size(401, 20);
this.end_fold.TabIndex = 1;
//
// file_name
//
this.file_name.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.file_name.Location = new System.Drawing.Point(312, 6);
this.file_name.Name = "file_name";
this.file_name.Size = new System.Drawing.Size(95, 20);
this.file_name.TabIndex = 9;
//
// tabControl1
//
this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(12, 32);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(492, 98);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.st_fold);
this.tabPage1.Controls.Add(this.file_name);
this.tabPage1.Controls.Add(this.button2);
this.tabPage1.Controls.Add(this.end_fold);
this.tabPage1.Controls.Add(this.button1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(484, 72);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Файл";
this.tabPage1.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.end_fold_fold);
this.tabPage2.Controls.Add(this.st_fold_fold);
this.tabPage2.Controls.Add(this.button4);
this.tabPage2.Controls.Add(this.button3);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(484, 72);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Папка";
this.tabPage2.UseVisualStyleBackColor = true;
//
// end_fold_fold
//
this.end_fold_fold.Location = new System.Drawing.Point(6, 37);
this.end_fold_fold.Name = "end_fold_fold";
this.end_fold_fold.Size = new System.Drawing.Size(402, 20);
this.end_fold_fold.TabIndex = 3;
//
// st_fold_fold
//
this.st_fold_fold.Location = new System.Drawing.Point(6, 8);
this.st_fold_fold.Name = "st_fold_fold";
this.st_fold_fold.Size = new System.Drawing.Size(402, 20);
this.st_fold_fold.TabIndex = 2;
//
// button4
//
this.button4.Location = new System.Drawing.Point(414, 35);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(64, 23);
this.button4.TabIndex = 1;
this.button4.Text = "Папка 2";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(414, 6);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(64, 23);
this.button3.TabIndex = 0;
this.button3.Text = "Папка 1";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(516, 407);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.time);
this.Controls.Add(this.textBox);
this.Controls.Add(this.labelMousePosition);
this.Controls.Add(this.buttonStop);
this.Controls.Add(this.buttonStart);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.Text = "This application captures keystrokes";
this.Load += new System.EventHandler(this.MainFormLoad);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.tabPage2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
//==================================
int i ;
int click = 0;
string log;
bool files = false;
string str = "";
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
UserActivityHook actHook;
string file;
string filename;
string fold;
string begin_dir;
string end_dir;
//==================================
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
st_fold.Text = openFileDialog1.FileName;
file_name.Text = openFileDialog1.SafeFileName;
file = openFileDialog1.FileName;
filename = openFileDialog1.SafeFileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog bsx = new FolderBrowserDialog())
{
bsx.ShowDialog();
fold = bsx.SelectedPath;
end_fold.Text = fold;
}
}
private void button3_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog directoryDialog = new FolderBrowserDialog())
{
directoryDialog.ShowDialog();
begin_dir = directoryDialog.SelectedPath;
st_fold_fold.Text = begin_dir;
files = false;
}
}
private void button4_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog asx = new FolderBrowserDialog())
{
asx.ShowDialog();
end_dir = asx.SelectedPath;
end_fold_fold.Text = end_dir;
}
}
private void LogWrite(string txt)
{
textBox.AppendText(txt + Environment.NewLine);
textBox.SelectionStart = textBox.Text.Length;
}
public static void Main(string[] args)
{
Application.Run(new MainForm());
}
public void MyKeyUp(object sender, KeyEventArgs e)
{
LogWrite("KeyUp - " + e.KeyData.ToString());
}
void MainFormLoad(object sender, System.EventArgs e)
{
actHook = new UserActivityHook();
actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
//=======================
try
{
StreamReader streamReader = new StreamReader("info.ini");
while (!streamReader.EndOfStream)
{
str += streamReader.ReadLine();
}
streamReader.Close();
try
{
string input = str;
string[] split = input.Split(';');
time.Text = split[0];
st_fold.Text = split[1];
end_fold.Text = split[2];
file_name.Text = split[3];
st_fold_fold.Text = split[4];
end_fold_fold.Text = split[5];
}
catch (IndexOutOfRangeException)
{
}
}
catch (FileNotFoundException)
{
FileInfo fi = new FileInfo("info.ini");
fi.Create();
}
}
public void MyKeyDown(object sender, KeyEventArgs e)
{
LogWrite("KeyDown - " + e.KeyData.ToString());
}
private void timer1_Tick(object sender, EventArgs e)
{
--i;
time.Text = Convert.ToString(i);
if (i == 0)
{
if (files == false)
{
CopyDirectoryRecursive(begin_dir, end_dir);
timer1.Stop();
this.Close();
}
else
{
File.Copy(file, fold + "\\" + filename, true);
timer1.Stop();
this.Close();
}
}
}
void ButtonStopClick(object sender, System.EventArgs e)
{
actHook.Stop();
click = 0;
timer1.Stop();
if (tabControl1.TabPages[tabControl1.SelectedIndex].Text == "Файл")
{}
}
public void MouseMoved(object sender, MouseEventArgs e)
{
labelMousePosition.Text=String.Format("x={0} y={1} wheel={2}", e.X, e.Y, e.Delta);
if (e.Clicks > 0)
{
LogWrite("MouseButton - " + e.Button.ToString());
if (click == 1)
{
timer1.Start();
}
}
}
void ButtonStartClick(object sender, System.EventArgs e)
{
log = time.Text + ";" + st_fold.Text + ";" + end_fold.Text + ";" + file_name.Text + ";" + st_fold_fold.Text + ";" + end_fold_fold.Text;
StreamWriter sw = new StreamWriter("info.ini");
sw.WriteLine(log);
sw.Close();
i = Convert.ToInt32(time.Text);
if (tabControl1.TabPages[tabControl1.SelectedIndex].Text == "Файл")
{
files = false;
}
else
{
files = true;
}
actHook.Start();
click = 1;
file = st_fold.Text;
filename = file_name.Text;
fold = end_fold.Text;
}
public void MyKeyPress(object sender, KeyPressEventArgs e)
{
LogWrite("KeyPress - " + e.KeyChar);
}
private static void CopyDirectoryRecursive(string sourceDirectoryPath, string destinationDirectoryPath)
{
var sourceDirectoryInfo = new DirectoryInfo(sourceDirectoryPath);
var destinationDirectoryInfo = new DirectoryInfo(destinationDirectoryPath);
if (!sourceDirectoryInfo.Exists) return;
if (!destinationDirectoryInfo.Exists) destinationDirectoryInfo.Create();
foreach (var fileInfo in sourceDirectoryInfo.GetFiles())
{
try
{
File.Copy(fileInfo.FullName, Path.Combine(destinationDirectoryInfo.FullName, fileInfo.Name));
}
catch (Exception)
{
//Обработка ошибок при копировании файла.
}
}
foreach (var directoryInfo in sourceDirectoryInfo.GetDirectories())
{
CopyDirectoryRecursive(directoryInfo.FullName, Path.Combine(destinationDirectoryInfo.FullName, directoryInfo.Name));
}
}
}
}
ошибка возникает при вызове диалога выбор файла или папки.
Решение задачи: «Ошибка при вызове диалога выбора файла»
textual
Листинг программы
[STAThread]
static void Main()
{
...
}