Fixing designer issues with controls being outside our dialog.
2 using System.Collections.Generic;
3 using System.ComponentModel;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
11 using CodeProject.Dialog;
12 using System.Drawing.Imaging;
13 using System.ServiceModel;
14 using System.Threading;
15 using System.Diagnostics;
17 using SharpDisplayInterface;
18 using SharpDisplayClient;
21 namespace SharpDisplayManager
23 public partial class MainForm : Form
25 DateTime LastTickTime;
27 System.Drawing.Bitmap iBmp;
28 bool iCreateBitmap; //Workaround render to bitmap issues when minimized
29 ServiceHost iServiceHost;
31 /// Our collection of clients
33 public Dictionary<string, ClientData> iClients;
38 LastTickTime = DateTime.Now;
39 iDisplay = new Display();
40 iClients = new Dictionary<string, ClientData>();
42 InitializeComponent();
46 marqueeLabelTop.Font = Properties.Settings.Default.DisplayFont;
47 marqueeLabelBottom.Font = Properties.Settings.Default.DisplayFont;
48 checkBoxShowBorders.Checked = Properties.Settings.Default.DisplayShowBorders;
49 checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
50 checkBoxReverseScreen.Checked = Properties.Settings.Default.DisplayReverseScreen;
52 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
53 //We have a bug when drawing minimized and reusing our bitmap
54 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
55 iCreateBitmap = false;
58 private void MainForm_Load(object sender, EventArgs e)
67 if (Properties.Settings.Default.DisplayConnectOnStartup)
69 iDisplay.Open(Display.TMiniDisplayType.EMiniDisplayAutoDetect);
75 private void buttonFont_Click(object sender, EventArgs e)
77 //fontDialog.ShowColor = true;
78 //fontDialog.ShowApply = true;
79 fontDialog.ShowEffects = true;
80 fontDialog.Font = marqueeLabelTop.Font;
82 fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
84 //fontDialog.ShowHelp = true;
86 //fontDlg.MaxSize = 40;
87 //fontDlg.MinSize = 22;
89 //fontDialog.Parent = this;
90 //fontDialog.StartPosition = FormStartPosition.CenterParent;
92 //DlgBox.ShowDialog(fontDialog);
94 //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
95 if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
98 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
100 //MessageBox.Show("Ok");
101 marqueeLabelTop.Font = fontDialog.Font;
102 marqueeLabelBottom.Font = fontDialog.Font;
103 Properties.Settings.Default.DisplayFont = fontDialog.Font;
104 Properties.Settings.Default.Save();
113 void CheckFontHeight()
115 if (marqueeLabelBottom.Font.Height > marqueeLabelBottom.Height)
117 labelWarning.Text = "WARNING: Selected font is too height by " + (marqueeLabelBottom.Font.Height - marqueeLabelBottom.Height) + " pixels!";
118 labelWarning.Visible = true;
122 labelWarning.Visible = false;
127 private void buttonCapture_Click(object sender, EventArgs e)
129 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height);
130 tableLayoutPanel.DrawToBitmap(bmp, tableLayoutPanel.ClientRectangle);
131 //Bitmap bmpToSave = new Bitmap(bmp);
132 bmp.Save("D:\\capture.png");
134 marqueeLabelTop.Text = "Sweet";
137 string outputFileName = "d:\\capture.png";
138 using (MemoryStream memory = new MemoryStream())
140 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
142 bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
143 byte[] bytes = memory.ToArray();
144 fs.Write(bytes, 0, bytes.Length);
151 private void CheckForRequestResults()
153 if (iDisplay.IsRequestPending())
155 switch (iDisplay.AttemptRequestCompletion())
157 case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
158 if (iDisplay.PowerSupplyStatus())
160 toolStripStatusLabelPower.Text = "ON";
164 toolStripStatusLabelPower.Text = "OFF";
166 //Issue next request then
167 iDisplay.RequestDeviceId();
170 case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
171 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
172 //Issue next request then
173 iDisplay.RequestFirmwareRevision();
176 case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
177 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
178 //No more request to issue
185 public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
188 public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
190 return aBmp.Width - aX - 1;
193 public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
195 return iBmp.Height - aY - 1;
198 public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
203 public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
209 //This is our timer tick responsible to perform our render
210 private void timer_Tick(object sender, EventArgs e)
212 //Update our animations
213 DateTime NewTickTime = DateTime.Now;
215 marqueeLabelTop.UpdateAnimation(LastTickTime, NewTickTime);
216 marqueeLabelBottom.UpdateAnimation(LastTickTime, NewTickTime);
219 if (iDisplay.IsOpen())
221 CheckForRequestResults();
226 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
228 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
229 //iBmp.Save("D:\\capture.png");
231 //Select proper coordinate translation functions
232 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
233 CoordinateTranslationDelegate screenX;
234 CoordinateTranslationDelegate screenY;
236 if (Properties.Settings.Default.DisplayReverseScreen)
238 screenX = ScreenReversedX;
239 screenY = ScreenReversedY;
247 //Send it to our display
248 for (int i = 0; i < iBmp.Width; i++)
250 for (int j = 0; j < iBmp.Height; j++)
254 uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
255 //For some reason when the app is minimized in the task bar only the alpha of our color is set.
256 //Thus that strange test for rendering to work both when the app is in the task bar and when it isn't.
257 iDisplay.SetPixel(screenX(iBmp, i), screenY(iBmp, j), Convert.ToInt32(!(color != 0xFF000000)));
262 iDisplay.SwapBuffers();
266 //Compute instant FPS
267 toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " FPS";
269 LastTickTime = NewTickTime;
273 private void buttonOpen_Click(object sender, EventArgs e)
275 if (iDisplay.Open(Display.TMiniDisplayType.EMiniDisplayAutoDetect))
278 iDisplay.RequestPowerSupplyStatus();
283 toolStripStatusLabelConnect.Text = "Connection error";
288 private void buttonClose_Click(object sender, EventArgs e)
294 private void buttonClear_Click(object sender, EventArgs e)
297 iDisplay.SwapBuffers();
300 private void buttonFill_Click(object sender, EventArgs e)
303 iDisplay.SwapBuffers();
306 private void trackBarBrightness_Scroll(object sender, EventArgs e)
308 Properties.Settings.Default.DisplayBrightness = trackBarBrightness.Value;
309 Properties.Settings.Default.Save();
310 iDisplay.SetBrightness(trackBarBrightness.Value);
314 private void UpdateStatus()
316 if (iDisplay.IsOpen())
318 buttonFill.Enabled = true;
319 buttonClear.Enabled = true;
320 buttonOpen.Enabled = false;
321 buttonClose.Enabled = true;
322 trackBarBrightness.Enabled = true;
323 trackBarBrightness.Minimum = iDisplay.MinBrightness();
324 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
325 trackBarBrightness.Value = Properties.Settings.Default.DisplayBrightness;
326 trackBarBrightness.LargeChange = Math.Max(1,(iDisplay.MaxBrightness() - iDisplay.MinBrightness())/5);
327 trackBarBrightness.SmallChange = 1;
328 iDisplay.SetBrightness(Properties.Settings.Default.DisplayBrightness);
330 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
331 //+ " - " + iDisplay.SerialNumber();
335 buttonFill.Enabled = false;
336 buttonClear.Enabled = false;
337 buttonOpen.Enabled = true;
338 buttonClose.Enabled = false;
339 trackBarBrightness.Enabled = false;
340 toolStripStatusLabelConnect.Text = "Disconnected";
346 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
348 //Save our show borders setting
349 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
350 Properties.Settings.Default.DisplayShowBorders = checkBoxShowBorders.Checked;
351 Properties.Settings.Default.Save();
354 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
356 //Save our connect on startup setting
357 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
358 Properties.Settings.Default.Save();
361 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
363 //Save our reverse screen setting
364 Properties.Settings.Default.DisplayReverseScreen = checkBoxReverseScreen.Checked;
365 Properties.Settings.Default.Save();
368 private void MainForm_Resize(object sender, EventArgs e)
370 if (WindowState == FormWindowState.Minimized)
373 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
374 iCreateBitmap = true;
378 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
384 public void StartServer()
386 iServiceHost = new ServiceHost
388 typeof(DisplayServer),
389 new Uri[] { new Uri("net.tcp://localhost:8001/") }
392 iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
396 public void StopServer()
398 if (iClients.Count > 0 && !iClosing)
402 BroadcastCloseEvent();
406 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
408 iClosing = false; //We make sure we force close if asked twice
413 //We removed that as it often lags for some reason
414 //iServiceHost.Close();
418 public void BroadcastCloseEvent()
420 Trace.TraceInformation("BroadcastCloseEvent - start");
422 var inactiveClients = new List<string>();
423 foreach (var client in iClients)
425 //if (client.Key != eventData.ClientName)
429 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
430 client.Value.Callback.OnCloseOrder(/*eventData*/);
434 inactiveClients.Add(client.Key);
439 if (inactiveClients.Count > 0)
441 foreach (var client in inactiveClients)
443 iClients.Remove(client);
444 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
449 private void buttonStartClient_Click(object sender, EventArgs e)
451 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
452 clientThread.Start();
456 private void buttonSuspend_Click(object sender, EventArgs e)
458 timer.Enabled = !timer.Enabled;
461 buttonSuspend.Text = "Suspend";
465 buttonSuspend.Text = "Pause";
469 private void buttonCloseClients_Click(object sender, EventArgs e)
471 BroadcastCloseEvent();
474 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
479 //Delegates are used for our thread safe method
480 public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
481 public delegate void RemoveClientDelegate(string aSessionId);
482 public delegate void SetTextDelegate(string SessionId, int aLineIndex, string aText);
483 public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<string> aTexts);
484 public delegate void SetClientNameDelegate(string aSessionId, string aName);
490 /// <param name="aSessionId"></param>
491 /// <param name="aCallback"></param>
492 public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
494 if (this.InvokeRequired)
496 //Not in the proper thread, invoke ourselves
497 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
498 this.Invoke(d, new object[] { aSessionId, aCallback });
502 //We are in the proper thread
503 //Add this session to our collection of clients
504 ClientData newClient = new ClientData(aSessionId, aCallback);
505 Program.iMainForm.iClients.Add(aSessionId, newClient);
506 //Add this session to our UI
507 UpdateClientTreeViewNode(newClient);
514 /// <param name="aSessionId"></param>
515 public void RemoveClientThreadSafe(string aSessionId)
517 if (this.InvokeRequired)
519 //Not in the proper thread, invoke ourselves
520 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
521 this.Invoke(d, new object[] { aSessionId });
525 //We are in the proper thread
526 //Remove this session from both client collection and UI tree view
527 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
529 Program.iMainForm.iClients.Remove(aSessionId);
530 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
533 if (iClosing && iClients.Count == 0)
535 //We were closing our form
536 //All clients are now closed
537 //Just resume our close operation
547 /// <param name="aLineIndex"></param>
548 /// <param name="aText"></param>
549 public void SetTextThreadSafe(string aSessionId, int aLineIndex, string aText)
551 if (this.InvokeRequired)
553 //Not in the proper thread, invoke ourselves
554 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
555 this.Invoke(d, new object[] { aSessionId, aLineIndex, aText });
559 ClientData client = iClients[aSessionId];
562 //Make sure all our texts are in place
563 while (client.Texts.Count < (aLineIndex + 1))
565 client.Texts.Add("");
567 client.Texts[aLineIndex] = aText;
569 //We are in the proper thread
570 //Only support two lines for now
573 marqueeLabelTop.Text = aText;
575 else if (aLineIndex == 1)
577 marqueeLabelBottom.Text = aText;
581 UpdateClientTreeViewNode(client);
589 /// <param name="aTexts"></param>
590 public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<string> aTexts)
592 if (this.InvokeRequired)
594 //Not in the proper thread, invoke ourselves
595 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
596 this.Invoke(d, new object[] { aSessionId, aTexts });
600 ClientData client = iClients[aSessionId];
603 //Populate our client with the given texts
605 foreach (string text in aTexts)
607 if (client.Texts.Count < (j + 1))
609 client.Texts.Add(text);
613 client.Texts[j]=text;
617 //We are in the proper thread
618 //Only support two lines for now
619 for (int i = 0; i < aTexts.Count; i++)
623 marqueeLabelTop.Text = aTexts[i];
627 marqueeLabelBottom.Text = aTexts[i];
632 UpdateClientTreeViewNode(client);
641 /// <param name="aSessionId"></param>
642 /// <param name="aName"></param>
643 public void SetClientNameThreadSafe(string aSessionId, string aName)
645 if (this.InvokeRequired)
647 //Not in the proper thread, invoke ourselves
648 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
649 this.Invoke(d, new object[] { aSessionId, aName });
653 //We are in the proper thread
655 ClientData client = iClients[aSessionId];
660 //Update our tree-view
661 UpdateClientTreeViewNode(client);
669 /// <param name="aClient"></param>
670 private void UpdateClientTreeViewNode(ClientData aClient)
677 TreeNode node = null;
678 //Check that our client node already exists
679 //Get our client root node using its key which is our session ID
680 TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
683 //We already have a node for that client
685 //Clear children as we are going to recreate them below
690 //Client node does not exists create a new one
691 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
692 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
698 if (aClient.Name != "")
700 //We have a name, us it as text for our root node
701 node.Text = aClient.Name;
702 //Add a child with SessionId
703 node.Nodes.Add(new TreeNode(aClient.SessionId));
707 //No name, use session ID instead
708 node.Text = aClient.SessionId;
711 if (aClient.Texts.Count > 0)
713 //Create root node for our texts
714 TreeNode textsRoot = new TreeNode("Text");
715 node.Nodes.Add(textsRoot);
716 //For each text add a new entry
717 foreach (string text in aClient.Texts)
719 textsRoot.Nodes.Add(new TreeNode(text));
727 private void buttonAddRow_Click(object sender, EventArgs e)
729 if (tableLayoutPanel.RowCount < 6)
731 tableLayoutPanel.RowCount++;
736 private void buttonRemoveRow_Click(object sender, EventArgs e)
738 if (tableLayoutPanel.RowCount > 1)
740 tableLayoutPanel.RowCount--;
745 private void buttonAddColumn_Click(object sender, EventArgs e)
747 if (tableLayoutPanel.ColumnCount < 8)
749 tableLayoutPanel.ColumnCount++;
754 private void buttonRemoveColumn_Click(object sender, EventArgs e)
756 if (tableLayoutPanel.ColumnCount > 1)
758 tableLayoutPanel.ColumnCount--;
767 /// A UI thread copy of a client relevant data.
768 /// Keeping this copy in the UI thread helps us deal with threading issues.
770 public class ClientData
772 public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
774 SessionId = aSessionId;
776 Texts = new List<string>();
777 Callback = aCallback;
780 public string SessionId { get; set; }
781 public string Name { get; set; }
782 public List<string> Texts { get; set; }
783 public IDisplayServiceCallback Callback { get; set; }