diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md
index 590890f..762dd26 100644
--- a/CHANGELOG.en-US.md
+++ b/CHANGELOG.en-US.md
@@ -3,6 +3,8 @@
English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Before publishing a version, add a `## [VERSION]` section to **both** files: the workflow publishes the section matching the tag from each one and fails if either is missing.
## [Unreleased]
+### What's new
+- Desktop icons go back where they were after a session: changing the main display could make Windows reshuffle them. Console Mode saves their positions before touching the screens and puts them back a few seconds after the desk is restored. Toggle it in Settings → **Put desktop icons back in place** (on by default); it does nothing while **Auto arrange icons** is on. (#167)
## [1.7.0-alpha.2]
### What's new
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0cff8c..9900063 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,8 @@
Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CHANGELOG.en-US.md`. Antes de publicar uma versão, adicione uma seção `## [VERSÃO]` com o changelog daquela versão **nos dois arquivos**. O workflow publica as duas seções correspondentes à tag na mesma release e falha se faltar alguma.
## [Unreleased]
+### Novidades
+- Os ícones da área de trabalho voltam ao lugar depois da sessão: trocar a tela principal podia fazer o Windows embaralhá-los. O Console Mode salva a posição antes de mexer nas telas e os recoloca alguns segundos depois de restaurar a mesa. Liga e desliga em Ajustes → **Devolver os ícones da área de trabalho ao lugar** (ligado por padrão); não faz nada com **Organizar ícones automaticamente** ligado. (#167)
## [1.7.0-alpha.2]
### Novidades
diff --git a/docs/GUIDE.de-DE.md b/docs/GUIDE.de-DE.md
index 3a55462..ef431c2 100644
--- a/docs/GUIDE.de-DE.md
+++ b/docs/GUIDE.de-DE.md
@@ -27,6 +27,8 @@ Die Registerkarte **System** bietet dieselben Einstellungen wie der Desktopmodus
Bei der Rückkehr aus Big Picture schließt **Steam beim Zurückkehren zum PC in den Infobereich minimieren** das Client-Fenster, während Steam weiterläuft. Ist die Option aus, bleibt der Desktop-Client geöffnet. Steam-Fenster werden nicht angetastet, wenn ein Spiel läuft oder sich sein Zustand nicht prüfen lässt.
+Ein Wechsel des Hauptbildschirms kann Windows dazu bringen, die Desktopsymbole neu anzuordnen. **Desktopsymbole wieder an ihren Platz setzen** (standardmäßig an) speichert vor der Sitzung, wo sie liegen, und setzt sie nach der Wiederherstellung wieder dorthin. Ist auf dem Desktop **Symbole automatisch anordnen** aktiv, passiert nichts, weil Windows sie dann selbst anordnet.
+
## Lokale Steuerungs-API
`consolemode://`-Links werden abgeschickt, ohne auf eine Antwort zu warten. Werkzeuge, die eine Antwort brauchen, etwa ein Fernsteuerungs-Agent, der als Windows-Dienst läuft, oder ein Stream-Deck-Plugin, das anzeigt, ob der Konsolenmodus aktiv ist, können die Named Pipe `\\.\pipe\ConsoleMode.Control` nutzen, solange die App läuft: Eine JSON-Zeile senden, eine zurückbekommen.
diff --git a/docs/GUIDE.es-ES.md b/docs/GUIDE.es-ES.md
index 43cced6..9a6fbac 100644
--- a/docs/GUIDE.es-ES.md
+++ b/docs/GUIDE.es-ES.md
@@ -27,6 +27,8 @@ Abre la acción del atajo que quieras configurar, elige **Definir** o **Cambiar*
Al volver de Big Picture, **Enviar Steam a la bandeja al volver al PC** cierra la ventana del cliente y deja Steam en marcha. Con la opción desactivada, el cliente de escritorio se queda abierto. Las ventanas de Steam no se tocan si hay un juego en marcha o si no se puede comprobar su estado.
+Cambiar la pantalla principal puede hacer que Windows reordene los iconos del escritorio. **Devolver los iconos del escritorio a su sitio** (activado por defecto) guarda su posición antes de la sesión y los vuelve a colocar después de restaurar el escritorio. No hace nada si **Organizar iconos automáticamente** está activado en el escritorio, porque entonces Windows los coloca por sí mismo.
+
## API de control local
Los enlaces `consolemode://` se lanzan sin esperar respuesta. Las herramientas que necesitan una respuesta (un agente de control remoto que funciona como servicio de Windows, un plugin de Stream Deck que muestra si el modo consola está activo) pueden usar la canalización con nombre (named pipe) `\\.\pipe\ConsoleMode.Control` mientras la aplicación está abierta: envía una línea JSON y recibe otra.
diff --git a/docs/GUIDE.fr-FR.md b/docs/GUIDE.fr-FR.md
index 5060ac1..9612288 100644
--- a/docs/GUIDE.fr-FR.md
+++ b/docs/GUIDE.fr-FR.md
@@ -27,6 +27,8 @@ Ouvrez l'action de raccourci à configurer, choisissez **Définir** ou **Modifie
Au retour de Big Picture, **Réduire Steam dans la zone de notification au retour au PC** ferme la fenêtre du client tout en laissant Steam en marche. Si l'option est désactivée, le client de bureau reste ouvert. Les fenêtres de Steam ne sont pas touchées quand un jeu est en cours ou quand son état ne peut pas être vérifié.
+Changer d'écran principal peut amener Windows à mélanger les icônes du bureau. **Remettre les icônes du bureau à leur place** (activé par défaut) enregistre leur position avant la session et les remet en place une fois le bureau restauré. Sans effet si **Réorganiser automatiquement les icônes** est activé sur le bureau, car Windows les place alors lui-même.
+
## API de contrôle local
Les liens `consolemode://` s'envoient sans attendre de réponse. Les outils qui ont besoin d'une réponse (un agent de contrôle à distance qui tourne comme service Windows, un plugin Stream Deck qui indique si le mode console est actif) peuvent utiliser le canal nommé `\\.\pipe\ConsoleMode.Control` tant que l'application tourne : envoyez une ligne JSON, recevez-en une en retour.
diff --git a/docs/GUIDE.md b/docs/GUIDE.md
index f493c78..4b8774a 100644
--- a/docs/GUIDE.md
+++ b/docs/GUIDE.md
@@ -33,6 +33,8 @@ Open the shortcut action you want to configure, choose **Set** or **Change**, ho
When returning from Big Picture, **Send Steam to the tray when going back to the PC** closes the client window while keeping Steam running. With the option off, the desktop client is left open. Steam windows are left alone when a game is running or its state cannot be checked.
+Changing the main display can make Windows reshuffle the desktop icons. **Put desktop icons back in place** (on by default) saves where they are before the session and puts them back after the desk is restored. It does nothing when the desktop's **Auto arrange icons** is on, since Windows lays them out itself then.
+
## Local control API
`consolemode://` links fire and forget. Tools that need an answer — a remote-control agent running as a Windows service, a Stream Deck plugin showing whether console mode is on — can use the named pipe `\\.\pipe\ConsoleMode.Control` while the app is running: send one JSON line, get one back.
diff --git a/docs/GUIDE.pt-BR.md b/docs/GUIDE.pt-BR.md
index 8a9ce9e..b25d457 100644
--- a/docs/GUIDE.pt-BR.md
+++ b/docs/GUIDE.pt-BR.md
@@ -33,6 +33,8 @@ Abra a ação de atalho que deseja configurar, escolha **Definir** ou **Alterar*
Ao voltar do Big Picture, **Mandar a Steam para a bandeja ao voltar ao PC** fecha a janela do cliente e mantém a Steam em execução. Com a opção desligada, o cliente desktop fica aberto. As janelas da Steam são preservadas quando há jogo rodando ou não é possível verificar esse estado.
+Trocar a tela principal pode fazer o Windows embaralhar os ícones da área de trabalho. **Devolver os ícones da área de trabalho ao lugar** (ligado por padrão) salva a posição deles antes da sessão e os coloca de volta depois que a mesa é restaurada. Não faz nada quando **Organizar ícones automaticamente** está ligado na área de trabalho, porque aí o próprio Windows os arruma.
+
## API de controle local
Os links `consolemode://` não dão resposta. Ferramentas que precisam de uma — um agente de controle remoto rodando como serviço do Windows, um plugin de Stream Deck que mostra se o modo console está ligado — podem usar o named pipe `\\.\pipe\ConsoleMode.Control` com o app aberto: envie uma linha JSON e receba outra.
diff --git a/docs/GUIDE.ru-RU.md b/docs/GUIDE.ru-RU.md
index 9457df8..38a6f16 100644
--- a/docs/GUIDE.ru-RU.md
+++ b/docs/GUIDE.ru-RU.md
@@ -27,6 +27,8 @@
При возврате из Big Picture параметр **«Сворачивать Steam в область уведомлений при возврате к ПК»** закрывает окно клиента, но Steam продолжает работать. Если параметр выключен, клиент на рабочем столе остаётся открытым. Окна Steam не трогаются, если запущена игра или её состояние не удаётся проверить.
+При смене основного экрана Windows может перемешать значки рабочего стола. Параметр **«Возвращать значки рабочего стола на место»** (включён по умолчанию) запоминает их расположение перед сеансом и возвращает значки после восстановления рабочего места. Если на рабочем столе включено **«Упорядочить значки автоматически»**, параметр ничего не делает: Windows расставляет их сам.
+
## Локальный API управления
Ссылки `consolemode://` срабатывают без ответа. Инструменты, которым нужен ответ (агент удалённого управления, работающий как служба Windows, плагин Stream Deck, показывающий, включён ли режим консоли), могут использовать именованный канал `\\.\pipe\ConsoleMode.Control`, пока приложение запущено: отправьте одну строку JSON и получите одну в ответ.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 6129468..94bd52d 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -373,6 +373,17 @@ Pré-condições: pelo menos 3 telas (a TV desligada na mesa normal, mais duas t
- [ ] TV que já estava ligada (como tela estendida) antes da sessão: depois de voltar, ela continua ligada no mesmo lugar. Resultado: ______
- [ ] Se uma das telas originais não voltar (cabo solto): o log diz que a tela de jogo ficou ligada e o PC não fica sem imagem. Resultado: ______
+## Ícones da área de trabalho (issue #30)
+
+Pré-condições: área de trabalho com **Organizar ícones automaticamente** desligado (clique direito → Exibir) e ícones espalhados em lugares fáceis de reconhecer (alguns no meio da tela, um no canto direito); de preferência a TV não sendo a tela principal na mesa normal.
+
+- [ ] Ajustes → **Devolver os ícones da área de trabalho ao lugar** ligado (padrão): **Jogar agora** e **Voltar ao PC**: os ícones voltam exatamente onde estavam, mesmo que o Windows os tenha embaralhado durante a sessão. O log mostra `Ícones da área de trabalho: N posições salvas` e depois `… M reposicionados`. Resultado: ______
+- [ ] O retorno ao PC não fica mais lento: os ícones voltam alguns segundos depois da mesa, sem travar a janela. Resultado: ______
+- [ ] Um atalho criado na área de trabalho durante a sessão fica onde o Windows o pôs; um apagado durante a sessão não causa erro. Resultado: ______
+- [ ] Com a opção desligada (Ajustes e aba Sistema do modo Console): o log não mostra nada sobre ícones e nada é movido. Resultado: ______
+- [ ] Com **Organizar ícones automaticamente** ligado: o log mostra `organização automática ligada; posições não salvas` e o Windows arruma os ícones sozinho. Resultado: ______
+- [ ] Explorer reiniciado durante a sessão (Gerenciador de Tarefas → Reiniciar): voltar ao PC não trava nem dá erro. Resultado: ______
+
## Telas com código próprio (issue #91)
Pré-condições: 1.6 instalada por cima da 1.5, com a configuração da 1.5 (tela de jogo e telas a esconder escolhidas). Anote antes, na 1.5, como o mapa de telas aparece, para comparar.
diff --git a/src/ConsoleMode/Models/Models.cs b/src/ConsoleMode/Models/Models.cs
index 9a40c75..0a93825 100644
--- a/src/ConsoleMode/Models/Models.cs
+++ b/src/ConsoleMode/Models/Models.cs
@@ -78,6 +78,9 @@ public sealed class AppConfig
///
public bool CloseSteamOnRestore { get; set; } = true;
+ /// Put the desktop icons back where they were after the session (issue #30).
+ public bool RestoreDesktopIcons { get; set; } = true;
+
/// Enter console mode when a controller connects while the app is in the tray.
public bool AutoStartOnController { get; set; }
@@ -363,6 +366,8 @@ public sealed class ConsoleRuntimeState
public bool HdrTurnedOffByUser { get; set; }
public DateTime? SessionStartedAt { get; set; }
public string? BackupAudioId { get; set; }
+ /// The desktop icons read before the session; null when they aren't restored.
+ public List? DesktopIcons { get; set; }
}
public sealed class RtssBackup
diff --git a/src/ConsoleMode/Native/DesktopIcons.cs b/src/ConsoleMode/Native/DesktopIcons.cs
new file mode 100644
index 0000000..fbecfe6
--- /dev/null
+++ b/src/ConsoleMode/Native/DesktopIcons.cs
@@ -0,0 +1,263 @@
+using System.Runtime.InteropServices;
+using ConsoleMode.Services;
+
+namespace ConsoleMode.Native;
+
+///
+/// Reads and moves the desktop icons through the shell's own view of the desktop
+/// (IShellWindows → the desktop's IShellBrowser → IFolderView), the documented route instead of
+/// poking at Explorer's list view from another process (issue #30).
+/// Each call runs on its own STA thread: the shell objects live in Explorer and want one.
+///
+internal static class DesktopIcons
+{
+ /// Every icon and its position, or null when they can't be read or Windows arranges them itself.
+ public static List? Read() => OnSta(() =>
+ {
+ using var desktop = DesktopView.Open();
+ if (desktop is null) return null;
+ if (desktop.View.GetAutoArrange() == 0)
+ {
+ AppLog.Write("Ícones da área de trabalho: organização automática ligada; posições não salvas");
+ return null;
+ }
+ var icons = new List();
+ foreach (var (name, pidl) in desktop.Items())
+ {
+ if (desktop.View.GetItemPosition(pidl, out var point) == 0)
+ icons.Add(new DesktopIcon(name, point.X, point.Y));
+ }
+ return icons;
+ }, null);
+
+ /// Puts the given icons where they were. Returns how many moved, or -1 on failure.
+ public static int Move(IReadOnlyList icons) => OnSta(() =>
+ {
+ if (icons.Count == 0) return 0;
+ using var desktop = DesktopView.Open();
+ if (desktop is null || desktop.View.GetAutoArrange() == 0) return -1;
+ var wanted = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var icon in icons) wanted[icon.Name] = icon;
+
+ var moved = 0;
+ foreach (var (name, pidl) in desktop.Items())
+ {
+ if (!wanted.TryGetValue(name, out var icon)) continue;
+ var hr = desktop.View.SelectAndPositionItems(1, [pidl], [new Point { X = icon.X, Y = icon.Y }], SvsiPositionItem);
+ if (hr == 0) moved++;
+ }
+ return moved;
+ }, -1);
+
+ private static T OnSta(Func work, T fallback)
+ {
+ var result = fallback;
+ var thread = new Thread(() =>
+ {
+ try { result = work(); }
+ catch (Exception ex) { AppLog.Write($"Ícones da área de trabalho: {ex.Message}"); }
+ }) { IsBackground = true, Name = "DesktopIcons" };
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ if (thread.Join(TimeSpan.FromSeconds(10))) return result;
+ AppLog.Write("Ícones da área de trabalho: o Explorer não respondeu");
+ return fallback;
+ }
+
+ /// The desktop's folder view and folder; frees every shell object and item id it hands out.
+ private sealed class DesktopView : IDisposable
+ {
+ public IFolderView View { get; }
+ private readonly IShellFolder _folder;
+ private readonly List