using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Windows.Forms; internal static class Program { [STAThread] static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new MainForm()); } } public class MainForm : Form { private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct LVITEM { public uint mask; public int iItem; public int iSubItem; public uint state; public uint stateMask; public IntPtr pszText; public int cchTextMax; public int iImage; public IntPtr lParam; public int iIndent; public int iGroupId; public uint cColumns; public IntPtr puColumns; public IntPtr piColFmt; public int iGroup; } [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc proc, IntPtr lParam); [DllImport("user32.dll")] private static extern bool EnumChildWindows(IntPtr parent, EnumWindowsProc proc, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int max); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hWnd, StringBuilder text, int max); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, StringBuilder lParam); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern IntPtr GetMenu(IntPtr hWnd); [DllImport("user32.dll")] private static extern int GetMenuItemCount(IntPtr hMenu); [DllImport("user32.dll")] private static extern IntPtr GetSubMenu(IntPtr hMenu, int nPos); [DllImport("user32.dll")] private static extern uint GetMenuItemID(IntPtr hMenu, int nPos); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetMenuString( IntPtr hMenu, uint uIDItem, StringBuilder lpString, int cchMax, uint flags); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); [DllImport("kernel32.dll")] private static extern IntPtr OpenProcess(uint access, bool inherit, uint processId); [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] private static extern IntPtr VirtualAllocEx(IntPtr process, IntPtr address, UIntPtr size, uint allocationType, uint protect); [DllImport("kernel32.dll")] private static extern bool VirtualFreeEx(IntPtr process, IntPtr address, UIntPtr size, uint freeType); [DllImport("kernel32.dll")] private static extern bool WriteProcessMemory(IntPtr process, IntPtr address, byte[] buffer, int size, out IntPtr written); [DllImport("kernel32.dll")] private static extern bool ReadProcessMemory(IntPtr process, IntPtr address, byte[] buffer, int size, out IntPtr read); private const uint PROCESS_VM_OPERATION = 0x0008; private const uint PROCESS_VM_READ = 0x0010; private const uint PROCESS_VM_WRITE = 0x0020; private const uint PROCESS_QUERY_INFORMATION = 0x0400; private const uint MEM_COMMIT = 0x1000; private const uint MEM_RESERVE = 0x2000; private const uint MEM_RELEASE = 0x8000; private const uint PAGE_READWRITE = 0x04; private const uint LVM_FIRST = 0x1000; private const uint LVM_GETITEMCOUNT = LVM_FIRST + 4; private const uint LVM_GETITEMTEXTW = LVM_FIRST + 115; private const uint LVM_SETITEMSTATE = LVM_FIRST + 43; private const uint LVM_ENSUREVISIBLE = LVM_FIRST + 19; private const uint LVIF_TEXT = 0x0001; private const uint LVIS_FOCUSED = 0x0001; private const uint LVIS_SELECTED = 0x0002; private const uint BM_CLICK = 0x00F5; private const uint WM_COMMAND = 0x0111; private const uint WM_CLOSE = 0x0010; private const uint MF_BYPOSITION = 0x00000400; private const uint MF_BYCOMMAND = 0x00000000; private const uint INVALID_MENU_ID = 0xFFFFFFFF; private const int SW_HIDE = 0; private const byte VK_MENU = 0x12; // ALT private const byte VK_W = 0x57; // W private const byte VK_ENTER = 0x0D; private const byte VK_DOWN = 0x28; private const byte VK_UP = 0x26; private const uint KEYEVENTF_KEYUP = 0x0002; private readonly ListBox lst = new(); private readonly Button btnOpen = new(); private readonly Button btnUp = new(); private readonly Button btnDown = new(); private readonly Button btnRefresh = new(); private readonly Button btnSave = new(); private readonly Button btnTerminalAdd = new(); private readonly ComboBox cmbTerminal = new(); private readonly Label lblStatus = new(); private sealed class TerminalInfo { public IntPtr Hwnd { get; init; } public uint ProcessId { get; init; } public string Name { get; init; } = ""; public string Title { get; init; } = ""; public override string ToString() => Name; } // Gespeichert wird der vollständige MT5-Text. Angezeigt wird nur Symbol,Timeframe. private readonly List charts = new(); private bool terminalWechselLaeuft; // Drag & Drop innerhalb der Chartliste. private int dragStartIndex = -1; private Point dragStartPoint; private bool dragLaeuft; private TerminalInfo? AktuellesTerminal => cmbTerminal.SelectedItem as TerminalInfo; private string WindowFile => Path.Combine(AppContext.BaseDirectory, "fensterposition.json"); private sealed class SavedWindowState { public int X { get; set; } public int Y { get; set; } public int Width { get; set; } public int Height { get; set; } } private string SaveFile { get { string name = AktuellesTerminal?.Name ?? "MT5"; foreach (char c in Path.GetInvalidFileNameChars()) name = name.Replace(c, '_'); return Path.Combine(AppContext.BaseDirectory, $"chartreihenfolge_{name}.json"); } } [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute( IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute); private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20; private void AktiviereDunkleTitelleiste() { try { int dark = 1; DwmSetWindowAttribute( Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, ref dark, sizeof(int)); } catch { } } public MainForm() { Text = "Chart Organiser 1.1"; Width = 230; Height = 670; MinimumSize = new Size(150, 470); // Startposition wie im Screenshot: links oben, direkt unter der MT5-Menüleiste. StartPosition = FormStartPosition.Manual; Location = new Point(4, 220); // Navigationsleiste bleibt vor MT5 im Vordergrund. // Beim Minimieren verschwindet sie ganz normal. TopMost = true; BackColor = Color.FromArgb(24, 24, 27); ForeColor = Color.FromArgb(235, 235, 235); Font = new Font("Segoe UI", 9F); LadeFensterposition(); BuildGui(); FormClosing += (_, _) => SpeichereFensterposition(); HandleCreated += (_, _) => AktiviereDunkleTitelleiste(); Shown += (_, _) => { BeginInvoke(new Action(() => { TerminalsNeuEinlesen(); if (cmbTerminal.Items.Count > 0) { cmbTerminal.SelectedIndex = 0; LadeReihenfolge(); AktualisierenAutomatisch(); } else { lblStatus.Text = "Kein laufendes MT5-Terminal gefunden."; } })); }; } private void LadeFensterposition() { try { if (!File.Exists(WindowFile)) return; var state = JsonSerializer.Deserialize(File.ReadAllText(WindowFile)); if (state == null) return; // Nur sinnvolle Werte übernehmen. if (state.Width >= 150 && state.Height >= 300) { Location = new Point(state.X, state.Y); Size = new Size(state.Width, state.Height); } } catch { // Bei defekter Datei einfach die Standardposition verwenden. } } private void SpeichereFensterposition() { try { if (WindowState == FormWindowState.Minimized) return; Rectangle r = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds; var state = new SavedWindowState { X = r.X, Y = r.Y, Width = r.Width, Height = r.Height }; File.WriteAllText(WindowFile, JsonSerializer.Serialize(state)); } catch { } } private void BuildGui() { Color bg = Color.FromArgb(24, 24, 27); Color panel = Color.FromArgb(32, 33, 36); Color row = Color.FromArgb(38, 39, 43); Color rowSelected = Color.FromArgb(66, 68, 74); Color border = Color.FromArgb(68, 69, 74); Color text = Color.FromArgb(235, 235, 235); Color muted = Color.FromArgb(170, 172, 178); Color button = Color.FromArgb(48, 49, 54); var title = new Label { Text = "CHART ORGANISER", Left = 14, Top = 12, AutoSize = true, ForeColor = text, Font = new Font("Segoe UI Semibold", 12F, FontStyle.Bold) }; cmbTerminal.Left = 14; cmbTerminal.Top = 43; cmbTerminal.Width = ClientSize.Width - 73; cmbTerminal.Height = 28; cmbTerminal.DropDownStyle = ComboBoxStyle.DropDownList; cmbTerminal.FlatStyle = FlatStyle.Flat; cmbTerminal.BackColor = panel; cmbTerminal.ForeColor = text; cmbTerminal.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; StyleButton(btnTerminalAdd, "+", button, text); btnTerminalAdd.Left = ClientSize.Width - 40; btnTerminalAdd.Top = 43; btnTerminalAdd.Width = 26; btnTerminalAdd.Height = 28; btnTerminalAdd.Anchor = AnchorStyles.Top | AnchorStyles.Right; lst.Left = 14; lst.Top = 82; lst.Width = ClientSize.Width - 28; lst.Height = 505; lst.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; lst.BorderStyle = BorderStyle.FixedSingle; lst.BackColor = row; lst.ForeColor = text; lst.IntegralHeight = false; lst.DrawMode = DrawMode.OwnerDrawFixed; lst.ItemHeight = 25; lst.DrawItem += (_, e) => { if (e.Index < 0 || e.Index >= lst.Items.Count) return; bool selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected; using var bgBrush = new SolidBrush(selected ? rowSelected : row); using var linePen = new Pen(border); using var textBrush = new SolidBrush(text); e.Graphics.FillRectangle(bgBrush, e.Bounds); // Klare, aber dezente Trennlinie zwischen den Charts. e.Graphics.DrawLine( linePen, e.Bounds.Left + 8, e.Bounds.Bottom - 1, e.Bounds.Right - 8, e.Bounds.Bottom - 1); string value = lst.Items[e.Index]?.ToString() ?? ""; var rect = new Rectangle( e.Bounds.Left + 10, e.Bounds.Top, e.Bounds.Width - 18, e.Bounds.Height); TextRenderer.DrawText( e.Graphics, value, new Font("Segoe UI", 8.25F), rect, text, TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix); if (selected) e.DrawFocusRectangle(); }; StyleButton(btnOpen, "▶", button, text); StyleButton(btnUp, "↑", button, text); StyleButton(btnDown, "↓", button, text); StyleButton(btnSave, "Speichern", button, text); StyleButton(btnRefresh, "↻", button, text); // Eine einzige kompakte Buttonleiste. Dadurch bleibt mehr Platz für Charts. // Sehr kompakte Symbolleiste, damit das Fenster stark verschmälert werden kann. btnOpen.Left = 14; btnOpen.Top = 594; btnOpen.Width = 28; btnOpen.Height = 28; btnOpen.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; btnUp.Left = 46; btnUp.Top = 594; btnUp.Width = 28; btnUp.Height = 28; btnUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; btnDown.Left = 78; btnDown.Top = 594; btnDown.Width = 28; btnDown.Height = 28; btnDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; btnSave.Left = 110; btnSave.Top = 594; btnSave.Width = 28; btnSave.Height = 28; btnSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; btnRefresh.Left = 142; btnRefresh.Top = 594; btnRefresh.Width = 28; btnRefresh.Height = 28; btnRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; // Disketten-Symbol statt großem Speicher-Button. btnSave.Text = "💾"; lblStatus.Left = 14; lblStatus.Top = 624; lblStatus.Width = ClientSize.Width - 28; lblStatus.Height = 18; lblStatus.ForeColor = muted; lblStatus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; Controls.Add(title); Controls.Add(cmbTerminal); Controls.Add(btnTerminalAdd); Controls.Add(lst); Controls.Add(btnOpen); Controls.Add(btnUp); Controls.Add(btnDown); Controls.Add(btnSave); Controls.Add(btnRefresh); Controls.Add(lblStatus); btnRefresh.Click += (_, _) => { TerminalsNeuEinlesen(AktuellesTerminal?.ProcessId); AktualisierenAutomatisch(); }; btnTerminalAdd.Click += (_, _) => { uint? vorher = AktuellesTerminal?.ProcessId; int vorherAnzahl = cmbTerminal.Items.Count; TerminalsNeuEinlesen(vorher); if (cmbTerminal.Items.Count > vorherAnzahl) { // Das neu gestartete MT5 auswählen. var bekanntePid = vorher; int ziel = cmbTerminal.Items.Count - 1; if (bekanntePid.HasValue) { for (int i = 0; i < cmbTerminal.Items.Count; i++) { var t = (TerminalInfo)cmbTerminal.Items[i]; if (t.ProcessId != bekanntePid.Value) ziel = i; } } cmbTerminal.SelectedIndex = ziel; charts.Clear(); ListeNeuZeichnen(); LadeReihenfolge(); AktualisierenAutomatisch(); lblStatus.Text = $"{AktuellesTerminal?.Name}: Konto hinzugefügt."; } else { lblStatus.Text = "Kein weiteres laufendes MT5 gefunden. Neues Konto/MT5 zuerst starten."; } }; btnSave.Click += (_, _) => { SpeichereReihenfolge(); lblStatus.Text = $"Reihenfolge für {AktuellesTerminal?.Name ?? "MT5"} gespeichert."; }; btnOpen.Click += (_, _) => Oeffnen(); btnUp.Click += (_, _) => Verschieben(-1); btnDown.Click += (_, _) => Verschieben(+1); lst.DoubleClick += (_, _) => Oeffnen(); // Linke Maustaste gedrückt halten -> Chart ziehen -> loslassen. lst.MouseDown += (_, e) => { if (e.Button != MouseButtons.Left) return; dragStartIndex = lst.IndexFromPoint(e.Location); dragStartPoint = e.Location; dragLaeuft = false; }; lst.MouseMove += (_, e) => { if (e.Button != MouseButtons.Left || dragStartIndex < 0) return; if (!dragLaeuft) { Size dragSize = SystemInformation.DragSize; var dragRect = new Rectangle( dragStartPoint.X - dragSize.Width / 2, dragStartPoint.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height); if (dragRect.Contains(e.Location)) return; dragLaeuft = true; } int ziel = lst.IndexFromPoint(e.Location); // Unterhalb des letzten Eintrags = ans Ende ziehen. if (ziel < 0 && e.Y >= 0) ziel = charts.Count - 1; if (ziel < 0 || ziel >= charts.Count || ziel == dragStartIndex) return; string bewegt = charts[dragStartIndex]; charts.RemoveAt(dragStartIndex); charts.Insert(ziel, bewegt); dragStartIndex = ziel; ListeNeuZeichnen(); lst.SelectedIndex = ziel; }; lst.MouseUp += (_, e) => { if (e.Button == MouseButtons.Left && dragLaeuft) { SpeichereReihenfolge(); lblStatus.Text = "Neue Reihenfolge gespeichert."; } dragStartIndex = -1; dragLaeuft = false; }; cmbTerminal.SelectedIndexChanged += (_, _) => { if (terminalWechselLaeuft) return; charts.Clear(); ListeNeuZeichnen(); LadeReihenfolge(); AktualisierenAutomatisch(); }; } private static void StyleButton(Button b, string caption, Color bg, Color fg) { b.Text = caption; b.FlatStyle = FlatStyle.Flat; b.FlatAppearance.BorderSize = 1; b.FlatAppearance.BorderColor = Color.FromArgb(75, 76, 82); b.FlatAppearance.MouseOverBackColor = Color.FromArgb(60, 61, 67); b.FlatAppearance.MouseDownBackColor = Color.FromArgb(72, 73, 80); b.BackColor = bg; b.ForeColor = fg; b.Cursor = Cursors.Hand; } private void TerminalsNeuEinlesen(uint? bevorzugtePid = null) { var gefunden = FindeAlleMt5Terminals(); uint? vorher = bevorzugtePid ?? AktuellesTerminal?.ProcessId; terminalWechselLaeuft = true; try { cmbTerminal.Items.Clear(); foreach (var t in gefunden) cmbTerminal.Items.Add(t); int index = -1; if (vorher.HasValue) { for (int i = 0; i < cmbTerminal.Items.Count; i++) { if (((TerminalInfo)cmbTerminal.Items[i]).ProcessId == vorher.Value) { index = i; break; } } } if (index < 0 && cmbTerminal.Items.Count > 0) { // FTMO zuerst, falls vorhanden; sonst erstes Terminal. for (int i = 0; i < cmbTerminal.Items.Count; i++) { if (((TerminalInfo)cmbTerminal.Items[i]).Name.StartsWith("FTMO", StringComparison.OrdinalIgnoreCase)) { index = i; break; } } if (index < 0) index = 0; } if (index >= 0) cmbTerminal.SelectedIndex = index; } finally { terminalWechselLaeuft = false; } } private void AktualisierenAutomatisch() { IntPtr dialog = IntPtr.Zero; try { lblStatus.Text = "Lese Charts aus MT5 ..."; Application.DoEvents(); if (!OeffneFensterWaehlenAutomatisch(out dialog, out IntPtr list, out _)) { lblStatus.Text = "MT5 bzw. „Fenster wählen“ konnte nicht automatisch geöffnet werden."; return; } List aktuell = LeseAlleEintraege(list); var neu = new List(); foreach (string gespeichert in charts) { int pos = aktuell.FindIndex(x => GleicherChart(x, gespeichert)); if (pos >= 0) { neu.Add(aktuell[pos]); aktuell.RemoveAt(pos); } } // Neu geöffnete Charts ans Ende. neu.AddRange(aktuell); charts.Clear(); charts.AddRange(neu); ListeNeuZeichnen(); SpeichereReihenfolge(); lblStatus.Text = $"{charts.Count} Charts aus {AktuellesTerminal?.Name ?? "MT5"} gelesen."; } catch (Exception ex) { lblStatus.Text = "Fehler: " + ex.Message; } finally { if (dialog != IntPtr.Zero) SendMessage(dialog, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } } private void Verschieben(int delta) { int i = lst.SelectedIndex; if (i < 0) return; int n = i + delta; if (n < 0 || n >= charts.Count) return; (charts[i], charts[n]) = (charts[n], charts[i]); ListeNeuZeichnen(); lst.SelectedIndex = n; SpeichereReihenfolge(); lblStatus.Text = "Eigene Reihenfolge gespeichert. MT5 blieb unverändert."; } private void Oeffnen() { int index = lst.SelectedIndex; if (index < 0 || index >= charts.Count) { MessageBox.Show("Bitte zuerst einen Chart auswählen."); return; } string ziel = charts[index]; IntPtr dialog = IntPtr.Zero; bool aktiviert = false; try { lblStatus.Text = $"{Kurzname(ziel)} wird aktiviert ..."; Application.DoEvents(); if (!OeffneFensterWaehlenAutomatisch(out dialog, out IntPtr list, out IntPtr activate)) { lblStatus.Text = "MT5 bzw. „Fenster wählen“ konnte nicht automatisch geöffnet werden."; return; } List aktuell = LeseAlleEintraege(list); int mt5Index = aktuell.FindIndex(x => GleicherChart(x, ziel)); if (mt5Index < 0) { lblStatus.Text = "Chart nicht mehr geöffnet. Bitte Charts aktualisieren."; return; } SetListViewSelection(list, mt5Index); SendMessage(list, LVM_ENSUREVISIBLE, (IntPtr)mt5Index, IntPtr.Zero); // MT5-eigenen Aktivieren-Button auslösen. SendMessage(activate, BM_CLICK, IntPtr.Zero, IntPtr.Zero); aktiviert = true; Application.DoEvents(); System.Threading.Thread.Sleep(80); // Falls MT5 den Dialog nicht selbst geschlossen hat, schließen wir ihn. if (AktuellesTerminal != null && FindeMt5FensterDialog(AktuellesTerminal.ProcessId, out IntPtr restDialog, out _, out _)) SendMessage(restDialog, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); lblStatus.Text = $"{Kurzname(ziel)} in MT5 aktiviert."; } catch (Exception ex) { lblStatus.Text = "Fehler: " + ex.Message; } finally { // Falls MT5 den Dialog durch "Aktivieren" nicht selbst geschlossen hat. if (!aktiviert && dialog != IntPtr.Zero) SendMessage(dialog, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } } private void SetListViewSelection(IntPtr list, int index) { GetWindowThreadProcessId(list, out uint pid); IntPtr process = OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, pid); if (process == IntPtr.Zero) throw new Exception("MT5-Prozess konnte nicht geöffnet werden."); int size = Marshal.SizeOf(); IntPtr remote = IntPtr.Zero; try { remote = VirtualAllocEx( process, IntPtr.Zero, (UIntPtr)size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (remote == IntPtr.Zero) throw new Exception("Speicher konnte nicht reserviert werden."); // Zuerst Auswahl aller Einträge löschen. LVITEM clear = new() { stateMask = LVIS_SELECTED | LVIS_FOCUSED, state = 0 }; WriteStruct(process, remote, clear); SendMessage(list, LVM_SETITEMSTATE, (IntPtr)(-1), remote); // Dann genau den gewünschten Eintrag markieren. LVITEM select = new() { stateMask = LVIS_SELECTED | LVIS_FOCUSED, state = LVIS_SELECTED | LVIS_FOCUSED }; WriteStruct(process, remote, select); SendMessage(list, LVM_SETITEMSTATE, (IntPtr)index, remote); } finally { if (remote != IntPtr.Zero) VirtualFreeEx(process, remote, UIntPtr.Zero, MEM_RELEASE); CloseHandle(process); } } private void ListeNeuZeichnen() { int old = lst.SelectedIndex; lst.BeginUpdate(); lst.Items.Clear(); for (int i = 0; i < charts.Count; i++) lst.Items.Add($"{i + 1,2}. {Kurzname(charts[i])}"); lst.EndUpdate(); if (charts.Count > 0 && old >= 0) lst.SelectedIndex = Math.Min(old, charts.Count - 1); } private static string Kurzname(string full) { int colon = full.IndexOf(':'); return (colon >= 0 ? full[..colon] : full).Trim(); } private static bool GleicherChart(string a, string b) => string.Equals(Kurzname(a), Kurzname(b), StringComparison.OrdinalIgnoreCase); private void LadeReihenfolge() { try { if (!File.Exists(SaveFile)) return; charts.Clear(); charts.AddRange( JsonSerializer.Deserialize>(File.ReadAllText(SaveFile)) ?? new List()); } catch { charts.Clear(); } } private void SpeichereReihenfolge() { try { File.WriteAllText( SaveFile, JsonSerializer.Serialize(charts, new JsonSerializerOptions { WriteIndented = true })); } catch { } } private bool OeffneFensterWaehlenAutomatisch( out IntPtr dialog, out IntPtr list, out IntPtr activate) { TerminalInfo? terminal = AktuellesTerminal; if (terminal == null) { dialog = IntPtr.Zero; list = IntPtr.Zero; activate = IntPtr.Zero; return false; } // Nur den Dialog des ausgewählten MT5-Terminals verwenden. if (FindeMt5FensterDialog(terminal.ProcessId, out dialog, out list, out activate)) return WarteBisListeGefuellt(list); if (terminal.Hwnd == IntPtr.Zero) { dialog = IntPtr.Zero; list = IntPtr.Zero; activate = IntPtr.Zero; return false; } // Bewährter V7-Ablauf: ausgewähltes MT5 fokussieren -> ALT+W. SetForegroundWindow(terminal.Hwnd); Application.DoEvents(); System.Threading.Thread.Sleep(250); TasteMitAlt(VK_W); for (int i = 0; i < 80; i++) { Application.DoEvents(); System.Threading.Thread.Sleep(25); if (FindeMt5FensterDialog(terminal.ProcessId, out dialog, out list, out activate)) { if (WarteBisListeGefuellt(list)) return true; } } dialog = IntPtr.Zero; list = IntPtr.Zero; activate = IntPtr.Zero; return false; } private bool WarteBisListeGefuellt(IntPtr list) { int letzterCount = -1; int stabil = 0; for (int i = 0; i < 60; i++) { Application.DoEvents(); System.Threading.Thread.Sleep(25); int count = SendMessage( list, LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero).ToInt32(); if (count > 0 && count == letzterCount) { stabil++; if (stabil >= 3) return true; } else { letzterCount = count; stabil = 0; } } return false; } private static void TasteMitAlt(byte vk) { keybd_event(VK_MENU, 0, 0, UIntPtr.Zero); keybd_event(vk, 0, 0, UIntPtr.Zero); keybd_event(vk, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); } private static void Taste(byte vk) { keybd_event(vk, 0, 0, UIntPtr.Zero); keybd_event(vk, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); } private static string ErzeugeTerminalName(string titel, uint pid) { string broker = titel.Contains("FTMO", StringComparison.OrdinalIgnoreCase) ? "FTMO" : (titel.Contains("RLC", StringComparison.OrdinalIgnoreCase) || titel.Contains("RLCrates", StringComparison.OrdinalIgnoreCase) || titel.Contains("RLC rates", StringComparison.OrdinalIgnoreCase)) ? "RLC" : "MT5"; // MT5-Titel beginnen normalerweise mit der Kontonummer. var match = System.Text.RegularExpressions.Regex.Match(titel, @"^\s*(\d{4,})"); string konto = match.Success ? match.Groups[1].Value : ""; if (!string.IsNullOrWhiteSpace(konto)) return $"{broker} {konto}"; return broker == "MT5" ? $"MT5 {pid}" : broker; } private List FindeAlleMt5Terminals() { var result = new List(); EnumWindows((h, _) => { GetWindowThreadProcessId(h, out uint pid); try { using Process p = Process.GetProcessById((int)pid); if (!p.ProcessName.Equals("terminal64", StringComparison.OrdinalIgnoreCase) && !p.ProcessName.Equals("terminal", StringComparison.OrdinalIgnoreCase)) return true; } catch { return true; } string titel = HoleText(h); if (string.IsNullOrWhiteSpace(titel)) return true; // Nur typische MT5-Hauptfenster berücksichtigen. if (!titel.Contains("[") || !titel.Contains("]")) return true; string name = ErzeugeTerminalName(titel, pid); // Pro Prozess nur ein Hauptfenster. if (!result.Any(x => x.ProcessId == pid)) { result.Add(new TerminalInfo { Hwnd = h, ProcessId = pid, Name = name, Title = titel }); } return true; }, IntPtr.Zero); return result .OrderBy(x => x.Name.StartsWith("FTMO", StringComparison.OrdinalIgnoreCase) ? 0 : x.Name.StartsWith("RLC", StringComparison.OrdinalIgnoreCase) ? 1 : 2) .ThenBy(x => x.Name) .ToList(); } private IntPtr FindeMt5Hauptfenster() { IntPtr found = IntPtr.Zero; EnumWindows((h, _) => { GetWindowThreadProcessId(h, out uint pid); try { using Process p = Process.GetProcessById((int)pid); if (!p.ProcessName.Equals("terminal64", StringComparison.OrdinalIgnoreCase) && !p.ProcessName.Equals("terminal", StringComparison.OrdinalIgnoreCase)) return true; } catch { return true; } IntPtr menu = GetMenu(h); if (menu == IntPtr.Zero) return true; // Nicht irgendein Terminal-Fenster nehmen, sondern eines, // dessen Menü den gesuchten MT5-Befehl wirklich enthält. uint testCommandId; if (SucheMenuBefehl(menu, "Fenster wählen", out testCommandId)) { found = h; return false; } return true; }, IntPtr.Zero); return found; } private bool SucheMenuBefehl(IntPtr menu, string suchtext, out uint commandId) { int count = GetMenuItemCount(menu); for (int i = 0; i < count; i++) { StringBuilder text = new(512); GetMenuString(menu, (uint)i, text, text.Capacity, MF_BYPOSITION); string name = BereinigeMenuText(text.ToString()); IntPtr sub = GetSubMenu(menu, i); if (sub != IntPtr.Zero) { if (SucheMenuBefehl(sub, suchtext, out commandId)) return true; } else { uint id = GetMenuItemID(menu, i); if (id != INVALID_MENU_ID && name.Contains(suchtext, StringComparison.OrdinalIgnoreCase)) { commandId = id; return true; } } } commandId = 0; return false; } private static string BereinigeMenuText(string text) { return text .Replace("&", "") .Replace("…", "") .Replace("...", "") .Trim(); } private bool FindeMt5FensterDialog( uint processId, out IntPtr dialog, out IntPtr list, out IntPtr activate) { dialog = IntPtr.Zero; list = IntPtr.Zero; activate = IntPtr.Zero; IntPtr foundDialog = IntPtr.Zero; IntPtr foundList = IntPtr.Zero; IntPtr foundActivate = IntPtr.Zero; EnumWindows((h, _) => { GetWindowThreadProcessId(h, out uint pid); if (pid != processId) return true; if (!HoleText(h).Equals("Fenster", StringComparison.OrdinalIgnoreCase)) return true; IntPtr localList = IntPtr.Zero; IntPtr localActivate = IntPtr.Zero; EnumChildWindows(h, (c, __) => { string cls = HoleKlasse(c); string txt = HoleText(c); if (cls.Equals("SysListView32", StringComparison.OrdinalIgnoreCase)) localList = c; if (cls.Equals("Button", StringComparison.OrdinalIgnoreCase) && txt.Equals("Aktivieren", StringComparison.OrdinalIgnoreCase)) localActivate = c; return true; }, IntPtr.Zero); if (localList != IntPtr.Zero && localActivate != IntPtr.Zero) { foundDialog = h; foundList = localList; foundActivate = localActivate; return false; } return true; }, IntPtr.Zero); dialog = foundDialog; list = foundList; activate = foundActivate; return dialog != IntPtr.Zero && list != IntPtr.Zero && activate != IntPtr.Zero; } private List LeseAlleEintraege(IntPtr list) { int count = SendMessage(list, LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero).ToInt32(); var result = new List(); for (int i = 0; i < count; i++) { string text = LeseListViewText(list, i); if (!string.IsNullOrWhiteSpace(text)) result.Add(text); } return result; } private string LeseListViewText(IntPtr listView, int index) { GetWindowThreadProcessId(listView, out uint pid); IntPtr process = OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, pid); if (process == IntPtr.Zero) throw new Exception("MT5-Prozess konnte nicht zum Lesen geöffnet werden."); const int chars = 1024; int itemSize = Marshal.SizeOf(); int textBytes = chars * 2; int total = itemSize + textBytes; IntPtr remote = IntPtr.Zero; try { remote = VirtualAllocEx( process, IntPtr.Zero, (UIntPtr)total, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (remote == IntPtr.Zero) throw new Exception("Speicher im MT5-Prozess konnte nicht reserviert werden."); IntPtr remoteText = IntPtr.Add(remote, itemSize); LVITEM item = new() { mask = LVIF_TEXT, iItem = index, iSubItem = 0, pszText = remoteText, cchTextMax = chars }; WriteStruct(process, remote, item); SendMessage(listView, LVM_GETITEMTEXTW, (IntPtr)index, remote); byte[] buffer = new byte[textBytes]; if (!ReadProcessMemory(process, remoteText, buffer, buffer.Length, out _)) throw new Exception("Chartname konnte nicht gelesen werden."); string text = Encoding.Unicode.GetString(buffer); int zero = text.IndexOf('\0'); if (zero >= 0) text = text[..zero]; return text; } finally { if (remote != IntPtr.Zero) VirtualFreeEx(process, remote, UIntPtr.Zero, MEM_RELEASE); CloseHandle(process); } } private static void WriteStruct(IntPtr process, IntPtr remote, T value) where T : struct { int size = Marshal.SizeOf(); byte[] bytes = new byte[size]; IntPtr local = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(value, local, false); Marshal.Copy(local, bytes, 0, size); if (!WriteProcessMemory(process, remote, bytes, bytes.Length, out _)) throw new Exception("Daten konnten nicht an MT5 übergeben werden."); } finally { Marshal.FreeHGlobal(local); } } private static string HoleText(IntPtr h) { StringBuilder sb = new(2048); GetWindowText(h, sb, sb.Capacity); return sb.ToString(); } private static string HoleKlasse(IntPtr h) { StringBuilder sb = new(512); GetClassName(h, sb, sb.Capacity); return sb.ToString(); } }