как сделать кнопку «назад» в winforms C#?
-
Вопрос задан
-
1945 просмотров
1
комментарий
Подписаться
1
Простой
1
комментарий
Решения вопроса 1
@mindtester Куратор тега C#
http://iczin.su/hexagram_48
1 — сделать кнопку
2 — выпилить дизайн
3 — заточить код клика
.. а вы как хотели?
Пригласить эксперта
Ответы на вопрос 1
Делаете форму на ней кнопки назад вперёд добавляете список usercontrol создаёте в форме место где они показываются и всовываете из этого списка контрол. Ещё поищите wizard wizard pages там немного сложнее, но это рекомендованный путь.
UP
Был с телефона и не смог найти
https://docs.microsoft.com/en-us/windows/win32/con…
Собственно эти контролы часто используются, обертки на .NET довольно легко написать и получить нативное поведение
Ваш ответ на вопрос
Войдите, чтобы написать ответ
Похожие вопросы
-
Показать ещё
Загружается…
Минуточку внимания
Реклама
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Шаблоны обнаружения сервисов в Kubernetes
Mr. Docker 04.05.2025
Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .
Создаем SPA на C# и Blazor
stackOverflow 04.05.2025
Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .
Реализация шаблонов проектирования GoF на C++
NullReferenced 04.05.2025
«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .
C# и сети: Сокеты, gRPC и SignalR
UnmanagedCoder 04.05.2025
Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .
Создание микросервисов с Domain-Driven Design
ArchitectMsa 04.05.2025
Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .
Многопоточность в C++: Современные техники C++26
bytestream 04.05.2025
C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .
A generic class and two ToolStripSplitButtons provide navigational history, like in web browsers.
- Download source and demo project — 10.83 KB
Introduction
With controls that present large quantities of distinct items, providing a history of user’s selections might enhance user pleasure. Especially, since (s)he would be accustomed to this feature from the web browser experience. This article presents a History<T>
class, which is generic for the selected item, and works in conjunction with one or two ToolStripSplitButton
s to provide the feature.
Background
The class handles the functionality of the buttons, their appearance is not its responsibility. Updating the class with new selections is accomplished by assigning the current selection to the CurrentItem
property inside an appropriate SelectionChanged
event handler of the historized control. Internally, history is tracked by a generic LinkedList
, with the selected items as LinkedListNode
s. The ToolStripDropDownMenu
s are filled dynamically on their respective Opening
events. If an exact history is feasible, the default filtering of duplicates can be turned off. No fancy coding to further mention it here.
Public Interface
With the provided comments, I hope that the usage would be self-explanatory:
public sealed class History<T> : IDisposable where T : class { public event EventHandler<HistoryEventArgs<T>> GotoItem public delegate string GetHistoryMenuText(T item) public delegate Image GetHistoryMenuImage(T item) public History(ToolStripSplitButton back, ToolStripSplitButton forward, uint limitList) public T CurrentItem { get; set; } public void Clear() public bool AllowDuplicates { get; set; } public string GetHistoryMenuText MenuTexts { set; } public Image GetHistoryMenuImage MenuImages { set; } } public class HistoryEventArgs<T> : EventArgs { public HistoryEventArgs(T item) public T Item { get; } }
Using the Code
The provided demo shows the most simplistic use with a ListBox
. You might copy the ToolStripSplitButton
s to your own project. Here is a slightly elaborated example for a TreeView
, with support of menu images:
private TreeView treeView; private ToolStripSplitButton tssbBack; private ToolStripSplitButton tssbForward; private History<TreeNode> history; { history = new History<TreeNode>(tssbBack, tssbForward, 8); history.GotoItem += new EventHandler<HistoryEventArgs<TreeNode>>(history_GotoItem); history.MenuTexts = delegate(TreeNode node) { return node.Text; }; history.MenuImages = delegate(TreeNode node) { return treeView.ImageList != null && !string.IsNullOrEmpty(node.ImageKey) ? treeView.ImageList.Images[node.ImageKey] : null; }; } private void treeView_AfterSelect(object sender, TreeViewEventArgs e) { history.CurrentItem = treeView.SelectedNode; } private void history_GotoItem(object sender, HistoryEventArgs<TreeNode> e) { treeView.SelectedNode = e.Item; } protected override void Dispose(bool disposing) { if (disposing && history != null) { history.Dispose(); } base.Dispose(disposing); }
Last, but not the least, the item T
could be a custom class, exposing additional properties, like an absolute address that allows reloading of items which are not contained anymore in the current view.
Points of Interest
- Encapsulating buttons and classes by deriving from a
ToolStripControlHost
control. - Your comments, suggestions, and votes.
History
- February 2006: coded.
- April 2006: published.
- March 2008: Class constraint added and implements IDisposable.
-
#1
I am fairly new to VB.NET but did manage to pass all my college classes on the subject, in any event I am working on a project — actually my very first work-related project and I am having difficulties creating the necessary «Next» and «Back» button code on my forms.
My program is a questionnaire survey and will have three pages; however I need to give the survey taker the ability to move between the three pages by having a “Next” button on form 1; which I do have successfully working; a “Next” and “Back” button on form 2 and a “Back” and “Submit” button on form3. I can get the “Back” button on form2 to function, however it always leaves an instance of form 2 running. Ideally, I would like the program to close or hide form1 when clicking on the “Next” button to move to form2 and vice-versa when clicking on form2’s “Back” button to return to form1 – same scenario for the movement between form2 and form3. I am distraught at the thought of what I am going to do with the submit button.
If anybody can provide any suggestions or good websites that speak of multiple page navigation buttons, I’d be very appreciative. Furthermore, I can produce a compressed compilation of my current code if anyone is that open to assist.
TIA
-
#2
What you could do is use 3 groupbox controls and hide/show them with the next/back buttons
mzim
Well-known member
-
#3
or you could make a usercontrol and put a panel and your label questions attached to the panel. Simply just call the usercontrol and hide the other usercontrol.
-
#4
Thanks for the input everybody!
With the replies received I did manage to get the next & back buttons working properly….now on to the next Endeavour! (which I am sure I will be posting questions regarding).
How to create a back button using windows based desktop application
Answers (2)
Next Recommended Forum