I wrote a C++ program that could sendKey. the code is as Follows;

s.SendKeys(_T("{Enter}"));s.SendKeys(_T("{Enter}"));

this piece if code is inside a function.

Now, i need to access this method from a C code. When i added the includes, i get alot of errors. Some says, that you can't access C++ code from a C program. is this statement correct?

If so, Could someone tell me or give me a sample code to have key press in C. like what i did in C++.

I am new to C, google didn't help me, please help me solve this

Dani AI

Generated

Two practical routes will solve 's problem: (A) keep the existing C++ logic and expose a tiny C-style API for the C program to call, or (B) implement the keypress in plain C using the Win32 API. is correct that direct use of C++-only constructs from a C translation unit is not possible without a C-compatible interface; wrapping the needed functions in a small C ABI is the usual solution. That prevents C++ name mangling, but it does not remove other ABI/runtime issues (linker settings, C vs C++ runtimes, calling convention), so keep the wrapper minimal.

If avoiding cross-language linking is preferred, the Win32 API provides a simple, reliable way to synthesize keyboard events from C. The example below sends an Enter press and release using SendInput:

#include <windows.h>

void press_enter(void)
{
    INPUT i[2] = {0};
    i[0].type = INPUT_KEYBOARD;
    i[0].ki.wVk = VK_RETURN;
    i[1].type = INPUT_KEYBOARD;
    i[1].ki.wVk = VK_RETURN;
    i[1].ki.dwFlags = KEYEVENTF_KEYUP;
    SendInput(2, i, sizeof(INPUT));
}

Troubleshooting notes: SendInput targets the foreground session/window; it can fail against elevated or isolated processes (UAC/UIPI) or different desktops. For a specific window handle, PostMessage/SendMessage with WM_KEYDOWN/WM_KEYUP may be needed, but those behave differently than real keyboard hardware. If linking a C program to a C++ wrapper, compile the wrapper as C++ and produce a small DLL or object with plain C exports; link the C program against that output and ensure the same compiler/runtime or a stable ABI is used.

is this statement correct?

Nope, but there are caveats. You can't directly access C++-specific features without wrapping them in a C-compatible interface. This is done with the extern "C" construct to force C linkage and disable name mangling:

extern "C" void c_send_key(const char *key)
{
    // ...
}

In the C program, you can link to the C++ object file and call the function:

extern void c_send_key(const char *key);

int main(void)
{
    c_send_key("{Enter}");
    return 0;
}

Further reading.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.