С windows gui programming with

How can I do GUI programming in C? [closed]

I want to do Graphics programming in C. I had searched a lot about the compiler that provides a rich set of functions for doing GUI programming in C, but I couldn’t find anything.

Basically I want to draw buttons and then accept the choice from the user and take an appropriate action. It would be helpful if you can suggest a C compiler, or a library that I can add to my compiler. I am working on the Windows operating system.

Presently, I am using TURBO C compiler that does not support direct methods for creating buttons. Any help would be appreciated.

6 Answers 6

This is guaranteed to have nothing to do with the compiler. All compilers do is compile the code that they are given. What you’re looking for is a GUI library, which you can write code against using any compiler that you want.

Of course, that being said, your first order of business should be to ditch Turbo C. That compiler is about 20 years old and continuing to use it isn’t doing you any favors. You can’t write modern GUI applications, as it will only produce 16-bit code. All modern operating systems are 32-bit, and many are now 64-bit. It’s also worth noting that 64-bit editions of Windows will not run 16-bit applications natively. You’ll need an emulator for that; it’s not really going to engender much feeling of accomplishment if you can only write apps that work in a DOS emulator. 🙂

Microsoft’s Visual Studio Express C++ is available as a free download. It includes the same compiler available in the full version of the suite. The C++ package also compiles pure C code.

And since you’re working in Windows, the Windows API is a natural choice. It allows you to write native Windows applications that have access to the full set of GUI controls. You’ll find a nice tutorial here on writing WinAPI applications in C. If you choose to go with Visual Studio, it also includes boilerplate code for a blank WinAPI application that will get you up and running quickly.

If you really care about learning to do this, Charles Petzold’s Programming Windows is the canonical resource of the subject, and definitely worth a read. The entire Windows API was written in C, and it’s entirely possible to write full-featured Windows applications in C. You don’t need no stinkin’ C++.

That’s the way I’d do it, at least. As the other answers suggest, GTK is also an option. But the applications it generates are just downright horrible-looking on Windows.

EDIT: Oh dear. It looks like you’re not alone in wanting to write «GUI» applications using an antiquated compiler. A Google search turns up the following library: TurboGUI: A GUI Framework for Turbo C/C++:

If you’re another one of those poor people stuck in the hopelessly out-of-date Indian school system and forced to use Turbo C to complete your education, this might be an option. I’m loathe to recommend it, as learning to work around its limitations will be completely useless to you once you graduate, but apparently it’s out there for you if you’re interested.

Windows GUI C++ Programming

I want to learn C++ GUI programming using Visual Studio 2008. I’m not sure where to start though. I learned C++ in high school, but not GUI. I’ve been doing C# for about 3 years now and thats how I «learned» GUI programming. Now I want to learn how to write GUI’s without the use of the .NET framework, so where do I start?

7 Answers 7

MFC is almost outdated now. I would recommend to use WTL instead .

Well it is also not a good idea just to start programming for GUI in C++ when there are so many good frameworks available like QT cross platform framework.

Charles Petzold’s «Programming Windows 5th Edition» is the Bible for Windows programming.

Since you say you’ve been doing C# GUI programming for about 3 years, I’ll assume that means Windows Forms. One way to dip your toe in the water is to remember that WinForms is really just an object-oriented wrapper around user32 . So load up Reflector and take a look at the way some of the controls are implemented. You’ll see that these strange messages like WM_PAINT and WM_KEYDOWN are pumped to the WndProc of the various controls by Windows. In plain old Win32 or MFC programming, the same thing is still going on. Doing this will let you slowly peel back the layers of the onion; you’ll get a better feel for how Windows Forms works, too. From there, I’d recommend picking up Programming Windows by Petzold; it’s old, but the native APIs in Windows don’t move around that much. Have fun!

Читайте также:  Altera usb blaster driver windows

Some heretical opinions.

I wouldn’t recommend C++ for writing complex Windows GUIs — language/library combos like C# or Delphi are so much more productive. If you want to get into C++ programming I’d suggest using it to write a multi-threaded server of some sort — a simple Web server would do for starters.

And if you really want to understand the underlying Windows APIs, I think there is something to be said for writing a simple application (like, say, a simplified version of notebook) in C (not C++). You’ll only want to do it once, but you will learn a lot in the process.

And before anyone starts madly down-voting, let me say that I am a C++ programmer of over 20 years standing, and really love the language.

Универсальный GUI

Введение

В настоящее время любая современная мониторинговая система включает в себя прикладное программное обеспечение (ПО) для визуализации данных. Как правило, запуск этого ПО предполагает наличие рекомендуемой операционной системы (ОС), в большинстве своих случаев ОС компании Microsoft. Однако сейчас наблюдается тенденция использования кроссплатформенных средств для разработки ПО. В результате этого появляется возможность запуска готового программного продукта на разных ОС, включая и мобильные ОС.

Кроме того, в связи с бурным распространением интернета популярным направлением разработки ПО стала разработка веб-приложений или веб-сервисов. Веб-приложение является полезным дополнением к клиентской прикладной программе (приложению). Обычно веб-приложение даёт возможность удалённого использования мониторинговой системы. Это означает, что пользователь не привязан к месту расположения аппаратной части мониторинговой системы и может использовать её из любой точки мира, где есть рекомендуемое интернет-соединение. Важно заметить, что разработка веб-приложений в значительной степени отличается от разработки клиентских приложений и это в свою очередь создаёт некоторые проблемы. В частности, это проблема создания универсального графического интерфейса пользователя (GUI). Чтобы клиентское приложение и веб-приложение были реализованы в едином графическом стиле, необходимо приложить достаточно усилий как разработчику интерфейса клиентского приложения, так и разработчику интерфейса веб-приложения. В конечном счёте величина усилий одного или другого разработчика будет зависеть от того, интерфейс какого приложения будет задавать общий стиль.

Современные способы построения интерфейсов

Рассмотрим наиболее популярные в настоящий момент способы построения интерфейсов клиентских приложений на языке C++, как наиболее используемом для разработки ПО, для ОС Microsoft Windows (MS Windows) и ОС Linux. Главным средством разработки ПО для MS Windows является MS Visual Studio [1]. Эта интегрированная среда разработки (IDE) позволяет разрабатывать ПО на разных языках программирования, но основными языками, конечно, являются C++ и C#. Для разработки интерфейса приложения имеются два основных средства — Windows Forms (WinForms) и Windows Presentation Foundation (WPF). Большая часть существующих приложений для MS Windows разработана с использованием WinForms, однако с появлением более современных версий ОС (MS Windows 7, 8), система WPF становится более популярной. Кроме того, последние версии MS Visual Studio позволяют использовать язык разметки HTML5 для построения интерфейсов, близких по стилю к нативным веб-приложениям. Однако стоит заметить, что коммерческая лицензия MS Visual Studio является платной, как и лицензия MS Windows, что несомненно является недостатком для низкобюджетных проектах.

Если говорить о низкобюджетных проектах, то тут наиболее подходящим вариантом является ОС Linux. Помимо того, что большинство дистрибутивов этой ОС являются абсолютно бесплатными, в том числе и для коммерческого использования, также имеется ряд бесплатных средств для разработки качественного ПО для ОС Linux. Самым распространённым средством для разработки ПО на языке С++ является кроссплатформенный инструментарий Qt [2]. Важно подчеркнуть, что Qt позволяет разрабатывать приложения не только для ОС Linux, но и для MS Windows, Mac OS X, Android и других UNIX-подобных ОС. Разработчики Qt предлагают как бесплатную для коммерческого использования, так и платную лицензию с дополнительными возможностями. Но исходя из современной практики разработки ПО с помощью этого инструментария, бесплатной лицензии оказывается больше чем достаточно.

Если проводить аналогию с MS Visual Studio, то в Qt мы имеем IDE Qt Creator. Здесь альтернативой WinForms являются так называемые виджеты (Qt Widgets), а альтернатива для WPF — Qt Quick. Также в Qt Creator имеется возможность создания интерфейсов на основе HTML5. Но наиболее интересным модулем инструментария является встраиваемый веб-движок WebKit, который лежит в основе всех современных веб-браузеров. Подобный модуль имеется и в MS Visual Studio, но он имеет ряд ограничений, и тем более нас больше интересуют низкобюджетные средства, которые позволяют уменьшить издержки при создания программного продукта. Веб-движок — это ядро браузера, он отвечает за правильное отображения веб-страниц. Модуль Qt WebKit позволяет создавать интерфейс клиентского приложения с использованием техники разработки интерфейсов веб-приложений. В основе создания интерфейса веб-приложения лежит устоявшийся стек технологий. Он включает язык разметки HTML (HTML 4, 5), каскадные таблицы стилей (CSS 2, 3) и скриптовый язык JavaScript с богатым выбором дополнительных библиотек (каркасов). Отдельного внимания заслуживает тот факт, что скорость появления новых полезных каркасов для языка JavaScript стремительно растёт, а это делает разработку, насыщенных функционалом приложений, более быстрой и удобной.

Читайте также:  Установка виндовс 10 поверх линукс минт

Теперь решение проблемы создания универсального GUI лежит на поверхности, но это только на первый взгляд.

Традиционный способ: Qt WebKit + Qt-костыли

Рассмотрим традиционный способ создания универсального GUI с помощью модуля Qt WebKit на примере модуля визуализации данных системы акустического мониторинга, разрабатываемой в рамках кандидатской диссертационной работы [3]. Под системой акустического мониторинга подразумевается система, включающая аппаратную и программную части. Аппаратная часть системы состоит из сенсорной сети акустических датчиков, данные с которых обрабатываются на микроконтроллере и отправляются по какому-либо интерфейсу (UART, IEEE 802.X и др.) на персональный компьютер (ПК). Программная часть состоит из набора прикладных программ, работающих как на локальном ПК (клиентское ПО), так и на удалённом сервере (серверное ПО).

Традиционный метод подразумевает использование межпроцессного


Рис. 1. Традиционный метод реализации универсального GUI

взаимодействия по средствам встроенного механизма Qt. Здесь подразумевается взаимодействие между основной логикой клиентского приложения, изображённой на рис.1 как Обработчик данных, и GUI-элементом. Одним из недостатков такого подхода является то, что код для реализации GUI на языке JavaScript будет иметь специфические функции, которые будут актуальны только для клиентского Qt-приложения. Для серверного приложения, отвечающего за GUI, нужен будет другой, специфичный для серверной реализации, код. Например, в случае использования PHP-скрипта для реализации основной логики серверного приложения, понадобится реализация межпроцессного взаимодействия с помощью какой-либо другой технологии (AJAX или WebSocket). Отсюда следует ещё один недостаток, а именно использование дополнительного языка программирования для реализации основной логики серверного приложения и разработка нового алгоритма межпроцессного взаимодействия.

Более интересный подход: Qt WebKit + WebSocket

Для решения этих проблем предлагается новый метод, основанный на использования упомянутой выше технологии WebSocket. Суть метода заключается в том, чтобы унифицировать метод межпроцессного взаимодействия между основной логикой приложения и GUI, как на клиентской стороне, так и на серверной. В этом случае появляется возможность использования JavaScript кода для реализации универсального для обеих сторон GUI.


Рис. 2. Новый метод реализации универсального GUI

На рис. 2. видно, что теперь для межпроцессного взаимодействия, как для клиентской, так и для серверной части используется технология WebSocket. То есть теперь мы имеем один универсальный JavaScript код для разных приложений. В этом случае необходимым условием является серверное приложение, основная логика которого реализована с помощью Qt, на не совсем привычном для веб-разработчиков, языке C++. С одной стороны такой подход к реализации серверного приложения усложняет задачу для узкоспециализированного веб-разработчика. Но с другой стороны мы имеем универсальные части кода, которые позволяют нам сэкономить время на дублировании одних и тех по смыслу алгоритмов на разных языках. Важно также подчеркнуть, что для использования технологии WebSocket необходима дополнительная библиотека, которая имеется в интернете в свободном доступе или включается по умолчанию в более поздние версии Qt.


Рис. 3. Локальное (справа) и серверное (слева) приложения, запущенные на ОС Ubuntu 14.04

На рис. 3 приведён пример реализации нового метода создания универсального GUI для ОС Ubuntu 14.04. Как видно на рисунке, в конечном итоге мы получаем универсальный интерфейс, как для локального приложения, запущенного в качестве исполняемого файла ОС, так и для серверного приложения, запущенного в современном веб-браузере. Так как для разработки ПО используются кроссплатформенные инструменты, это позволяет говорить о простой переносимости программного продукта на другие ОС в будущем.

С windows gui programming with

Many programming languages bolster GUI improvement as one of the centrepieces of its language highlights. C has no such library connected to it like the string library, IO library, etc, that we every now and again use. This weakness opened the skyline for engineers to pick from a wide assortment of GUI library toolbox accessible in C. GTK+ is one of them. It represents GIMP (GNU Image Manipulation Program) Toolkit and can be utilized to program current GUI interfaces.

The beneficial thing about GTK+ is that it is steady, developed, and its starting point can be followed back to the past times of X Windows that structure the centre GUI arrangement of Linux today. GTK is completely written in C and the GTK+ programming that we regularly use in Linux is additionally written in C. The work area administrators, for example, GNOME and XFCE, likewise are manufactured utilizing GTK.

A GTK+ application isn’t limited to the Linux stage no one but; it very well may be ported to non-UNIX/Linux stages also.

Here, we will cling to the fundamental type of GTK+, which is its C avatar on the Linux stage. The official webpage to download GTK+ is https://www.gtk.org. The site contains API documentation, instructional exercises, and other Gnome libraries that are frequently utilized alongside GTK. Truth be told, GTK is based over libraries, for example,

  • ATK: This library provides help to create accessibility tools such as sticky keys, screen readers, etc.
  • Glib: It is a universally useful utility library that offers help for threads, dynamic loading, event loops, low-level data structures, etc.
  • GObject: This library gives full-featured object-oriented help in C, without utilizing C++. This library encourages the language binding made for different languages to give you simple access to C APIs.
  • GdkPixBuf: This library gives picture control capacities.
  • GDK (GIMP Drawing Toolkit): This is the designs library that gives low-level drawing capacities over Xlib.
  • Pango: This library helps in content and design rendering
  • Xlib: This library provides low-level graphics support for Linux system
Читайте также:  Элементы окна windows заголовок

When composing code with GTK, we regularly locate that a significant number of the primitive data types are prefixed with ‘g‘ as in

These data types guarantee that the code can be recompiled on any platform without rolling out any improvements. These data types are characterized in these libraries to help in making it platform-independent.

GUI programming inherent object-oriented in it which is the main issue. In this, a procedural worldview doesn’t fit consummately in this scheme. Thus, regardless of GTK being written in C, it gives object-oriented help through GObject. Note that this item arranged help has nothing to do with C++. C++ has its own GTK library, called gtkmm. GObject encourages a portion of the object-oriented principles, similar to polymorphism and inheritance with the assistance of macros. The following diagram illustrates the hierarchical relation.

GtkWindow inherits GtkBin, which itself is a child of GtkContainer; in this manner, an object of GtkWindow can call the function defined in GtkBin or GtkContainer. This is an example of object-oriented implementation in C by GTK.

GUI With GTK

Let us comprehend a couple of things from our first GTK code in C.

  • To start with, we incorporate the header file. This incorporates all the file one needs to make a GUI, including the Glib library.
  • Presently, we declare a pointer to GtkWidget, which is only a window for our situation. What’s more, another GtkWidget pointer will be the button. Review that GtkWidget is a top-level storage type for widgets in the hierarchy.
  • Next, we invoke gtk_init function to initialize the GTK+ libraries by passing the command line parameters of the main function.
  • All GTK+ applications are instated as such; it is an “absolute necessity” statement. It parses the command arguments line and returns back to the application. Accordingly, these parameters might be utilized to alter the run time conduct of the application.
  • Now, we create the window and the button.
  • The window type value GTK_WINDOW_TOPLEVEL implies that the window made will be a standard framed window. Other sort values might be GTK_WINDOW_POPUP, which implies a frameless dialogue window will be made.
  • When we make a window, it must be closable with the goal that the client should at any rate ready to close the application because of the client hitting the upper right close the window. This implies the window must have the option to react to an event (close event).
  • Like all windowing system, GTK+ additionally executes events and event handlers. Since the code that transmits the signal is interior to a specific object, we have to compose an interfacing callback function.
  • The organization of a regular callback function is:
  • The primary parameter represents the widget that produces the signal and the subsequent parameter is a void pointer that might be utilized for any reason. Along these lines, the callback function to deal with the close events of our window will be as per the following:
  • The function gtk_main_quit() shuts the application. Presently, we should interface the window object with the callback function.
  • Likewise, we make the callback function to deal with the button event and associate it with the button widget.
  • Since the button widget is contained inside the window, we should explicitly add it to the container.
  • Also, at long last, we show the widgets made in memory with the gtk_widget_show_all() function that takes a reference to the window we have made.
  • Finally, the gtk_main() function is summoned to begin the interactive procedure.
  • This is a key function on the grounds that ordinarily a C program ends in the wake of executing the last statement. Here, it passes the control of the program to GTK+ and stays away for the indefinite future until the gtk_main_quit event is activated by the client tapping the close button for our situation.

Below is the implementation of the above steps:

Оцените статью