I have written a small program which insert the value and its corresponding value into the Windows registry key.
Program is working fine but it is not inserting value and its corresponding value.
And one more thing when I run prog as an administrator RegSetValueEx() fails..but still inssert only the value not its data.
Please help for finding out the issue here.
My code is as follows..
#define WIN32_LEAN_AND_MEAN
#define WIN32_DEFAULT_LIBS
#ifndef _WIN32_WINNT
#define _WIN32_WINNT (0x0601)
#endif /* _WIN32_WINNT */
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <tchar.h>
#include <unistd.h>
#include <stdbool.h>
#include<string.h>
BOOL InstallRunOnStartup()
{
HKEY key;
long result;
BOOL ret = FALSE;
LPTSTR val=L"12as3d12";
LPTSTR a=L"zzz";
TCHAR szBuf[20];
result = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", NULL, KEY_WRITE | KEY_WOW64_64KEY | KEY_SET_VALUE , &key);
if (result == ERROR_SUCCESS)
{
printf("hi \n");
if (RegSetValueEx(key, a, 0, REG_SZ,(LPBYTE)val, (DWORD)(lstrlen(val)+1) == ERROR_SUCCESS)){
printf("success \n");
ret = TRUE;
}
RegCloseKey(key);
}
return ret;
}
int main()
{
InstallRunOnStartup();
getch();
}
Add your program to the following path in Windows XP:
C:\Documents and Settings\All Users\Start Menu\Programs\Startup
Did you try assigning LPBYTE(val) to a temp variable & using that?
RegSetValueEx expects the buffer in bytes & the number of bytes in that buffer.
If LPTSTR is defined as Unicode in your project, then lstrlen(val) will return the length of the string which is half the size of your byte array.
I tried a different program and it worked..
HKEY hMykey; //Handle to your key
DWORD pDWDisp; // Ignore for this
LONG lRes; // Test Success
char prog[] = "\"C:\\a.exe\""; //Key to launch
lRes = RegCreateKeyEx(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion\\run",
0,"Whatever",REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS ,
NULL,&hMykey,&pDWDisp); // Open a key for edit
if(lRes != ERROR_SUCCESS){
MessageBox(0,"Error opening key","",MB_OK);
return false;
//exit(0);// Shutdown on fail
}
lRes = RegSetValueEx(hMykey,"a",0,REG_SZ,
(LPBYTE)prog,strlen(prog)+1);// Add your key value
if(lRes != ERROR_SUCCESS){
MessageBox(0,"Error saving record","",MB_OK);
RegCloseKey(hMykey);
return false;
//exit(0);// Shutdown on fail
}
MessageBox(0,"Success!! Registry value recorded","",MB_OK);
RegCloseKey(hMykey);
return true;
Related
I made a program that captures every keystroke and prints it in the terminal. The problem is it is all in upper case and I can't figure how to do it properly. I can post the code if it is gonna help.
Main:
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <TestLibrary.h>
#pragma comment( lib, "user32" )
int main()
{
fun();
printf("Loading library\n");
HMODULE libHandle = LoadLibraryA("TestLibrary");
if (libHandle == NULL) printf("***ERROR*** loading library\n");
printf("Getting address of hook procedure\n");
HOOKPROC procAddress = (HOOKPROC)GetProcAddress(libHandle, "KeyboardProc");
if (procAddress == NULL) printf("***ERROR*** getting address\n");
printf("Installing hook\n");
HHOOK hook = SetWindowsHookEx(WH_KEYBOARD_LL, procAddress, libHandle, 0);
if (hook == NULL) printf("***ERROR*** installing hook\n");
printf("Entering message loop\n");
while (GetMessage(NULL, NULL, 0, 0));
}
DLL:
#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include "TestLibrary.h"
void fun()
{
printf("Program started\n");
}
LRESULT CALLBACK KeyboardProc(_In_ int code, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
if (wParam == WM_KEYDOWN)
{
PKBDLLHOOKSTRUCT tmp = (PKBDLLHOOKSTRUCT)lParam;
char c = MapVirtualKeyA(tmp->vkCode, 2);
if (tmp->vkCode == VK_RETURN)
printf("\n");
else if (tmp->vkCode == VK_BACK)
printf("\b \b");
else
printf("%c", c);
}
return CallNextHookEx(NULL, code, wParam, lParam);
MapVirtualKey[A]/[W]/[ExA]/[ExW] has a known broken behaviour.
The docs are lying you about MAPVK_VK_TO_CHAR or 2 mode. It is said:
The uCode parameter is a virtual-key code and is translated into an
unshifted character value in the low order word of the return value.
Dead keys (diacritics) are indicated by setting the top bit of the
return value. If there is no translation, the function returns 0.
But according to experiments and leaked Windows XP source code (in \windows\core\ntuser\kernel\xlate.c file) it contains different behaviour for 'A'..'Z' VKs (that are specifically not defined in Win32 API WinUser.h header and are equivalent to 'A'..'Z' ASCII chars):
case 2:
/*
* Bogus Win3.1 functionality: despite SDK documenation, return uppercase for
* VK_A through VK_Z
*/
if ((wCode >= (WORD)'A') && (wCode <= (WORD)'Z')) {
return wCode;
}
For other buttons it works as described. And this behavior is even more annoying considering that, for example for US English keyboard layout it returns:
VK_Q (0x51) -> `Q` (U+0051 Latin Capital Letter Q)
VK_OEM_PERIOD (0xbe) -> `.` (U+002E Full Stop)
But for Russian keyboard layout it returns:
VK_Q (0x51) -> `Q` (U+0051 Latin Capital Letter Q) <- here it should return `й` (U+0439 Cyrillic Small Letter Short I) according to docs
VK_OEM_PERIOD (0xbe) -> `ю` (U+044E Cyrillic Small Letter Yu)
Not sure why MS decided to pull this bug from Win 3.1 but current situation on my Windows 10 is like this.
As a workaround I can recommend you to use ToUnicode[Ex] API that can do this mapping for you:
wchar_t VkToChar(uint16_t vk, bool isShift = false)
{
uint16_t sc = MapVirtualKeyW(vk, MAPVK_VK_TO_VSC);
const uint32_t flags = 1 << 2; // Do not change keyboard state of this thread
static uint8_t state[256] = { 0 };
state[VK_SHIFT] = isShift << 7; // Modifiers set the high-order bit when pressed
wchar_t unicodeChar;
if (ToUnicode(vk, sc, state, &unicodeChar, 1, flags) != 1)
return L'\0';
if (!std::iswprint(unicodeChar))
return L'\0';
return unicodeChar;
}
Or even better: if you have Win32 message loop - just use TranslateMessage() (that calls ToUnicode() inside its code) and then process WM_CHAR message.
I'm trying to print ConsoleCursorInfo on my win7 sp1.
#include <windows.h>
#include <stdio.h>
int main(){
printf("xp SetConsoleCursorInfo\n");
CONSOLE_CURSOR_INFO *CURSOR;
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleCursorInfo(hStdout, CURSOR);
printf("%u",CURSOR->dwSize);
}
I built this code successfully with vs2019 build tools, though running it always crashes. How do I fix it?
There are several problems in your code.
This is your corrected code with comments:
#include <windows.h>
#include <stdio.h>
int main(){
printf("xp SetConsoleCursorInfo\n");
CONSOLE_CURSOR_INFO cursor; // we need a CONSOLE_CURSOR_INFO and not
// a pointer to CONSOLE_CURSOR_INFO
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if (GetConsoleCursorInfo(hStdout, &cursor)) // check if GetConsoleCursorInfo fails
// ^ and mind the & operator here
printf("%u",cursor.dwSize);
else
printf("GetConsoleCursorInfo failed with error %d\n", GetLastError());
}
I need to write a simple program that prints the name of the most recently modified file whose name starts with 0-9 in the current directory. So far I can get it to print the name of a file that starts with 0-9, but it fails to consistently print the one that was modified most recently. I have been stuck at this part and I am in very desperate need to figure this out. Any help or hints would be of much help! Thank you!
Below is my code:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
int main(void){
// Open the current directory
DIR* currDir = opendir("./");
struct dirent *aDir;
time_t lastModifTime;
struct stat dirStat;
int first_file_checked = 0;
char directoryName[256];
// Go through all the entries
while((aDir = readdir(currDir)) != NULL){
// only check on directories with a name that starts with 0-9
if (48 <= (int)aDir->d_name[0] && (int)aDir->d_name[0] <= 57) {
// Get meta-data for the current entry
stat(aDir->d_name, &dirStat);
// Use the difftime function to get the time difference between the current value of lastModifTime and the st_mtime value of the directory entry
if(first_file_checked == 0 || difftime(dirStat.st_mtime, lastModifTime) > 0){
lastModifTime = dirStat.st_mtime;
memset(directoryName, '\0', sizeof(directoryName));
strcpy(directoryName, aDir->d_name);
}
first_file_checked = 1;
}
}
// Close the directory
closedir(currDir);
printf("The last file/directory modified in the current directory is %s\n", directoryName);
return 0;
}
Works here:
BTW: you dont check for directories, you need to add a check for d_type to accomplish that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
int main(void){
// Open the current directory
DIR* currDir ;
struct dirent *aDir;
time_t lastModifTime;
struct stat dirStat;
int count ;
char thename[256] = "";
// Go through all the entries
currDir = opendir("./");
for(count=0; (aDir = readdir(currDir)) ; ){
int rc;
// only check on directories with a name that starts with 0-9
if (aDir->d_name[0] < '0' || aDir->d_name[0] > '9' ) continue;
// Get meta-data for the current entry
rc = stat(aDir->d_name, &dirStat);
if (rc < 0) continue; // check the return value!
if(!count++ || dirStat.st_mtime < lastModifTime ){
lastModifTime = dirStat.st_mtime;
strcpy(thename, aDir->d_name);
}
}
// Close the directory
closedir(currDir);
if (count) {
printf("%d files checked. The last file/directory modified in the current directory is %s(time=%u)\n"
, count, thename, (unsigned) lastModifTime);
}
else {
printf("No files/directories were found\n");
}
return 0;
}
I am making a program that downloads files to a windows. To do so i used urlmon and the urldownload to file function. Whenever i download a file with the function in question in my windows i only get a prefetch file, but i can't find the file on my hard drive. Please tell me what i am doing wrong?
#include <windows.h>
#include <stdio.h>
typedef HRESULT (WINAPI *UDTF)(LPVOID, LPCTSTR, LPCTSTR, DWORD, LPVOID);
int dl_url(char *url, char *path)
{
int q = 1;
HMODULE hDll;
UDTF URLDownloadToFile;
if((hDll = LoadLibrary("urlmon")))
{
if((URLDownloadToFile = (UDTF)GetProcAddress(hDll, "URLDownloadToFileA")))
{
if(URLDownloadToFile(0, url, path, 0, 0) == 0)
q = 0;
}
FreeLibrary(hDll);
}
return q;
}
Note: I use a 32 bit windows xp to test this program.
I am completing cs50x (the edX (free) version of the Harvard cs50) course and am trying to be a bit tricky/lazy/test myself.
I am trying to use a C program to create all the directories I will need for my psets.
I have looked online and found that <sys/stat.h> includes the mkdir() function and therefore tried creating some nested loops to create all the necessary folders by doing something similar to mkdir {pset1,pset1/{standard,hacker},pset2,pset2{standard... to give me a directory structure like this:
pset1/Standard
pset1/Hacker
pset2/Standard
etc...
I came up with this:
#include <cs50.h>
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, string argv[])
{
for(int i = 1; i <=8; i++)
{
string dir = argv[1];
sprintf(dir,"%s%i", argv[1], i);
mkdir(dir, 0777);
for(int j = 0; j<2; j++)
{
string subDir[] = {"Standard","Hacker"};
sprintf(dir,"%s%i/%s", argv[1], i, subDir[j]);
mkdir(dir, 0777);
}
}
}
However, the program only creates pset1 and completes, there are no subfolders, no pset2 etc.
Yes, you're being lazy since you seem to have very little knowledge of C, yet try to program in it. :)
C is not Python, there is no string interpolation/formatting operator. You have to call a function, specificially snprintf(). Read that manual page.
Also, you can't create a bunch of nested directories with a single call to mkdir(). Read the manual page.
To create nested directories, you're either going to have to build each's absolute path (i.e. each successive time you call mkdir() the path will be longer than the previous time), or actually enter each directory as you create it, and go from there.
To create a full path you can call mkdir() recursivly like this:
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
int mkdirr(const char * path, const mode_t mode, const int fail_on_exist)
{
int result = 0;
char * dir = NULL;
do
{
if (NULL == path)
{
errno = EINVAL;
result = -1;
break;
}
if ((dir = strrchr(path, '/')))
{
*dir = '\0';
result = mkdirr(path, mode, fail_on_exist);
*dir = '/';
if (result)
{
break;
}
}
if (strlen(path))
{
if ((result = mkdir(path, mode)))
{
char s[PATH_MAX];
sprintf(s, "mkdir() failed for '%s'", path);
perror(s);
if ((EEXIST == result) && (0 == fail_on_exist))
{
result = 0;
}
else
{
break;
}
}
}
} while (0);
return result;
}
And then call mkdirr() like this;
int main(void)
{
char p[] = "test/1/2/3";
if (-1 == mkdirr(p, 0777, 0))
{
perror("mkdirr() failed()");
}
return 0;
}