目的:把vncviewer从exe封装成dll,然后通过.NET程序提供的用户界面予以调用。
环境:VNC Free Edition 4.1 + .NET 2.0。
结果:
C#代码:
public partial class vncviewer : Form
{
private class vncparameter
{
public string host;
public string password;
public vncparameter(string host, string password)
{
this.host = host;
this.password = password;
}
public override string ToString()
{
return host;
}
}
public vncviewer()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Regex host = new Regex("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}contentquot;);
Regex hostandport = new Regex("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5}contentquot;);
if (!host.IsMatch(txtHost.Text) && !hostandport.IsMatch(txtHost.Text))
{
MessageBox.Show("Format:000.000.000.000[:00000]");
return;
}
foreach (object o in lstHost.Items)
{
vncparameter item = (vncparameter)o;
if (item.host == txtHost.Text)
return;
}
lstHost.Items.Add(new vncparameter(txtHost.Text,txtPassword.Text));
}
private void lstHost_SelectedIndexChanged(object sender, EventArgs e)
{
}
private delegate void AppendTextMethod(string text);
private void AppendText(string text)
{
txtLog.AppendText(text);
}
private delegate void SetTextMethod(string text);
private void SetText(string text)
{
txtLog.Text = text;
}
private void PipeLog()
{
SafeFileHandle pipe = CreateNamedPipe("\\.\pipe\pipeforvncviewer", PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1,
BUFFER_SIZE, BUFFER_SIZE, 0, 0);
int fConnect = ConnectNamedPipe(pipe, 0);
if (fConnect != 0)
{
StreamReader sr = new StreamReader(new FileStream(pipe, FileAccess.Read), Encoding.ASCII);
string line;
while ((line = sr.ReadLine()) != null)
{
if (line != string.Empty)
{
string lines = txtLog.Lines;
if (lines.Length <= LINE_LIMIT)
txtLog.Invoke(new AppendTextMethod(AppendText), line + " ");
else
{
List<string> newLines = new List<string>(lines.Length);
for (int n = 1; n < LINE_LIMIT; n++)
{
newLines.Add(lines[n]);
}
newLines.Add(line + " ");
txtLog.Invoke(new SetTextMethod(SetText), String.Join(" ", newLines.ToArray()));
}
}
}
sr.Close();
}
}
private void vncviewer_Load(object sender, EventArgs e)
{
Thread log = new Thread(new ThreadStart(PipeLog));
log.IsBackground = true;
log.Start();
Init();
}
[DllImport("KERNEL32.DLL", EntryPoint = "CreateNamedPipeW", SetLastError = false,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern SafeFileHandle CreateNamedPipe(string lpName, uint dwOpenMode, uint dwPipeMode, uint nMaxInstances,
uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut, uint lpSecurityAttributes);
[DllImport("KERNEL32.DLL", EntryPoint = "ConnectNamedPipe", SetLastError = false,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern int Connect