我目前正在使用C#将Windows窗体应用程序转换为控制台应用程序。
我正在忙着转换代码,我遇到了一些语法问题,我不确定如何正确转换。 以下是Windows窗体应用程序中的原始代码:
private eSkan.api.TeSkanAPI feSkanAPI = null;
private void MessageFilter_AddRemove_Invoked(bool AddFilter, IMessageFilter Filter)
{
if (AddFilter)
{
Application.AddMessageFilter(Filter);
}
else
{
Application.RemoveMessageFilter(Filter);
}
}
private void MessageFilter_AddRemove(bool AddFilter, IMessageFilter Filter)
{
{
IAsyncResult sr = BeginInvoke((ESKAN_ADD_REMOVE_MESSAGEFILTER)MessageFilter_AddRemove_Invoked,
AddFilter, Filter);
sr.AsyncWaitHandle.WaitOne(2000);
}
}
private void IniteSkan()
{
lMSG.Items.Clear();
feSkanAPI = new TeSkanAPI();
// To add a message filter you have to add it from the MAIN thread - thus the main form
feSkanAPI.AddRemoveMessageFilterProc = MessageFilter_AddRemove;
feSkanAPI.OneSkanEvent += eScan_Callback;
feSkanAPI.Thread_Start(true);
}
public Form1()
{
InitializeComponent();
}
private void eScan_Callback_safe(EeSkan_EventType command, object Data)
{
lMSG.Items.Insert(0, "++++++++");
lMSG.Items.Insert(0, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
lMSG.Items.Insert(0, "New Command "+command.ToString());
if (Data is TeSkan_EventInfo)
{
lMSG.Items.Insert(0, "Data File : " + ((TeSkan_EventInfo)Data).DataFile);
lMSG.Items.Insert(0, "Image File : " + ((TeSkan_EventInfo)Data).ImageFile);
} else if (Data is string)
{
lMSG.Items.Insert(0, "Data String : " + (string) Data);
}
//lMSG.Items.Insert(0, "Image File " + ScanInfo.ImageFile);
//lMSG.Items.Insert(0, "Data File " + ScanInfo.ImageFile);
lMSG.Items.Insert(0, "--------");
}
/// <summary>
/// When accesing GUI/Form/Components - you cannot work cross-thread.
/// This method will invoke eScan_Callback_safe in main/GUI thread if another thread called it,
/// or call eScan_Callback_safe directly if already on GUI/main thread
///
/// </summary>
/// <param name="ScanInfo"></param>
private void eScan_Callback(EeSkan_EventType command, object Data)
{
if (InvokeRequired)
{
this.Invoke((ESKAN_EVENT_CALLBACK)eScan_Callback_safe, command, Data);
}
else
{
eScan_Callback_safe(command, Data);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
feSkanAPI.Thread_Stop(10000);
feSkanAPI.Dispose();
}
private void Form1_Load(object sender, EventArgs e)
{
IniteSkan();
}
我正在使用Action在控制台应用程序中执行BeginInvoke部分。我想知道“eScan_Callback()”函数中“InvokeRequired”部分的最佳用途。
答案 0 :(得分:1)
InvokeRequired
用于检查当前线程是否可以安全地访问winforms控件。如果您要将其转换为控制台应用程序,您可以将其替换为“else”块中的标准方法调用。
然而,看起来这是做一些线程的事情,所以而不是副本&amp;粘贴作业,我会看看这个表单整体上做了什么,并以更“'-console-y'的方式重写它。
答案 1 :(得分:0)
读到您制作控制台应用程序我认为您不需要此代码,只需使用:eScan_Callback_safe(命令,数据);