I am using the following code to load a custom cursor for my program:
public static Cursor LoadCustomCursor(string path)
{
IntPtr hCurs = LoadCursorFromFile(path);
if (hCurs == IntPtr.Zero) throw new Win32Exception(-2147467259, "Key game file missing. Please try re-installing the game to fix this error.");
Cursor curs = new Cursor(hCurs);
// Note: force the cursor to own the handle so it gets released properly.
FieldInfo fi = typeof(Cursor).GetField("ownHandle", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(curs, true);
return curs;
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr LoadCursorFromFile(string path);
And then:
Cursor gameCursor = NativeMethods.LoadCustomCursor(@"C:/Users/User/Documents/Visual Studio 2015/Projects/myProj/myProj/Content/Graphics/Cursors/cursor_0.xnb");
Form gameForm = (Form)Control.FromHandle(Window.Handle);
I am wondering if this absolute path above will also work if the project folder is for example moved to D:/ partition or another folder on C:/? Can I do something like this:
string myStr = Assembly.GetExecutingAssembly().Location;
string output = myStr.Replace("bin\\Windows\\Debug\\myProj.exe", "Content\\Graphics\\Cursors\\cursor_0.xnb");
And use output
for the path of the cursor file? Is Assembly.GetExecutingAssembly().Location
dynamic (changes every time the program folder is moved)? Or is it always the same as when the project was built?
You can use Environment.CurrentDirectory
. Example:
string cursorPath = @"Content\Graphics\Cursors\cursor_0.xnb";
string output = Path.Combine(Environment.CurrentDirectory, cursorPath);
Environment.CurrentDirectory returns the full path of the current working directory and you can use @
to escape the literal \
all at once if you place it in front of the string.