AdvancedHMI Software
General Category => Open Discussion => Topic started by: bachphi on April 20, 2019, 02:29:52 PM
-
I am trying to translate some C# codes to VB, it seemed to work, but want to check if it's alright or some improvement ideas. TIA.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ThreadSafeControls
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.CustomInvoke(l => l.Text = "Thread Safe Controls");
}
}
public static class MyInvoke
{
public static void CustomInvoke<T>(this T @control, Action<T> toPerform) where T : ISynchronizeInvoke
{
if (@control.InvokeRequired)
@control.Invoke(toPerform, new object[] { @control });
else
toPerform(@control);
}
}
}
and the VB code that I translated :
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.CustomInvoke(Sub(l) l.Text = "Thread Safe Controls")
End Sub
End Class
Public Module MyInvoke
<System.Runtime.CompilerServices.Extension()>
Public Sub CustomInvoke(Of T As ISynchronizeInvoke)(control As T, toPerform As Action(Of T))
If control.InvokeRequired Then
control.Invoke(toPerform, New Object() {control})
Else
toPerform(control)
End If
End Sub
End Module
-
Using lambda expressions and extension methods gets into some sophisticated coding techniques, but your code is the correct way to do it.
-
I tried 3 web sites, none are translated correctly:
if (bAdd)
{
//Add event handlers
txtSQLServerName.TextChanged += BuildConnectionString;
btnExecute.Click += btnExecute_Click;
}
else
{
//Remove event handlers
txtSQLServerName.TextChanged -= BuildConnectionString;
btnExecute.Click -= btnExecute_Click;
}
I believe, they should be like:
If bAdd Then
'Add event handlers
AddHandler txtSQLServerName.TextChanged, AddressOf BuildConnectionString
AddHandler btnExecute.Click, AddressOf btnExecute_Click
Else
'Remove event handlers
RemoveHandler txtSQLServerName.TextChanged, AddressOf BuildConnectionString
RemoveHandler btnExecute.Click, AddressOf btnExecute_Click
End If
-
I'm surprised the code converters do not properly convert such as common function, but your conversion is correct.
-
In C# application, any sub routines that put after InitializeComponent() will get execute BEFORE form_move and form_load events.
How can I get this same effect in vb .net? TIA.
-
I found the answer, use the drop down and select new
Public Sub New()
' This call is required by the designer.
InitializeComponent()
DoEventFirst()
' Add any initialization after the InitializeComponent() call.
End Sub