Author Topic: How To Incorporate a GUI in C  (Read 23215 times)

0 Members and 2 Guests are viewing this topic.

Offline bostonmanTopic starter

  • Super Contributor
  • ***
  • Posts: 2104
  • Country: us
How To Incorporate a GUI in C
« on: December 20, 2023, 04:11:48 am »
I have a question about C. Being aware of C and having done a few basic programs (i.e. I'm a novice), I asked someone about a very basic compiler that didn't require lots of setting up. He recommended GCC Compiler For Windows which seems to suit my needs well.

Unlike when I tried Visual Studio years ago, I don't need to change several settings and still get compiling issues for programs I know are correct. GCC seems to compile very easy and the few programs I've run compile without needing to wonder if a setting needs to be changed. It has a few drawbacks such as being command line based, having to type the program in Notepad++ , etc... but still, it's decent.

My question is: how can I incorporate a GUI into C?

From reading, I see gtk2-runtime-2.24.10-2012-10-10-ash is something that allows a GUI to be used with GCC, however, I'm not having much luck. I've entered a program the website provided, but get compiling errors.

Also, the reading I've done shows any available GUIs for C are very basic. If so, since GUIs are used in Windows (and Linux), does this mean C++ needs to be incorporated into a C program (as a library?) to have a nicer GUI?
 

Online ataradov

  • Super Contributor
  • ***
  • Posts: 11780
  • Country: us
    • Personal site
Re: How To Incorporate a GUI in C
« Reply #1 on: December 20, 2023, 04:50:05 am »
Anything that is not "basic" will take time to figure out. If you stop at "it gives me errors", you will not go far. Read the errors and figure what they mean, then fix them.

GTK is a full framework, it is big and complicated. For simpler things you can use something like ImGUI or even direct WinAPI calls.

GUIs always suck, there is no one "easy" solution, it all depends on your needs. This is why a lot of new software just uses Electron or similar web-based UIs.

Also, you are confusing IDEs and compilers. Visual Studio is an IDE and the compiler it uses is also command line. You can install any IDE that and use that with GCC. Eclipse is a common option, although more and more people move to VSCode.
« Last Edit: December 20, 2023, 04:54:20 am by ataradov »
Alex
 

Offline bostonmanTopic starter

  • Super Contributor
  • ***
  • Posts: 2104
  • Country: us
Re: How To Incorporate a GUI in C
« Reply #2 on: December 20, 2023, 05:25:13 am »
Quote
Anything that is not "basic" will take time to figure out. If you stop at "it gives me errors", you will not go far. Read the errors and figure what they mean, then fix them.

You're correct and I did devote time to working through them. What I meant was that I was spending more time trying to figure out Visual Studio than errors in my C program; or I was questioning whether it was the program or VS for compiling errors.

I am confusing IDEs and compilers for the most part, but I also thought they were a compliment of each other. As an example, I thought I can't use VS without using its compiler. I may be totally wrong, but getting back to not being able to figure out errors, VS seemed to compile my C programs as it would C++ (or maybe some other programming language), so it spit out errors. When I thought the settings were all correct, I would still get compiling errors even though I copied the programs from online or a book and somewhat gave up.

As for my intent with C, I've always had a desire to expand my knowledge, but find anything basic (like Hello World, performing math, or if statements) to be somewhat "mastered" while the more complicated ones get way more involved.

Years ago a co-worker gave me a development kit that used a micro on a thumbdrive. Apparently it involved the ability to program it in C. I never grasped the concept of how to write (I'm exchanging a bit here) "Hello World" onto an IC chip. I also thought this was jumping into the deep end too quickly. The times I've tinkered with C, I try a basic (maybe) for statement and expand on it. I run it and see what happens, expand on that, and see what happens.

I thought the idea of a basic compiler like GCC and a basic GUI may help visualize what is happening. One program I had in mind was to utilize my resistor collection.

I have several value resistors, and, when it comes time to needing a value I don't have, I begin looking into using different values in series/parallel to achieve the desired value. I thought of writing a program that will take all my values, and perform a series of calculations that would spit out a a combination based within a percentage of my needed value. As an example: I tell it to calculate based on three resistors, the program takes all the values I've listed, and calculates several in a series or parallel and a series/parallel combination until it comes within x% (a value I set) of the value I need.

While this doesn't need a GUI, and although I thought this program may be useful, I believe it's more about the method of performing the calculations rather than actually learning C, so I never pursued the idea. The GUI was something I thought would be cool to click a button and have it perform a step, expand on that, blah blah.



 

Online ataradov

  • Super Contributor
  • ***
  • Posts: 11780
  • Country: us
    • Personal site
Re: How To Incorporate a GUI in C
« Reply #3 on: December 20, 2023, 05:50:19 am »
As an example, I thought I can't use VS without using its compiler.
Well, yes, VS is specifically designed for one compiler. But you can use the compiler on its own without the VS.

I would still get compiling errors even though I copied the programs from online or a book and somewhat gave up.
C is not some magic universal language. If you copy some example for Linux, it is mot likely to compile on Windows. You may also be missing some libraries.

I thought the idea of a basic compiler like GCC and a
GCC is not a "basic" compiler. It is literally one of the leading compilers currently available.


Long story short - read the errors. You can't "think" your way though correctness of compiler settings. If something does not compile,  you have something setup incorrectly. Or the code is just broken.

For quick and simple GUIs, ImGUI is a decent option and it is relatively easy to get working. It is a bit non-traditional compared to other frameworks, but it does work and there is a number of complex applications using it.
Alex
 

Offline gmb42

  • Frequent Contributor
  • **
  • Posts: 302
  • Country: gb
Re: How To Incorporate a GUI in C
« Reply #4 on: December 20, 2023, 11:25:13 am »
Somewhat off-topic, for some time Visual Studio has been able to use Clang for compilation, especially with Linux projects.

It's an option in the VS installer.

How well it all works together I don't know.
 

Offline Warhawk

  • Frequent Contributor
  • **
  • Posts: 834
  • Country: 00
    • Personal resume
Re: How To Incorporate a GUI in C
« Reply #5 on: December 20, 2023, 11:30:53 am »
I like the answer that "GUIs always suck" because it is true  :-DD
Not sure if this helps but some weeks ago I had to create a GUI for a reference design. Something that sends commands over CAN from windows-based PC. Python turned out to be quite practical and multi-platform.
I am not sure how complex your GUI is going to be but python can be "quick and dirty". Good luck.

Online nctnico

  • Super Contributor
  • ***
  • Posts: 28101
  • Country: nl
    • NCT Developments
Re: How To Incorporate a GUI in C
« Reply #6 on: December 20, 2023, 11:47:54 am »
I have a question about C. Being aware of C and having done a few basic programs (i.e. I'm a novice), I asked someone about a very basic compiler that didn't require lots of setting up. He recommended GCC Compiler For Windows which seems to suit my needs well.

Unlike when I tried Visual Studio years ago, I don't need to change several settings and still get compiling issues for programs I know are correct. GCC seems to compile very easy and the few programs I've run compile without needing to wonder if a setting needs to be changed. It has a few drawbacks such as being command line based, having to type the program in Notepad++ , etc... but still, it's decent.

My question is: how can I incorporate a GUI into C?

From reading, I see gtk2-runtime-2.24.10-2012-10-10-ash is something that allows a GUI to be used with GCC, however, I'm not having much luck. I've entered a program the website provided, but get compiling errors.

Also, the reading I've done shows any available GUIs for C are very basic. If so, since GUIs are used in Windows (and Linux), does this mean C++ needs to be incorporated into a C program (as a library?) to have a nicer GUI?
If you want to have your program to have a GUI, look into WxWidgets or QT. Forget about gtk as this is 1) difficult to work with and 2) results in emulated GUI elements which are crappy to use.
You'll need to use C++ with Wxidgets and Qt though but both also provide a lot of other features that take away difficulties when dealing with the OS and offer an easier way to get software written more quickly.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 
The following users thanked this post: 5U4GB

Offline T3sl4co1l

  • Super Contributor
  • ***
  • Posts: 22436
  • Country: us
  • Expert, Analog Electronics, PCB Layout, EMC
    • Seven Transistor Labs
Re: How To Incorporate a GUI in C
« Reply #7 on: December 20, 2023, 03:47:12 pm »
I've done, actually, *very* little win32 (or otherwise) GUI programming, directly in C(++)... so don't mind me too much here, but I do have *an* example online just for sake of introduction / discussion:
https://github.com/T3sl4co1l/raycast_win

Just opening a frame and getting a canvas object, setting up menus if applicable, etc., it's not too painful, but there's just a lot of parameters to these objects, and you have to go through EVERYTHING manually, declare all the objects, initialize, register them, write the callback functions, and register them, process notification/message objects... it's a lot of stuff to write out.  Most toolchains/libraries integrate a lot of that boilerplate for you, and many provide a default look and feel, which -- maybe you can take or leave it, but it puts your application into a certain style and feel and you can pick and choose your library in part based on that.

I've done a bit more in Java (which, gosh, that was quite some time ago, now..), which is a bit easier, and kinda maybe a bit more powerful, in that you have the layout managers and stuff handy, if you want to get something more flexible and nicer to use, active resizable etc.  And much of the init and boilerplate is done for you, and the object-oriented nature of Java at least is a strong fit for object-oriented GUIs (which is most of them, AFAIK?).  Of course, it's been decades since Java was "hot", and OOP is just one of many standard language features these days, so, this latter point is pretty unremarkable, buuuut, if you're talking doing it all in C, well, you need to write out all that OOP stuff yourself, and, keeping object-orientation in mind while writing in C can make that a bit easier to understand.

It's ever more complicated as time goes on, for example how desktop styling affects the title bar, frame, etc. (e.g. transparency in Aero (since Vista)), live resizing (I mean that's been around since what, "Plus!"?, but it's up to you how much you want to repaint when it is resized), desktop scaling, accessibility options, etc.  You can use a minimal subset of these, even old (potentially deprecated) APIs, there's a thousand mostly-equivalent ways to do anything you want -- but knowing which ones are best supported/recommended, easiest, and, just which ones are important to provide whatever accessibility / compatibility / etc. features you want to have -- you can read a book or three just to get started on that.  Or go a whole career working with it directly and still be finding new ways of using it.  So, depending on what you want, usability, support, look and feel, and stuff like portability, you may want to choose a library or whatever to handle most of the grunt work.

And yeah, a lot of these tools are available right there in the IDE, using Visual Studio or what have you; it's the go-to environment for this.  The main thing is looking up enough references/docs to make something useful.

Tim
Seven Transistor Labs, LLC
Electronic design, from concept to prototype.
Bringing a project to life?  Send me a message!
 

Offline chilternview

  • Regular Contributor
  • *
  • Posts: 189
  • Country: gb
Re: How To Incorporate a GUI in C
« Reply #8 on: December 20, 2023, 04:57:48 pm »
If you want to lean to create GUIs and use C++ then you could start with the free version of Visual C++. Sure it has a bit of an uphill learning curve at first, but it's not that bad and it has the best debugger around imho.

For GUI development, it really makes sense to use a crossplatform GUI toolkit - added to the fact that Microsoft stuff is truly horrible. Over 20 years ago I tried to use MFC for a gui, after months of tearing my hair out I discovered Qt, doing the same thing took only a few days. Qt has its own IDE, Qt Creator, but I find it slow and irritating to use so do most development work in Windows, with little or no changes to port to Linux/Mac.

 

Online ejeffrey

  • Super Contributor
  • ***
  • Posts: 3932
  • Country: us
Re: How To Incorporate a GUI in C
« Reply #9 on: December 20, 2023, 05:09:10 pm »
I've done basic GUIs in a few different frameworks in C, C++ and Python, and QT has been the easiest to set things up.  Creating a polished, easy to use and learn GUI is a lot of work for all but the most trivial applications.  But if you just want to throw a bunch of controls on a big canvas, Qt makes it pretty easy.
 

Offline madires

  • Super Contributor
  • ***
  • Posts: 8177
  • Country: de
  • A qualified hobbyist ;)
Re: How To Incorporate a GUI in C
« Reply #10 on: December 20, 2023, 06:33:01 pm »
A good IDE is Eclipse (it's a beast) for example, And for a cross-platform GUI framework I would recommend Qt too. Understanding a GUi framework takes as much effort as learning a new programming language. Often they come with a design tool to make things easier, but it can give you a headache if its output and your program's structure don't match.
 

Offline djsb

  • Frequent Contributor
  • **
  • Posts: 964
  • Country: gb
Re: How To Incorporate a GUI in C
« Reply #11 on: December 20, 2023, 06:56:21 pm »
I like BCX (BASIC to C translator) for code prototyping

https://www.bcxbasiccoders.com/

It uses the Windows API directly and works with several C compilers (PellesC (http://www.smorgasbordet.com/pellesc/), etc). It can create GUI and Console based programs.

It has a very helpful forum

https://bcxbasiccoders.com/smf/

HTH.
« Last Edit: December 20, 2023, 07:02:23 pm by djsb »
David
Hertfordshire, UK
University Electronics Technician, London, PIC16/18, CCS PCM C, Arduino UNO, NANO,ESP32, KiCad V8+, Altium Designer 21.4.1, Alibre Design Expert 28 & FreeCAD beginner. LPKF S103,S62 PCB router Operator, Electronics instructor. Credited KiCad French to English translator
 

Offline bostonmanTopic starter

  • Super Contributor
  • ***
  • Posts: 2104
  • Country: us
Re: How To Incorporate a GUI in C
« Reply #12 on: December 20, 2023, 07:13:45 pm »
Guess I'm trying to wrap my head around everything.

From my understanding, C is low level and very powerful meaning one can accomplish more because it's not a language built on top of a language.

Basic C is creating programs that display 'Hello World', perform math, etc... Now we came to an era where we have Windows and a GUI would be useful. Maybe I'm not understanding the feedback or I can't get my head wrapped around this, but does C have its own method of incorporating GUIs or does the only way exist by merging a C program with a IDE that offers a GUI interface?

Deviating a bit, what gets accomplished using C for microprocessors? I know at my old job we had a Software Engineer who ran four PCs and did line-by-line coding that eventually got burned onto EEPROMs. I can only assume the architecture of the EEPROM (or micro) would tell the user specic commands that would read/write and the SE would take those and incorporate them into the code to perform additional calculations eventually spewing results that get fed into other locations.

Is learning C by this method better than takin the initial baby steps of Hello World and/or a GUI based C program?
 

Offline magic

  • Super Contributor
  • ***
  • Posts: 7246
  • Country: pl
Re: How To Incorporate a GUI in C
« Reply #13 on: December 20, 2023, 07:19:24 pm »
C is low level so you will write plenty of code to get anything to show up and then some more for it not to crash within seconds.

Few GUI applications are written in C anymore.

If you want to learn C for purposes where C is actually useful or required (MCUs for instance), forget GUI.
If you want to build a simple GUI application easily, forget C. I have no idea what's used these days, when I was kid VisualBASIC was all the rage ;D
If you want to build a complex GUI application, forget "easily" :P
« Last Edit: December 20, 2023, 07:23:00 pm by magic »
 

Offline bostonmanTopic starter

  • Super Contributor
  • ***
  • Posts: 2104
  • Country: us
Re: How To Incorporate a GUI in C
« Reply #14 on: December 20, 2023, 07:38:12 pm »
Thinking out loud.... I guess maybe I want to learn C because it's powerful, but, at the same time, find the Kernigan and Ritchie approach to learning it to be less than exciting because the C programs don't do much except display results in a text format. It seems as if learning printf and if/then statements are just familiarizing yourself with C and something that is necessary for a school course rather than it being practical to something more useful.

As stated, other (easier) languages exist for achieving similar programs, so I'm really uncertain which area of C is best; I thought a GUI based program would be good but seems it's more trouble than it's worth since GUIs aren't done in C anymore.

Obviously I need much more education in C as I don't understand basic concepts and have more errors in my code than I do correct code, but I find that's the stuff that one improves on as time goes on due to encountering programming errors.

Maybe the question I should ask is whether C is still relevant today? I know this is a loaded question like asking a comic book reader who the best super hero is, but maybe I'm assuming C is still an important language to learn.

On a side note, I also think Assembly (mainly for the Commodore 64) would be cool to know too. I have done some Assembly years ago in college on a little thing that had a keypad and seven segment LCD. We'd enter commands and then it would display the result(s) from a memory location. I don' t remember what those were called, but I'm sure there are GUI based ones now rather than digging out one of those boxes.



 

Online ataradov

  • Super Contributor
  • ***
  • Posts: 11780
  • Country: us
    • Personal site
Re: How To Incorporate a GUI in C
« Reply #15 on: December 20, 2023, 07:52:28 pm »
Maybe the question I should ask is whether C is still relevant today?
  It depends. If you are making web sites - no, if you are programming embedded systems - yes.

If you have never programmed GUIs, you will have a lot of issue no matter the language. You just need to pick one and get as far as you can. If you give up at a first error, you will not get anything done with any language.

Qt is a nice framework (be careful with its licensing though). But it is not easy either. It is still easier than doing things from scratch in C or even with Gtk.
Alex
 

Offline shapirus

  • Super Contributor
  • ***
  • Posts: 1626
  • Country: ua
Re: How To Incorporate a GUI in C
« Reply #16 on: December 20, 2023, 09:04:27 pm »
C is a beautiful and powerful language. It is beginner-friendly, as long as you know how to make friends with it. If you can into C, then you can into everything (not without some learning, of course).

I would advise getting comfortable with writing small programs with console (aka command line) interface first.

Start with a simple "write line; read line" approach. Also learn to read from files and write to them.

Then, libreadline.

Then, console window-based libraries, e.g., ncurses, and there were modern more attractive alternatives -- I don't remember the names, maybe someone here does.

Only then, by the time you get comfortable with the language itself, you can expect to be able to approach GUI libraries with success.


What follows is much more of a personal opinion of mine than what I wrote before it.

Ditch Windows. It's not a programmer-friendly OS. Ditch everything that matches the "microsoft" or "visual" keywords. They won't give you the right start.
 

Online ejeffrey

  • Super Contributor
  • ***
  • Posts: 3932
  • Country: us
Re: How To Incorporate a GUI in C
« Reply #17 on: December 20, 2023, 10:41:09 pm »
Thinking out loud.... I guess maybe I want to learn C because it's powerful, but, at the same time, find the Kernigan and Ritchie approach to learning it to be less than exciting because the C programs don't do much except display results in a text format. It seems as if learning printf and if/then statements are just familiarizing yourself with C and something that is necessary for a school course rather than it being practical to something more useful.

Probably the vast majority of C programs just display output to the console or write to files.  It's so much easier to implement, lets you do the actual job you want to do, and is more easily scripted and automated.  So it's definitely a practical skill.

Quote
From my understanding, C is low level and very powerful meaning one can accomplish more because it's not a language built on top of a language.

It's low level, and that lets you do a lot of things efficiently because the language doesn't do a lot "extra" for you that you might not need or want.  ON the other hand, if you do need those things, you just have to do them yourself.  It is a relatively simple language, which makes it relatively easy to learn, but maybe harder to learn to use it well.

"not a language built on top of a language" doesn't really mean much.  Also, it's not a question of being able to "accomplish more" -- outside of specific low level hardware access which is important in small parts of an OS, you can do all the same things in pretty much any language that hasn't been deliberately sanboxed (like javascript).  C mostly stands out in it's ability (when used properly) to be very efficient, and also that it is basically the lowest common denominator for languages on modern systems.  Pretty much any programming language you choose will be able to support calling external C libraries, because it is so simple and basic.  But Java, C++, and Python support such different object oriented models that it is a lot harder to directly interface between them unless you restrict yourself to a C-like subset of their data models.  C is also the most widely ported language.  That doesn't mean your code is automatically portable, implementations diverge a lot, but you can write C code almost everywhere.


Quote
As stated, other (easier) languages exist for achieving similar programs, so I'm really uncertain which area of C is best; I thought a GUI based program would be good but seems it's more trouble than it's worth since GUIs aren't done in C anymore.

Embedded development is one of the biggest areas of use for C today.  It's used some in high performance computing although C++ is very common.  It's common in basic low-level libraries that need to be accessible from any language.  It's also pretty common in older software projects, especially UNIX based projects started in the early 90s or before) such as the Linux kernel, gcc, CPython. 
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 15439
  • Country: fr
Re: How To Incorporate a GUI in C
« Reply #18 on: December 21, 2023, 01:05:29 am »
There's a number (probably very large) of C GUI toolkits out there. GTK is one example that is "mainstream" (outside of the Windows world). If you have already developed GUI programs with basic OS APIs (such as Windows API or macOS, etc), it'll be kinda familiar, but still with a learning curve. I recommend looking at the documentation on the official site: https://www.gtk.org/docs/ . Also, you mentioned a pretty old version of GTK of not clear provenance. It's a recipe for head banging. If you go for GTK, I recommend reading the above docs and using MSYS2 if you're on Windows. It gives you a Linux-like environment that will make it much easier to use GTK (and follow the tutorials and examples): https://www.msys2.org/ . It has a package manager, everything can be installed from there with recent and working versions (dev tools, GTK libs, etc.) Recommended.

If you target Windows only, you could learn the Windows API. It's pretty straightforward, hasn't much changed in over 20 years *for the basic stuff*, and you'll find a ton of material. In pure C.

You also have FLTK, which is a bit dated but worth a shot if you don't know where to start and GTK looks too intimidating: https://www.fltk.org/index.php

Much more out there. Most of course has a learning curve, so don't expect a quick and dirty path to GUIs, but it's all quite usable.
 

Offline tellurium

  • Frequent Contributor
  • **
  • Posts: 274
  • Country: ua
Re: How To Incorporate a GUI in C
« Reply #19 on: December 29, 2023, 12:23:06 am »
Did anyone mention Web UI?

By incorporating a web server into your C program, you can easily create a Web UI - and a very modern, appealing, sophisticated one.

Or, you could incorporate a headless browser directly into your program, and again - make a web UI! Look at these repos:

https://github.com/webview/webview
https://github.com/webview/lorca

Be cool. Forget about those outdated desktop UI toolkits.
Open source embedded network library https://github.com/cesanta/mongoose
TCP/IP stack + TLS1.3 + HTTP/WebSocket/MQTT in a single file
 
The following users thanked this post: Warhawk

Offline Zipdox

  • Regular Contributor
  • *
  • Posts: 204
  • Country: nl
Re: How To Incorporate a GUI in C
« Reply #20 on: March 07, 2024, 10:32:00 pm »
GTK 3 really isn't that hard.

Here's a quadratic equation solver I wrote. It's quite a few lines but the solver is most of it.
main.c
Code: (c) [Select]
#include <gtk/gtk.h>
#include <math.h>

GtkWidget *a_input;
GtkWidget *b_input;
GtkWidget *c_input;

GtkWidget *d_label;
GtkWidget *x1_label;
GtkWidget *x2_label;

void solve(){
    const char *a_text = gtk_entry_get_text(GTK_ENTRY(a_input));
    const char *b_text = gtk_entry_get_text(GTK_ENTRY(b_input));
    const char *c_text = gtk_entry_get_text(GTK_ENTRY(c_input));

    char *endptr;
    double a = strtod(a_text, &endptr);
    double b = strtod(b_text, &endptr);
    double c = strtod(c_text, &endptr);

    double d, x1, x2;
    char *d_text, *x1_text, *x2_text;

    if(a != 0.0){
        d = pow(b, 2.0) - 4.0 * a * c;

        d_text = g_strdup_printf("d: %f", d);
        gtk_label_set_text(GTK_LABEL(d_label), d_text);
        g_free(d_text);

        if(d >= 0.0){
            if(abs(d) == 0.0){
                x1 = (-b   sqrt(d)) / (2.0 * a);
                x1_text = g_strdup_printf("x: %f", x1);
                gtk_label_set_text(GTK_LABEL(x1_label), x1_text);
                g_free(x1_text);
            }else{
                x1 = (-b   sqrt(d)) / (2.0 * a);
                x2 = (-b - sqrt(d)) / (2.0 * a);
                x1_text = g_strdup_printf("x1: %f", x1);
                x2_text = g_strdup_printf("x2: %f", x2);
                gtk_label_set_text(GTK_LABEL(x1_label), x1_text);
                gtk_label_set_text(GTK_LABEL(x2_label), x2_text);
                g_free(x1_text);
                g_free(x2_text);
            }
        }else{
            gtk_label_set_text(GTK_LABEL(x1_label), "No solution");
            gtk_label_set_text(GTK_LABEL(x2_label), NULL);
        }
    }else{
        gtk_label_set_text(GTK_LABEL(d_label), "No discriminant, it's a inear equation");

        double x1 = -c / b;
        x1_text = g_strdup_printf("x: %f", x1);
        gtk_label_set_text(GTK_LABEL(x1_label), x1_text);
        g_free(x1_text);

        gtk_label_set_text(GTK_LABEL(x2_label), NULL);
    }
}

void button_clicked(GtkButton *button, gpointer user_data){
    solve();
}

void enter_pressed(GtkEntry *button, gpointer user_data){
    solve();
}

int main(int argc, char *argv[]){
    gtk_init (&argc, &argv);
    GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(window), "Quadratic Solver");
    gtk_window_set_default_size(GTK_WINDOW(window), 280, 160);
    g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

    GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);

    GtkWidget *a_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
    GtkWidget *a_label = gtk_label_new("a: ");
    a_input = gtk_entry_new();
    g_signal_connect(G_OBJECT(a_input), "activate", G_CALLBACK(enter_pressed), NULL);
    gtk_box_pack_start(GTK_BOX(a_box), a_label, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(a_box), a_input, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(box), a_box, FALSE, FALSE, 0);

    GtkWidget *b_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
    GtkWidget *b_label = gtk_label_new("b: ");
    b_input = gtk_entry_new();
    g_signal_connect(G_OBJECT(b_input), "activate", G_CALLBACK(enter_pressed), NULL);
    gtk_box_pack_start(GTK_BOX(b_box), b_label, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(b_box), b_input, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(box), b_box, FALSE, FALSE, 0);

    GtkWidget *c_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
    GtkWidget *c_label = gtk_label_new("c: ");
    c_input = gtk_entry_new();
    g_signal_connect(G_OBJECT(c_input), "activate", G_CALLBACK(enter_pressed), NULL);
    gtk_box_pack_start(GTK_BOX(c_box), c_label, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(c_box), c_input, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(box), c_box, FALSE, FALSE, 0);

    GtkWidget *solve_button = gtk_button_new_with_label("Solve");
    g_signal_connect(G_OBJECT(solve_button), "clicked", G_CALLBACK(button_clicked), NULL);
    gtk_box_pack_start(GTK_BOX(box), solve_button, FALSE, FALSE, 0);

    d_label = gtk_label_new(NULL);
    gtk_box_pack_start(GTK_BOX(box), d_label, FALSE, FALSE, 0);
    x1_label = gtk_label_new(NULL);
    gtk_box_pack_start(GTK_BOX(box), x1_label, FALSE, FALSE, 0);
    x2_label = gtk_label_new(NULL);
    gtk_box_pack_start(GTK_BOX(box), x2_label, FALSE, FALSE, 0);

    gtk_container_add(GTK_CONTAINER(window), box);

    gtk_widget_show_all(window);

    gtk_main();
}
Makefile
Code: (make) [Select]
CC=gcc
FLAGS=`pkg-config --cflags gtk -3.0`
LIBS=`pkg-config --libs gtk -3.0` -lm

solver: main.c
$(CC) $(FLAGS) -o $@ $^ $(LIBS)

Here's a palindrome checker. Use uses Glade to make designing the UI easier.
main.c
Code: (c) [Select]
#include <gtk/gtk.h>

GtkBuilder *builder;
GtkWidget *window;
GtkEntry *word_input;
GtkWidget *ignore_special_characters;
GtkLabel *result_label;
GtkButton *test_button;

int is_letter_or_number(char character){
    if(character >= '0' && character <= '9') return 1;
    if(character >= 'A' && character <= 'Z') return 1;
    if(character >= 'a' && character <= 'z') return 1;
    return 0;
}

char lowercase(char letter){
    if(letter >= 'A' && letter <= 'Z') return letter   32;
    return letter;
}

int is_palindrome(const char *text, gboolean ignore_special_chars){
    int text_len = strlen(text);

    char *filtered_text = calloc(1, text_len   1);
    int j = 0;
    for(int i = 0; i < text_len; i  ){
        if(ignore_special_chars) if(!is_letter_or_number(text[i])) continue;
        filtered_text[j] = lowercase(text[i]);
        j  ;
    }

    int filtered_text_len = strlen(filtered_text);
    for(int i = 0; i < filtered_text_len; i  ){
        if(filtered_text[i] != filtered_text[filtered_text_len - 1 - i]){
            g_free(filtered_text);
            return 0;
        }
    }
    g_free(filtered_text);
    return 1;
}

void test(){
    const char *input_text = gtk_entry_get_text(word_input);
    gboolean ignore_special_chars = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(ignore_special_characters));

    if(is_palindrome(input_text, ignore_special_chars)){
        gtk_label_set_markup(result_label, "<span foreground='#00FF00'>Palindrome!</span>");
    }else
        gtk_label_set_markup(result_label, "<span foreground='#FF0000'>Not a palindrome.</span>");
}

void deleted(){
    gtk_label_set_text(result_label, NULL);
}

int main(){
    gtk_init(NULL, NULL);

    builder = gtk_builder_new_from_file("ui.glade");

    window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
    g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

    ignore_special_characters = GTK_WIDGET(gtk_builder_get_object(builder, "ignore_special_characters"));

    word_input = GTK_ENTRY(gtk_builder_get_object(builder, "word_input"));
    g_signal_connect(G_OBJECT(word_input), "activate", G_CALLBACK(test), NULL);
    g_signal_connect(G_OBJECT(word_input), "backspace", G_CALLBACK(deleted), NULL);
    g_signal_connect(G_OBJECT(word_input), "delete-from-cursor", G_CALLBACK(deleted), NULL);

    result_label = GTK_LABEL(gtk_builder_get_object(builder, "result_label"));

    test_button = GTK_BUTTON(gtk_builder_get_object(builder, "test_button"));
    g_signal_connect(G_OBJECT(test_button), "clicked", G_CALLBACK(test), NULL);

    gtk_widget_show_all(window);

    gtk_main();
}
ui.glade
Code: (xml) [Select]
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.38.2 -->
<interface>
  <requires lib="gtk " version="3.24"/>
  <object class="GtkWindow" id="window_main">
    <property name="can-focus">False</property>
    <property name="title" translatable="yes">Palindrome Test</property>
    <property name="default-width">280</property>
    <child>
      <object class="GtkBox">
        <property name="visible">True</property>
        <property name="can-focus">False</property>
        <property name="orientation">vertical</property>
        <child>
          <object class="GtkEntry" id="word_input">
            <property name="visible">True</property>
            <property name="can-focus">True</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkCheckButton" id="ignore_special_characters">
            <property name="label" translatable="yes">Ignore space and special characters</property>
            <property name="name">ignore_special_characters</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <property name="receives-default">False</property>
            <property name="halign">center</property>
            <property name="margin-start">4</property>
            <property name="margin-end">4</property>
            <property name="margin-top">4</property>
            <property name="margin-bottom">4</property>
            <property name="draw-indicator">True</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="test_button">
            <property name="label" translatable="yes">Test</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <property name="receives-default">True</property>
            <property name="margin-start">4</property>
            <property name="margin-end">4</property>
            <property name="margin-top">4</property>
            <property name="margin-bottom">4</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">2</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="result_label">
            <property name="visible">True</property>
            <property name="can-focus">False</property>
            <property name="margin-start">4</property>
            <property name="margin-end">4</property>
            <property name="margin-top">4</property>
            <property name="margin-bottom">4</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">3</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>
Makefile
Code: (make) [Select]
CC=gcc
FLAGS=`pkg-config --cflags gtk -3.0`
LIBS=`pkg-config --libs gtk -3.0` -lm

palindrome: main.c
$(CC) $(FLAGS) -o $@ $^ $(LIBS)

I suggest you install devhelp and libgtk-3-doc. I use it all the time to check the docs.
« Last Edit: March 09, 2024, 04:25:48 pm by Zipdox »
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 4538
  • Country: nz
Re: How To Incorporate a GUI in C
« Reply #21 on: March 07, 2024, 11:02:54 pm »
Did anyone mention Web UI?

By incorporating a web server into your C program, you can easily create a Web UI - and a very modern, appealing, sophisticated one.

Web UIs help to make layout easy, but they are also a pain.

I'd say that overall the easiest environment I've ever used to make UIs and interface them to high performance code is the NextStep / OS X line using Objective C and Interface Builder.

It's like two languages mixed together, with plain C/C++ for the computations, and SmallTalk-like Obj C calls for the UI.  There is a little bit of friction but overall it's I think a lot better than pure C++ stuff like Qt.

I haven't looked at this stuff for over a decade I guess. Is OpenStep / GNUStep practical for making UIs on Linux and Windows? I just looked and their "gorm" Interface Builder clone seems to be under active development still:

https://github.com/gnustep/apps-gorm

There is also open-source Swift. I haven't looked at it, have no idea what the UI story is for it on Linux and Windows. Cool language but it's not C.
« Last Edit: March 07, 2024, 11:23:08 pm by brucehoult »
 

Offline mariush

  • Super Contributor
  • ***
  • Posts: 5143
  • Country: ro
  • .
Re: How To Incorporate a GUI in C
« Reply #22 on: March 07, 2024, 11:38:29 pm »
For a more basic library, I'd suggest trying Dear Imgui : https://github.com/ocornut/imgui   wiki page here : https://github.com/ocornut/imgui/wiki

Otherwise... for something native to windows, I'd probably download the source code of a native application and see how the windows are created, menus added and so on.

For example, the first application that comes to mind is VirtualDub, a video editing application : https://virtualdub.sourceforge.net/
 

Offline Zipdox

  • Regular Contributor
  • *
  • Posts: 204
  • Country: nl
Re: How To Incorporate a GUI in C
« Reply #23 on: March 07, 2024, 11:43:45 pm »
For a more basic library, I'd suggest trying Dear Imgui : https://github.com/ocornut/imgui   wiki page here : https://github.com/ocornut/imgui/wiki
Personally I'm not a fan. It's C++, which is more complicated than C. It also doesn't integrate well with the desktop and themes.
 

Offline Psi

  • Super Contributor
  • ***
  • Posts: 10241
  • Country: nz
Re: How To Incorporate a GUI in C
« Reply #24 on: March 07, 2024, 11:50:45 pm »
Making a one-off GUI in C is not that hard.
The hard bit is making a "reconfigurable" GUI. One that is flexible so you can easily add new menus and items and controls later with almost zero effort.

The other hard bit is making a GUI that looks professional.

If it's just a one-off and not going to be maintained/upgraded you can simply load images from flash and sort of 'fake it".  e.g. make it look nice by designed all the menu screen images in photoshop instead of generating them on the fly in code

Basically, making a "good" GUI is like coding a new language but with the added complexity of it needing to look pretty :)
But you don't always need that, sometimes you just need it to be good enough.
« Last Edit: March 07, 2024, 11:56:28 pm by Psi »
Greek letter 'Psi' (not Pounds per Square Inch)
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf